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.
Description: Know every rules,steps, guidance and be outstanding in JAVA programming language through the help of this eBook
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)
...
116
byte[] getBytes(String charsetName)
...
118
int hashCode()
...
120
int indexOf(int ch, int fromIndex)
...
123
int indexOf(String str, int fromIndex)
...
126
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)
...
139
String[] split(String regex)
...
141
boolean startsWith(String prefix)
...
144
CharSequence subSequence(int beginIndex, int endIndex)
...
146
String substring(int beginIndex, int endIndex)
...
148
String toLowerCase()
...
149
String toString()
...
151
String toUpperCase(Locale locale)
...
153
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:
...
174
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:
...
180
Example:
...
181
The Scope of Variables:
...
182
Example:
...
183
Example:
...
183
Variable Arguments(var-args):
...
184
The finalize( ) Method:
...
186
Byte Streams
...
187
Standard Streams
...
189
FileInputStream:
...
190
Example:
...
191
Example:
...
193
ByteArrayOutputStream
...
194
DataOutputStream
...
195
Example:
...
197
File Class
...
200
FileReader Class
...
201
FileWriter Class
...
202
Directories in Java:
...
203
Listing Directories:
...
205
Exception Hierarchy:
...
207
Catching Exceptions:
...
208
Multiple catch Blocks:
...
209
The throws/throw Keywords:
...
209
Example:
...
211
Example:
...
213
Java Inheritance
...
214
Example:
...
215
The instanceof Keyword:
...
216
Java Overriding
...
217
Rules for method overriding:
...
219
Java Polymorphism
...
220
Virtual Methods:
...
224
Abstract Class:
...
225
Abstract Methods:
...
228
Example:
...
229
TUTORIALS POINT
Simply Easy Learning
Java Interfaces
...
231
Example:
...
231
Implementing Interfaces:
...
232
Extending Multiple Interfaces:
...
233
Java Packages
...
234
Example:
...
235
Example:
...
236
Set CLASSPATH System Variable:
...
239
The Enumeration:
...
240
The BitSet
...
242
The Vector
...
246
The Stack
...
248
The Dictionary
...
249
Example:
...
251
Example:
...
253
Example:
...
256
The Collection Interfaces:
...
257
The Collection Algorithms:
...
259
Using Java Iterator
...
259
The Methods Declared by ListIterator:
...
260
How to use a Comparator?
...
261
The compare Method:
...
262
Example:
...
263
Java Generics
...
264
Example:
...
265
Example:
...
266
Example:
...
268
Serializing an Object:
...
269
Java Networking
...
271
URL Class Methods:
...
273
URLConnections Class Methods:
...
274
Socket Programming:
...
276
Socket Class Methods:
...
278
Socket Client Example:
...
279
Java Sending E-mail
...
281
Send an HTML E-mail:
...
284
User Authentication Part:
...
286
Life Cycle of a Thread:
...
287
Create Thread by Implementing Runnable Interface:
...
288
TUTORIALS POINT
Simply Easy Learning
STEP 2:
...
288
Example:
...
289
STEP 1
...
289
Example:
...
291
Example:
...
293
What is Thread synchronization?
...
294
Multithreading example with Synchronization:
...
297
Example:
...
299
Example:
...
300
Major thread operatios
...
301
Java Applet Basics
...
304
A "Hello, World" Applet:
...
305
Invoking an Applet:
...
307
Specifying Applet Parameters:
...
308
Event Handling:
...
310
Playing Audio:
...
313
What is Javadoc?
...
314
Example:
...
317
TUTORIALS POINT
Simply Easy Learning
1
CHAPTER
Java Overview
J
ava programming language was originally developed by Sun Microsystems which was initiated by James
Gosling and released in 1995 as core component of Sun Microsystems’ Java platform (Java 1
...
As of December 2008, the latest release of the Java Standard Edition is 6 (J2SE)
...
Ex: J2EE for
Enterprise Applications, J2ME for Mobile Applications
...
Java is
guaranteed to be Write Once, Run Anywhere
...
Java can be easily extended since it is based on the
Object model
...
This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform
it is being run
...
If you understand the basic concept of OOP,Java would be
easy to master
...
Authentication
techniques are based on public-key encryption
...
•
Portable: Being architectural-neutral and having no implementation dependent aspects of the
specification makes Java portable
...
•
Robust:Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time
error checking and runtime checking
...
This design feature allows developers to construct smoothly running interactive
applications
...
The development process is more rapid and analytical since the linking is an incremental and
lightweight process
...
•
Distributed:Java is designed for the distributed environment of the internet
...
Java programs can carry extensive amount of run-time information that can be
used to verify and resolve accesses to objects on run-time
...
The language, initially called Oak after an oak tree that stood outside Gosling's office, also went by the name
Green and ended up later being renamed as Java, from a list of random words
...
0 in 1995
...
On 13 November 2006, Sun released much of Java as free and open source software under the terms of the GNU
General Public License (GPL)
...
Tools you will need:
For performing the examples discussed in this tutorial, you will need a Pentium 200-MHz computer with a minimum
of 64 MB of RAM (128 MB of RAM recommended)
...
1 or Windows 95/98/2000/XP operating system
...
What is Next?
Next chapter will guide you to where you can obtain Java and its documentation
...
TUTORIALS POINT
Simply Easy Learning
2
CHAPTER
Java Environment Setup
B
efore we proceed further, it is important that we set up the Java environment correctly
...
Please follow the following steps to set up the
environment
...
So you download a version based on your operating
system
...
exe to install Java on your machine
...
•
Click on the 'Environment variables' button under the 'Advanced' tab
...
Example, if the path is
currently
set
to
'C:\WINDOWS\SYSTEM32',
then
change
your
path
to
read
'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'
...
bat'
file
and
add
'SET PATH=%PATH%;C:\Program Files\java\jdk\bin'
the
following
line
at
the
end:
Setting up the path for Linux, UNIX, Solaris, FreeBSD:
Environment variable PATH should be set to point to where the Java binaries have been installed
...
Example, if you use bash as your shell, then you would add the following line to the end of your '
...
There are even more sophisticated IDEs available in the
market
...
Netbeans:Is a Java IDE that is open-source and free which can be downloaded
fromhttp://www
...
org/index
...
Eclipse: Is also a Java IDE developed by the eclipse open-source community and can be downloaded
from http://www
...
org/
...
TUTORIALS POINT
Simply Easy Learning
3
CHAPTER
Java Basic Syntax
W
hen we consider a Java program, it can be defined as a collection of objects that communicate via
invoking each other's methods
...
•
•
•
•
Object - Objects have states and behaviors
...
An object is an instance of a class
...
Methods - A method is basically a behavior
...
It is in methods where the
logics are written, data is manipulated and all the actions are executed
...
An object's state is created by the
values assigned to these instance variables
...
public class MyFirstJavaProgram{
/* This is my first java program
...
out
...
Please follow the steps given below:
•
Open notepad and add the code as above
...
java
...
Assume it's C:\
...
java ' and press enter to compile your code
...
TUTORIALS POINT
Simply Easy Learning
•
Now, type ' java MyFirstJavaProgram ' to run your program
...
C :> javac MyFirstJavaProgram
...
•
Case Sensitivity - Java is case sensitive, which means identifier Hello and hello would have different
meaning in Java
...
If several words are used to form a name of the class, each inner word's first letter should be in Upper Case
...
If several words are used to form the name of the method, then each inner word's first letter should be in
Upper Case
...
When saving the file, you should save it using the class name (Remember Java is case sensitive) and append
'
...
Example : Assume 'MyFirstJavaProgram' is the class name, then the file should be saved
as'MyFirstJavaProgram
...
Java Identifiers:
All Java components require names
...
In Java, there are several points to remember about identifiers
...
•
After the first character, identifiers can have any combination of characters
...
•
Most importantly identifiers are case sensitive
...
, by using modifiers
...
Java Variables:
We would see following type of variables in Java:
•
•
•
Local Variables
Class Variables (Static Variables)
Instance Variables (Non-static variables)
Java Arrays:
Arrays are objects that store multiple variables of the same type
...
We will look into how to declare, construct and initialize in the upcoming chapters
...
0
...
The
values in this enumerated list are called enums
...
For example, if we consider an application for a fresh juice shop, it would be possible to restrict the glass size to
small, medium and large
...
Example:
Class FreshJuice{
enum FreshJuiceSize{ SMALL, MEDUIM, LARGE }
FreshJuiceSize size;
}
public class FreshJuiceTest{
public static void main(String args[]){
FreshJuice juice =new FreshJuice();
juice
...
FreshJuiceSize
...
Methods, variables, constructors can be defined inside
enums as well
...
These reserved words may not be used as constant or variable
or any other identifier names
...
All characters available inside any
comment are ignored by Java compiler
...
* This will print 'Hello World' as the output
* This is an example of multi-line comments
...
*/
System
...
println("Hello World");
}
}
Using Blank Lines:
A line containing only whitespace, possibly with a comment, is known as a blank line, and Java totally ignores it
...
Basically, if you need to create a new class and here is already a class
that has some of the code you require, then it is possible to derive your new class from the already existing code
...
In this scenario, the existing class is called the superclass and the derived class is called the subclass
...
Interfaces play a vital role when it comes to the concept of inheritance
...
But the implementation of the methods is
totally up to the subclass
...
At the end of the session, you will be
able to get a clear picture as to what are objects and what are classes in Java
...
As a language that has the Object Oriented feature, Java supports the
following fundamental concepts:
•
•
•
•
•
•
•
•
•
Polymorphism
Inheritance
Encapsulation
Abstraction
Classes
Objects
Instance
Method
Message Parsing
In this chapter, we will look into the concepts Classes and Objects
...
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
...
If we consider the real-world we can find many objects around us, Cars,
Dogs, Humans, etc
...
If we consider a dog, then its state is - name, breed, color, and the behavior is - barking, wagging, running
If you compare the software object with a real world object, they have very similar characteristics
...
A software object's state is stored in fields and behavior is shown
via methods
...
TUTORIALS POINT
Simply Easy Learning
Classes in Java:
A class is a blue print from which individual objects are created
...
•
•
•
Local variables: Variables defined inside methods, constructors or blocks are called local variables
...
Instance variables: Instance variables are variables within a class but outside any method
...
Instance variables can be accessed from inside any method,
constructor or blocks of that particular class
...
A class can have any number of methods to access the value of various kinds of methods
...
Below mentioned are some of the important topics that need to be discussed when looking into classes of the Java
Language
...
Every class has a
constructor
...
Each time a new object is created, at least one constructor will be invoked
...
A class can have more than one constructor
...
}
}
TUTORIALS POINT
Simply Easy Learning
Java also supports Singleton Classes where you would be able to create only one instance of a class
...
Since there is only
one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields
...
For example, if you have a license for only one connection for your database or your JDBC driver has trouble with
multithreading, the Singleton makes sure that only one connection is made or that only one thread can access the
connection at a time
...
The private field can be assigned from within a static initializer block or, more simply, using an initializer
...
java
public class Singleton{
private static Singleton singleton =new Singleton();
/* A private Constructor prevents any other
* class from instantiating
...
out
...
java
public lassSingletonDemo{
public staticvoid main(String[] args){
Singleton tmp =Singleton
...
demoMethod();
}
}
This would produce the following result:
demoMethod for singleton
TUTORIALS POINT
Simply Easy Learning
Example 2:
Following implementation shows a classic Singleton design pattern:
public class ClassicSingleton{
private static ClassicSingleton instance =null;
protected ClassicSingleton(){
// Exists only to defeat instantiation
...
Here ClassicSingleton class employs a technique known as lazy instantiation to create the singleton; as a result, the
singleton instance is not created until the getInstance() method is called for the first time
...
Creating an Object:
As mentioned previously, a class provides the blueprints for objects
...
In Java the new keyword is used to create new objects
...
Instantiation: The 'new' keyword is used to create the object
...
This call initializes the new object
...
System
...
println("Passed Name is :"+ name );
}
public static void main(String[]args){
// Following statement would create an object myPuppy
Puppy myPuppy =new Puppy("tommy");
}
}
If we compile and run the above program, then it would produce the following result:
PassedNameis:tommy
Accessing Instance Variables and Methods:
Instance variables and methods are accessed via created objects
...
variableName;
/* Now you can call a class method as follows */
ObjectReference
...
System
...
println("Passed Name is :"+ name );
}
public void setAge(int age ){
puppyAge = age;
}
public int getAge(){
System
...
println("Puppy's age is :"+ puppyAge );
return puppyAge;
}
public static void main(String[]args){
/* Object creation */
Puppy myPuppy =newPuppy("tommy");
/* Call class method to set puppy's age */
myPuppy
...
getAge();
/* You can access instance variable as follows as well */
System
...
println("Variable Value :"+ myPuppy
...
These rules are essential when
declaring classes, import statements and package statements in a source file
...
•
A source file can have multiple non public classes
...
java at the
end
...
public class Employee{} Then the source file should be as
Employee
...
•
If the class is defined inside a package, then the package statement should be the first statement in the source
file
...
If there are no package statements then the import statement should be the first line in the source
file
...
It is not possible to
declare different import and/or package statements to different classes in the source file
...
I
will be explaining about all these in the access modifiers chapter
...
Java Package:
In simple, it is a way of categorizing the classes and interfaces
...
Import statements:
In Java if a fully qualified name, which includes the package and the class name, is given, then the compiler can
easily locate the source code or classes
...
For example,the following
java_installation/java/io
line
would
ask
compiler
to
load
all
the
classes
available
in
directory
import java
...
*;
A Simple Case Study:
For our case study, we will be creating two classes
...
First open notepad and add the following code
...
Now, save this source file with the name Employee
...
The Employee class has four instance variables name, age, designation and salary
...
import java
...
*;
public class Employee{
String name;
int age;
String designation;
double salary;
// This is the constructor of the class Employee
public Employee(String name){
TUTORIALS POINT
Simply Easy Learning
this
...
public void empAge(int empAge){
age = empAge;
}
/* Assign the designation to the variable designation
...
*/
public void empSalary(double empSalary){
salary = empSalary;
}
/* Print the Employee details */
public void printEmployee(){
System
...
println("Name:"+ name );
System
...
println("Age:"+ age );
System
...
println("Designation:"+ designation );
System
...
println("Salary:"+ salary);
}
}
As mentioned previously in this tutorial, processing starts from the main method
...
We will be creating a separate class
for these tasks
...
Save the following code in EmployeeTest
...
io
...
empAge(26);
empOne
...
empSalary(1000);
empOne
...
empAge(21);
empTwo
...
empSalary(500);
empTwo
...
java
C :> vi EmployeeTest
...
java
C :> java EmployeeTest
Name:JamesSmith
TUTORIALS POINT
Simply Easy Learning
Age:26
Designation:SeniorSoftwareEngineer
Salary:1000
...
0
What is Next?
Next session will discuss basic data types in Java and how they can be used when developing Java applications
...
This means that when you create a
variable you reserve some space in memory
...
Therefore, by assigning different data types to variables, you can store integers, decimals,
or characters in these variables
...
Primitive data types are predefined by the language and
named by a keyword
...
byte:
•
Byte data type is an 8-bit signed two's complement integer
...
•
Example: byte a = 100, byte b = -50
short:
•
Short data type is a 16-bit signed two's complement integer
...
A short is 2 times smaller than an int
•
Default value is 0
...
•
Minimum value is - 2,147,483,648
...
(2^31 -1)
•
Int is generally used as the default data type for integral values unless there is a concern about memory
...
•
Example: int a = 100000, int b = -200000
long:
•
Long data type is a 64-bit signed two's complement integer
...
(-2^63)
•
Maximum value is 9,223,372,036,854,775,807 (inclusive)
...
•
Default value is 0L
...
•
Float is mainly used to save memory in large arrays of floating point numbers
...
0f
...
•
Example: float f1 = 234
...
•
This data type is generally used as the default data type for decimal values, generally the default choice
...
•
Default value is 0
...
•
Example: double d1 = 123
...
•
There are only two possible values: true and false
...
•
Default value is false
...
•
Minimum value is '\u0000' (or 0)
...
•
Char data type is used to store any character
...
They are used to access objects
...
For example, Employee, Puppy,
etc
...
•
Default value of any reference variable is null
...
•
Example: Animal animal = new Animal("giraffe");
TUTORIALS POINT
Simply Easy Learning
Java Literals:
A literal is a source code representation of a fixed value
...
Literals can be assigned to any primitive type variable
...
Prefix 0 is used to indicate octal and prefix 0x indicates hexadecimal when using these number systems for literals
...
Examples of string literals are:
"Hello World"
"two\nlines"
"\"This is in quotes\""
String and char types of literals can contain any Unicode characters
...
They are:
Notation
Character represented
\n
Newline (0x0a)
\r
Carriage return (0x0d)
\f
Formfeed (0x0c)
\b
Backspace (0x08)
\s
Space (0x20)
\t
Tab
\"
Double quote
\'
Single quote
\\
Backslash
\ddd
Octal character (ddd)
\uxxxx
Hexadecimal UNICODE character (xxxx)
TUTORIALS POINT
Simply Easy Learning
What is Next?
This chapter explained you various data types, next topic explains different variable types and their usage
...
TUTORIALS POINT
Simply Easy Learning
6
CHAPTER
Java Variable Types
A
variable provides us with named storage that our programs can manipulate
...
You must declare all variables before they can be used
...
] ;
Here data type is one of Java's datatypes and variable is the name of the variable
...
Following are valid examples of variable declaration and initialization in Java:
int a, b, c;
int a = 10, b = 10;
byte B = 22;
double pi = 3
...
Example of initialization
initializes a byte type variable B
...
the char variable a iis initialized with value 'a'
This chapter will explain various variable types available in Java Language
...
•
Local variables are created when the method, constructor or block is entered and the variable will be destroyed
once it exits the method, constructor or block
...
TUTORIALS POINT
Simply Easy Learning
•
Local variables are visible only within the declared method, constructor or block
...
•
There is no default value for local variables so local variables should be declared and an initial value should be
assigned before the first use
...
This is defined inside pupAge() method and its scope is limited to this method only
...
out
...
pupAge();
}
}
This would produce the following result:
Puppy age is: 7
Example:
Following example uses age without initializing it, so it would give an error at the time of compilation
...
out
...
pupAge();
}
}
This would produce the following error while compiling it:
Test
...
TUTORIALS POINT
Simply Easy Learning
•
When a space is allocated for an object in the heap, a slot for each instance variable value is created
...
•
Instance variables hold values that must be referenced by more than one method, constructor or block, or
essential parts of an object's state that must be present throughout the class
...
•
Access modifiers can be given for instance variables
...
Normally, it is
recommended to make these variables private (access level)
...
•
Instance variables have default values
...
Values can be assigned during the declaration or within the constructor
...
However within static
methods and different class ( when instance variables are given accessibility) should be called using the fully
qualified name
...
VariableName
...
io
...
public String name;
// salary variable is visible in Employee class only
...
public Employee (String empName){
name = empName;
}
// The salary variable is assigned a value
...
public void printEmp(){
System
...
println("name : " + name );
System
...
println("salary :" + salary);
}
public static void main(String args[]){
Employee empOne = new Employee("Ransika");
empOne
...
printEmp();
}
}
This would produce the following result:
TUTORIALS POINT
Simply Easy Learning
name : Ransika
salary :1000
...
•
There would only be one copy of each class variable per class, regardless of how many objects are created
from it
...
Constants are variables that are
declared as public/private, final and static
...
•
Static variables are stored in static memory
...
•
Static variables are created when the program starts and destroyed when the program stops
...
However, most static variables are declared public since they must be
available for users of the class
...
For numbers, the default value is 0; for Booleans, it is false; and
for object references, it is null
...
Additionally values can be assigned in special static initializer blocks
...
ClassName
...
•
When declaring class variables as public static final, then variables names (constants) are all in upper case
...
Example:
import java
...
*;
public class Employee{
// salary variable is a private static variable
private static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
public static void main(String args[]){
salary = 1000;
System
...
println(DEPARTMENT+"average salary:"+salary);
}
}
This would produce the following result:
Development average salary:1000
Note: If the variables are
Employee
...
The next chapter will explain you
Access Modifiers and Non Access Modifiers in detail
...
The Java language
has a wide variety of modifiers, including the following:
1
...
The four access levels are:
•
Visible to the package, the default
...
•
Visible to the class only (private)
...
•
Visible to the package and all subclasses (protected)
...
A variable or method declared without any access control modifier is available to any other class in the same
package
...
5
...
Private access modifier is the most restrictive access level
...
Variables that are declared private can be accessed outside the class if public getter methods are present in the
class
...
Example:
The following class uses private access control:
public class Logger{
private String format;
public String getFormat(){
return this
...
format = format;
}
}
Here, the format variable of the Logger class is private, so there's no way for other classes to retrieve or set its value
directly
...
Public Access Modifier -‐ public:
A class, method, constructor, interface etc declared public can be accessed from any other class
...
However if the public class we are trying to access is in a different package, then the public class still need to be
imported
...
Example:
The following function uses public access control:
public static void main(String[] arguments){
//
...
Otherwise, it could not be called by a Java interpreter (such
as java) to run the class
...
The protected access modifier cannot be applied to class and interfaces
...
Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated
class from trying to use it
...
If we define it as public, then it would become accessible to all the outside world
...
Access Control and Inheritance:
The following rules for inherited methods are enforced:
•
Methods declared public in a superclass also must be public in all subclasses
...
•
Methods declared without access control (no modifier was used) can be declared more private in subclasses
...
2
...
The modifier precedes the
rest of the statement, as in the following examples (Italic ones):
public class className {
//
...
5;
protected static final int BOXWIDTH =42;
public static void main(String[] arguments){
TUTORIALS POINT
Simply Easy Learning
// body of method
}
Access Control Modifiers:
Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors
...
the default
...
•
Visible to the class only (private)
...
•
Visible to the package and all subclasses (protected)
...
The static modifier for creating class methods and variables
The final modifier for finalizing the implementations of classes, methods, and variables
...
The synchronized and volatile modifiers, which are used for threads
...
The modifier precedes the
rest of the statement, as in the following examples (Italic ones):
publicclass className {
//
...
5;
protected static final int BOXWIDTH =42;
public static void main(String[] arguments){
// body of method
}
Access Control Modifiers:
Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors
...
the default
...
•
Visible to the class only (private)
...
•
Visible to the package and all subclasses (protected)
...
TUTORIALS POINT
Simply Easy Learning
•
•
•
•
The static modifier for creating class methods and variables
The final modifier for finalizing the implementations of classes, methods, and variables
...
The synchronized and volatile modifiers, which are used for threads
...
The chapter will give you
an overview of how these operators can be used during application development
...
We can divide all the Java operators into the
following groups:
•
Arithmetic Operators
•
Relational Operators
•
Bitwise Operators
•
Logical Operators
•
Assignment Operators
•
Misc Operators
The Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra
...
Copy and paste the following Java
program in Test
...
out
...
out
...
out
...
out
...
out
...
out
...
out
...
out
...
out
...
out
...
!=
Checks if the values of two operands are equal or not, if values are not
(A != B) is true
...
>
Checks if the value of left operand is greater than the value of right
operand, if yes then condition becomes true
...
<
Checks if the value of left operand is less than the value of right
operand, if yes then condition becomes true
...
>=
Checks if the value of left operand is greater than or equal to the value
(A >= B) is not true
...
of right operand, if yes then condition becomes true
...
(A <= B) is true
...
Copy and paste the following Java
program in Test
...
:
public class Test{
public static void main(String args[]){
int a =10;
int b =20;
System
...
println("a == b = "+(a == b));
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));
}
}
This would produce the following result:
a
a
a
a
b
b
== b =false
!= b =true
> b =false
< b =true
>= a =true
<= a =false
The Bitwise Operators:
Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte
...
Assume if a = 60; and b = 13; now in binary format
they will be as follows:
a = 0011 1100
b = 0000 1101
----------------a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators:
Assume integer variable A holds 60 and variable B holds 13, then:
TUTORIALS POINT
Simply Easy Learning
Operator Description
Example
&
Binary AND Operator copies a bit to the result if it
exists in both operands
...
^
Binary XOR Operator copies the bit if it is set in
one operand but not both
...
(~A ) will give -60 which is 1100 0011
<<
Binary Left Shift Operator
...
>>
Binary Right Shift Operator
...
A >> 2 will give 15 which is 1111
>>>
Shift right zero fill operator
...
A >>>2 will give 15 which is 0000 1111
(A & B) will give 12 which is 0000 1100
Example
The following simple example program demonstrates the bitwise operators
...
java file and compile and run this program:
public class Test{
public static void main(String args[]){
int a =60;
/* 60 = 0011 1100 */
int b =13;
/* 13 = 0000 1101 */
int c =0;
c = a & b;/* 12 = 0000 1100 */
System
...
println("a & b = "+ c );
c = a | b;/* 61 = 0011 1101 */
System
...
println("a | b = "+ c );
c = a ^ b;/* 49 = 0011 0001 */
System
...
println("a ^ b = "+ c );
c =~a;/*-61 = 1100 0011 */
System
...
println("~a = "+ c );
c = a <<2;/* 240 = 1111 0000 */
System
...
println("a << 2 = "+ c );
c = a >>2;/* 215 = 1111 */
System
...
println("a >> 2 = "+ c );
c = a >>>2;/* 215 = 0000 1111 */
System
...
println("a >>> 2 = "+ c );
}
TUTORIALS POINT
Simply Easy Learning
}
This would produce the following result:
a & b =12
a | b =61
a ^ b =49
~a =-61
a <<2=240
a >>15
a >>>15
The Logical Operators:
The following table lists the logical operators:
Assume Boolean variables A holds true and variable B holds false, then:
Operator Description
Example
&&
Called Logical AND operator
...
condition becomes true
...
If any of the two operands are non-zero,
then the condition becomes true
...
!
Called Logical NOT Operator
...
If a condition is true then Logical NOT operator will make false
...
Example
The following simple example program demonstrates the logical operators
...
java file and compile and run this program:
public class Test{
public static void main(String args[]){
boolean a =true;
boolean b =false;
System
...
println("a && b = "+(a&&b));
System
...
println("a || b = "+(a||b));
System
...
println("!(a && b) = "+!(a && b));
}
}
This would produce the following result:
a && b =false
a || b =true
!(a && b)=true
The Assignment Operators:
There are following assignment operators supported by Java language:
TUTORIALS POINT
Simply Easy Learning
Operator Description
Example
=
Simple assignment operator, Assigns values
from right side operands to left side operand
C = A + B will assign value of A + B into C
+=
Add AND assignment operator, It adds right
operand to the left operand and assign the
result to left operand
C += A is equivalent to C = C + A
-=
Subtract AND assignment operator, It
subtracts right operand from the left operand
and assign the result to left operand
C -= A is equivalent to C = C - A
*=
Multiply AND assignment operator, It multiplies
right operand with the left operand and assign C *= A is equivalent to C = C * A
the result to left operand
/=
Divide AND assignment operator, It divides left
operand with the right operand and assign the C /= A is equivalent to C = C / A
result to left operand
%=
Modulus AND assignment operator, It takes
modulus using two operands and assign the
result to left operand
C %= A is equivalent to C = C % A
<<=
Left shift AND assignment operator
C <<= 2 is same as C = C << 2
>>=
Right shift AND assignment operator
C >>= 2 is same as C = C >> 2
&=
Bitwise AND assignment operator
C &= 2 is same as C = C & 2
^=
bitwise exclusive OR and assignment operator
C ^= 2 is same as C = C ^ 2
|=
bitwise inclusive OR and assignment operator
C |= 2 is same as C = C | 2
Example:
The following simple example program demonstrates the assignment 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 =0;
c = a + b;
System
...
println("c = a + b = "+ c );
c += a ;
System
...
println("c += a
= "+ c );
c -= a ;
System
...
println("c -= a = "+ c );
c *= a ;
System
...
println("c *= a = "+ c );
a =10;
c =15;
TUTORIALS POINT
Simply Easy Learning
c /= a ;
System
...
println("c /= a = "+ c );
a =10;
c =15;
c %= a ;
System
...
println("c %= a
= "+ c );
c <<=2;
System
...
println("c <<= 2 = "+ c );
c >>=2;
System
...
println("c >>= 2 = "+ c );
c >>=2;
System
...
println("c >>= a = "+ c );
c &= a ;
System
...
println("c &= 2
= "+ c );
c ^= a ;
System
...
println("c ^= a
c |= a ;
System
...
println("c |= a
}
}
= "+ c );
= "+ c );
This would produce the following result:
c
c
c
c
c
c
c
c
c
c
c
c
= a + b =30
+= a =40
-= a =30
*= a =300
/= a =1
%= a =5
<<=2=20
>>=2=5
>>=2=1
&= a =0
^= a
=10
|= a
=10
Misc Operators
There are few other operators supported by Java Language
...
This operator consists of three operands and is used to
evaluate Boolean expressions
...
The operator is written as:
variable x =(expression)? value iftrue: value iffalse
Following is the example:
public class Test{
TUTORIALS POINT
Simply Easy Learning
public static void main(String args[]){
int a , b;
a =10;
b =(a ==1)?20:30;
System
...
println("Value of b is : "+ b );
b =(a ==10)?20:30;
System
...
println("Value of b is : "+ b );
}
}
This would produce the following result:
Value of b is:30
Value of b is:20
instanceof Operator:
This operator is used only for object reference variables
...
instanceof operator is wriiten as:
(Object reference variable ) instanceof
(class/interface type)
If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface
type on the right side, then the result will be true
...
Following is one more example:
classVehicle{}
public class CarextendsVehicle{
public static void main(String args[]){
Vehicle a =newCar();
boolean result = a instanceofCar;
System
...
println(result);
}
}
This would produce the following result:
true
Precedence of Java Operators:
Operator precedence determines the grouping of terms in an expression
...
Certain operators have higher precedence than others; for example, the multiplication operator has
higher precedence than the addition operator:
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it
first gets multiplied with 3*2 and then adds into 7
...
Within an expression, higher precedence operators will be evaluated first
...
(dot operator)
Left to right
Unary
++ - - ! ~
Right to left
Multiplicative
*/%
Left to right
Additive
+-
Left to right
Shift
>>>>><<
Left to right
Relational
>>= <<=
Left to right
Equality
== !=
Left to right
Bitwise AND
&
Left to right
Bitwise XOR
^
Left to right
Bitwise OR
|
Left to right
Logical AND
&&
Left to right
Logical OR
||
Left to right
Conditional
?:
Right to left
Assignment
= += -= *= /= %= >>= <<= &= ^= |=
Right to left
Comma
,
Left to right
What is Next?
Next chapter would explain about loop control in Java programming
...
TUTORIALS POINT
Simply Easy Learning
9
CHAPTER
Java Loop Control
T
here may be a situation when we need to execute a block of code several number of times and is often
referred to as a loop
...
You can use one of the following three loops:
•
while Loop
•
do
...
This is mainly used for Arrays
...
Syntax:
The syntax of a while loop is:
while(Boolean_expression)
{
//Statements
}
When executing, if the boolean_expression result is true, then the actions inside the loop will be executed
...
Here, key point of the while loop is that the loop might not ever run
...
Example:
public class Test{
public static void main(String args[]){
int x =10;
while( x <20){
TUTORIALS POINT
Simply Easy Learning
System
...
print("value of x : "+ x );
x++;
System
...
print("\n");
}
}
}
This would produce the following result:
value
value
value
value
value
value
value
value
value
value
of
of
of
of
of
of
of
of
of
of
x
x
x
x
x
x
x
x
x
x
:10
:11
:12
:13
:14
:15
:16
:17
:18
:19
The do
...
while loop is similar to a while loop, except that a do
...
Syntax:
The syntax of a do
...
If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute
again
...
Example:
public class Test{
public static void main(String args[]){
int x =10;
do{
System
...
print("value of x : "+ x );
x++;
System
...
print("\n");
}while( x <20);
}
}
This would produce the following result:
value of x :10
value of x :11
value of x :12
TUTORIALS POINT
Simply Easy Learning
value
value
value
value
value
value
value
of
of
of
of
of
of
of
x
x
x
x
x
x
x
:13
:14
:15
:16
:17
:18
:19
The for Loop:
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific
number of times
...
Syntax:
The syntax of a for loop is:
for(initialization;Boolean_expression; update)
{
//Statements
}
Here is the flow of control in a for loop:
•
The initialization step is executed first, and only once
...
You are not required to put a statement here, as long as a semicolon appears
...
If it is true, the body of the loop is executed
...
•
After the body of the for loop executes, the flow of control jumps back up to the update statement
...
This statement can be left blank, as long as a
semicolon appears after the Boolean expression
...
If it is true, the loop executes and the process repeats itself
(body of loop, then update step,then Boolean expression)
...
Example:
public class Test{
public static void main(String args[]){
for(int x =10; x <20; x = x+1){
System
...
print("value of x : "+ x );
System
...
print("\n");
}
}
}
This would produce the following result:
value of x :10
value of x :11
value of x :12
TUTORIALS POINT
Simply Easy Learning
value
value
value
value
value
value
value
of
of
of
of
of
of
of
x
x
x
x
x
x
x
:13
:14
:15
:16
:17
:18
:19
Enhanced for loop in Java:
As of Java 5, the enhanced for loop was introduced
...
Syntax:
The syntax of enhanced for loop is:
for(declaration : expression)
{
//Statements
}
•
Declaration: The newly declared block variable, which is of a type compatible with the elements of the array
you are accessing
...
•
Expression: This evaluates to the array you need to loop through
...
Example:
public class Test{
public static void main(String args[]){
int[] numbers ={10,20,30,40,50};
for(int x : numbers ){
System
...
print(x);
System
...
print(",");
}
System
...
print("\n");
String[] names ={"James","Larry","Tom","Lacy"};
for(String name : names ){
System
...
print( name );
System
...
print(",");
}
}
}
This would produce the following result:
10,20,30,40,50,
James,Larry,Tom,Lacy,
The break Keyword:
The break keyword is used to stop the entire loop
...
TUTORIALS POINT
Simply Easy Learning
The break keyword will stop the execution of the innermost loop and start executing the next line of code after the
block
...
out
...
out
...
It causes the loop to immediately jump to
the next iteration of the loop
...
•
In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression
...
out
...
out
...
TUTORIALS POINT
Simply Easy Learning
CHAPTER
10
Java Decision Making
T
here are two types of decision making statements in Java
...
Syntax:
The syntax of an if statement is:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed
...
Example:
public class Test{
public static void main(String args[]){
int x =10;
if( x <20){
System
...
print("This is if statement");
}
}
}
This would produce the following result:
Thisisif statement
TUTORIALS POINT
Simply Easy Learning
The if
...
Syntax:
The syntax of an if
...
out
...
out
...
else if
...
else statement, which is very useful to test various conditions
using single if
...
When using if, else if , else statements there are few points to keep in mind
...
•
An if can have zero to many else if's and they must come before the else
...
Syntax:
The syntax of an if
...
}
Example:
public class Test{
public static void main(String args[]){
int x =30;
if( x ==10){
System
...
print("Value of X is 10");
}elseif( x ==20){
System
...
print("Value of X is 20");
}elseif( x ==30){
System
...
print("Value of X is 30");
}else{
System
...
print("This is else statement");
}
}
}
This would produce the following result:
Value of X is30
Nested if
...
Syntax:
The syntax for a nested if
...
else in the similar way as we have nested if statement
...
out
...
Each value is called a case,
and the variable being switched on is checked for each case
...
default://Optional
//Statements
}
The following rules apply to a switch statement:
•
The variable used in a switch statement can only be a byte, short, int, or char
...
Each case is followed by the value to be
compared to and a colon
...
•
When the variable being switched on is equal to a case, the statements following that case will execute until
a break statement is reached
...
•
Not every case needs to contain a break
...
•
A switch statement can have an optional default case, which must appear at the end of the switch
...
No break is needed in the default
case
...
charAt(0);
switch(grade)
TUTORIALS POINT
Simply Easy Learning
{
case'A':
System
...
println("Excellent!");
break;
case'B':
case'C':
System
...
println("Well done");
break;
case'D':
System
...
println("You passed");
case'F':
System
...
println("Better try again");
break;
default:
System
...
println("Invalid grade");
}
System
...
println("Your grade is "+ grade);
}
}
Compile and run above program using various command line arguments
...
lang package) and its subclasses in Java Language
...
TUTORIALS POINT
Simply Easy Learning
CHAPTER
Java Numbers
N
11
ormally, when we work with Numbers, we use primitive data types such as byte, int, long, double, etc
...
65;
byte mask =0xaf;
However, in development, we come across situations where we need to use objects instead of primitive data types
...
All the wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number
...
So when a primitive is used when an
object is required, the compiler boxes the primitive type in its wrapper class
...
The Number is part of the java
...
Here is an example of boxing and unboxing:
public class Test{
public static void main(String args[]){
Integer x =5;// boxes int to an Integer object
x = x +10;// unboxes the Integer to a int
System
...
println(x);
}
}
TUTORIALS POINT
Simply Easy Learning
This would produce the following result:
15
When x is assigned integer values, the compiler boxes the integer because x is integer objects
...
Number Methods:
Here is the list of the instance methods that all the subclasses of the Number class implement:
SN Methods with Description
1
xxxValue()
Converts the value of this Number object to the xxx data type and returned it
...
3
equals()
Determines whether this number object is equal to the argument
...
5
toString()
Returns a String object representing the value of specified int or Integer
...
7
abs()
Returns the absolute value of the argument
...
Returned as a double
...
Returned as a double
...
Returned as a double
...
12
min()
Returns the smaller of the two arguments
...
14
exp()
Returns the base of the natural logarithms, e, to the power of the argument
...
16
pow()
Returns the value of the first argument raised to the power of the second argument
...
18
sin()
Returns the sine of the specified double value
...
20
tan()
Returns the tangent of the specified double value
...
22
acos()
Returns the arccosine of the specified double value
...
24
atan2()
Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta
...
27
random()
Returns a random number
...
Syntax:
Here is a separate method for each primitive data type:
byte byteValue()
short shortValue()
int intValue()
long longValue()
float floatValue()
double doubleValue()
Parameters:
Here is the detail of parameters:
•
NA
TUTORIALS POINT
Simply Easy Learning
Return Value:
•
These method returns the primitive data type that is given in the signature
...
out
...
byteValue());
// Returns double primitive data type
System
...
println(x
...
out
...
longValue());
}
}
This produces the following result:
5
5
...
It is possible to compare Byte,
Long, Integer, etc
...
Syntax:
publicint compareTo(NumberSubClass referenceName )
Parameters:
Here is the detail of parameters:
•
referenceName -- This could be a Byte, Double, Integer, Float, Long or Short
...
•
If the Integer is less than the argument then -1 is returned
...
•
Example:
public class Test{
public static void main(String args[]){
Integer x =5;
System
...
println(x
...
out
...
compareTo(5));
System
...
println(x
...
Syntax:
publicboolean equals(Object o)
Parameters:
Here is the detail of parameters:
• o -- Any object
...
There are some extra requirements for Double and Float objects that are described in the Java
API documentation
...
out
...
equals(y));
System
...
println(x
...
out
...
equals(a));
}
}
This produces the following result:
false
true
false
valueOf()
Description:
The valueOf method returns the relevant Number Object holding the value of the argument passed
...
This method is a static method
...
Syntax:
All the variants of this method are given below:
staticInteger valueOf(int i)
staticInteger valueOf(String s)
staticInteger valueOf(String s,int radix)
Parameters:
Here is the detail of parameters:
•
•
•
i -- An int for which Integer representation would be returned
...
radix -- This would be used to decide the value of returned Integer based on passed String
...
•
valueOf(String s): This returns an Integer object holding the value of the specified string representation
...
public class Test{
public static void main(String args[]){
Integer x =Integer
...
valueOf(5);
Float a =Float
...
valueOf("444",16);
System
...
println(x);
System
...
println(c);
System
...
println(a);
System
...
println(b);
}
}
This produces the following result:
9
5
...
0
1092
toString()
Description:
The method is used to get a String object representing the value of the Number Object
...
If the method takes two arguments, then a String representation of the first argument in the radix specified by
the second argument will be returned
...
Return Value:
•
•
toString(): This returns a String object representing the value of this Integer
...
Example:
public class Test{
TUTORIALS POINT
Simply Easy Learning
public static void main(String args[]){
Integer x =5;
System
...
println(x
...
out
...
toString(12));
}
}
This produces the following result:
5
12
parseInt()
Description:
This method is used to get the primitive data type of a certain String
...
Syntax:
All the variant of this method are given below:
staticint parseInt(String s)
staticint parseInt(String s,int radix)
Parameters:
Here is the detail of parameters:
•
•
s -- This is a string representation of decimal
...
Return Value:
•
•
parseInt(String s): This returns an integer (decimal only)
...
Example:
public class Test{
public static void main(String args[]){
int x =Integer
...
parseDouble("5");
int b =Integer
...
out
...
out
...
out
...
0
1092
abs()
Description:
The method gives the absolute value of the argument
...
Syntax:
All the variant of this method are given below:
double abs(double d)
float abs(float f)
int abs(int i)
long abs(long lng)
Parameters:
Here is the detail of parameters:
•
Any primitive data type
Return Value:
•
This method Returns the absolute value of the argument
...
out
...
abs(a));
System
...
println(Math
...
out
...
abs(f));
}
}
TUTORIALS POINT
Simply Easy Learning
This produces the following result:
8
100
...
0
ceil()
Description:
The method ceil gives the smallest integer that is greater than or equal to the argument
...
Returned as a
double
...
675;
float f =-90;
System
...
println(Math
...
out
...
ceil(f));
System
...
println(Math
...
out
...
floor(f));
}
}
This produces the following result:
-100
...
0
-101
...
0
floor()
Description:
The method floor gives the largest integer that is less than or equal to the argument
...
Returned as a double
...
675;
float f =-90;
System
...
println(Math
...
out
...
floor(f));
System
...
println(Math
...
out
...
ceil(f));
}
}
This produces the following result:
-101
...
0
-100
...
0
TUTORIALS POINT
Simply Easy Learning
rint()
Description:
The method rint returns the integer that is closest in value to the argument
...
Returned as a double
...
675;
e =100
...
200;
System
...
println(Math
...
out
...
rint(e));
System
...
println(Math
...
0
100
...
0
round()
Description:
The method round returns the closest long or int, as given by the methods return type
...
Example:
public class Test{
public static void main(String args[]){
double d =100
...
500;
float f =100;
float g =90f;
System
...
println(Math
...
out
...
round(e));
System
...
println(Math
...
out
...
round(g));
}
}
This produces the following result:
101
101
100
90
min()
Description:
The method gives the smaller of the two arguments
...
Syntax:
TUTORIALS POINT
Simply Easy Learning
This method has following variants:
double min(double arg1,double arg2)
float min(float arg1,float arg2)
int min(int arg1,int arg2)
long min(long arg1,long arg2)
Parameters:
Here is the detail of parameters:
•
A primitive data types
Return Value:
•
This method Returns the smaller of the two arguments
...
out
...
min(12
...
456));
System
...
println(Math
...
12,23
...
123
23
...
The argument can be int, float, long, double
...
Example:
public class Test{
public static void main(String args[]){
System
...
println(Math
...
123,12
...
out
...
max(23
...
0));
}
}
This produces the following result:
12
...
12
exp()
Description:
The method returns the base of the natural logarithms, e, to the power of the argument
...
Example:
public class Test{
public static void main(String args[]){
double x =11
...
76;
System
...
printf("The value of e is %
...
E);
TUTORIALS POINT
Simply Easy Learning
System
...
printf("exp(%
...
3f%n", x,Math
...
7183
exp(11
...
831
log()
Description:
The method returns the natural logarithm of the argument
...
Example:
public class Test{
public static void main(String args[]){
double x =11
...
76;
System
...
printf("The value of e is %
...
E);
System
...
printf("log(%
...
3f%n", x,Math
...
7183
log(11
...
454
pow()
Description:
TUTORIALS POINT
Simply Easy Learning
The method returns the value of the first argument raised to the power of the second argument
...
Example:
public class Test{
public static void main(String args[]){
double x =11
...
76;
System
...
printf("The value of e is %
...
E);
System
...
printf("pow(%
...
3f) is %
...
pow(x, y));
}
}
This produces the following result:
The value of e is 2
...
635, 2
...
008
sqrt()
Description:
The method returns the square root of the argument
...
Example:
public class Test{
public static void main(String args[]){
double x =11
...
76;
System
...
printf("The value of e is %
...
E);
System
...
printf("sqrt(%
...
3f%n", x,Math
...
7183
sqrt(11
...
411
sin()
Description:
The method returns the sine 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 sine of %
...
4f%n",degrees,Math
...
1416
The sine of 45
...
7071
cos()
Description:
The method returns the cosine 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 cosine of %
...
4f%n",
degrees,Math
...
1416
The cosine of 45
...
7071
tan()
Description:
The method returns the tangent 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 tangent of %
...
4f%n",
degrees,Math
...
1416
The tangent of 45
...
0000
asin()
Description:
TUTORIALS POINT
Simply Easy Learning
The method returns the arcsine 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 arcsine 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 acos(double d)
Parameters:
TUTORIALS POINT
Simply Easy Learning
Here is the detail of parameters:
•
d -- A double data types
Return Value:
•
This method Returns the arccosine of the specified double value
...
0;
double radians =Math
...
out
...
4f%n",Math
...
out
...
4f is %
...
cos(radians),
Math
...
acos(Math
...
1416
The arccosine of 0
...
0000 degrees
atan()
Description:
The method returns the arctangent of the specified double value
...
TUTORIALS POINT
Simply Easy Learning
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 arctangent of %
...
4f degrees %n",
Math
...
toDegrees(Math
...
sin(radians))));
}
}
This produces the following result:
The value of pi is 3
...
0000 is 45
...
Syntax:
double atan2(double y,double x)
Parameters:
Here is the detail of parameters:
•
•
X -- X co-ordinate in double data type
Y -- Y co-ordinate in double data type
Return Value:
•
This method Returns theta from polar coordinate (r, theta)
Example:
public class Test{
public static void main(String args[]){
double x =45
...
0;
TUTORIALS POINT
Simply Easy Learning
System
...
println(Math
...
982793723247329
toDegrees()
Description:
The method converts the argument value to degrees
...
Return Value:
•
This method returns a double value
...
0;
double y =30
...
out
...
toDegrees(x));
System
...
println(Math
...
3100780887044
1718
...
Syntax:
double toRadians(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
...
toRadians(y));
}
}
This produces the following result:
0
...
5235987755982988
random()
Description:
The method is used to generate a random number between 0
...
0
...
0 =< Math
...
0
...
Syntax:
staticdouble random()
Parameters:
Here is the detail of parameters:
TUTORIALS POINT
Simply Easy Learning
•
NA
Return Value:
•
This method returns a double
Example:
public class Test{
public static void main(String args[]){
System
...
println(Math
...
out
...
random());
}
}
This produces the following result:
0
...
400551253762343
Note: Above result would vary every time you would call random() method
...
You will be learning how to use object
Characters and primitive data type char in Java
...
Example:
char ch ='a';
// Unicode for uppercase Greek omega character
char uniChar ='\u039A';
// an array of chars
char[] charArray ={'a','b','c','d','e'};
However in development, we come across situations where we need to use objects instead of primitive data types
...
The Character class offers a number of useful class (i
...
, static) methods for manipulating characters
...
For example, if you pass a
primitive char into a method that expects an object, the compiler automatically converts the char to a Character for
you
...
Example:
// Here following primitive char 'a'
// is boxed into the Character object ch
Character ch ='a';
// Here primitive 'x' is boxed for method test,
// return is unboxed to char 'c'
char c = test('x');
Escape Sequences:
A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler
...
out
...
Following table shows the Java escape sequences:
Escape Sequence
Description
\t
Inserts a tab in the text at this point
...
\n
Inserts a newline in the text at this point
...
\f
Inserts a form feed in the text at this point
...
\"
Inserts a double quote character in the text at this point
...
When an escape sequence is encountered in a print statement, the compiler interprets it accordingly
...
out
...
");
}
}
This would produce the following result:
She said "Hello!" to me
...
2
isDigit()
Determines whether the specified char value is a digit
...
4
isUpperCase()
Determines whether the specified char value is uppercase
...
6
toUpperCase()
Returns the uppercase form of the specified char value
...
8
toString()
Returns a String object representing the specified character valuethat is, a one-character string
...
lang
...
isLetter()
Description:
The method determines whether the specified char value is a letter
...
Example:
public class Test{
public static void main(String args[]){
System
...
println(Character
...
out
...
isLetter('5'));
}
}
This produces the following result:
true
false
TUTORIALS POINT
Simply Easy Learning
isDigit()
Description:
The method determines whether the specified char value is a digit
...
Example:
public class Test{
public static void main(String args[]){
System
...
println(Character
...
out
...
isDigit('5'));
}
}
This produces the following result:
false
true
isWhitespace()
Description:
The method determines whether the specified char value is a white space, which includes space, tab or new
line
...
Example:
public class Test{
public static void main(String args[]){
System
...
println(Character
...
out
...
isWhitespace(' '));
System
...
println(Character
...
out
...
isWhitespace('\t'));
}
}
This produces the following result:
false
true
true
true
isUpperCase()
Description:
The method determines whether the specified char value is uppercase
...
TUTORIALS POINT
Simply Easy Learning
Example:
public class Test{
public static void main(String args[]){
System
...
println(Character
...
out
...
isUpperCase('C'));
System
...
println(Character
...
out
...
isUpperCase('\t'));
}
}
This produces the following result:
false
true
false
false
isLowerCase()
Description:
The method determines whether the specified char value is lowercase
...
Example:
public class Test{
public static void main(String args[]){
System
...
println(Character
...
out
...
isLowerCase('C'));
System
...
println(Character
...
out
...
isLowerCase('\t'));
}
}
TUTORIALS POINT
Simply Easy Learning
This produces the following result:
true
false
false
false
toUpperCase()
Description:
The method returns the uppercase form of the specified char value
...
Example:
public class Test{
public static void main(String args[]){
System
...
println(Character
...
out
...
toUpperCase('C'));
}
}
This produces the following result:
C
C
toLowerCase()
Description:
The method returns the lowercase form of the specified char value
...
Example:
public class Test{
public static void main(String args[]){
System
...
println(Character
...
out
...
toLowerCase('C'));
}
}
This produces the following result:
c
c
toString()
Description:
The method returns a String object representing the specified character value, that is, a one-character string
...
out
...
toString('c'));
System
...
println(Character
...
You will be learning how to declare and use
Strings efficiently as well as some of the important methods in the String class
...
In the Java programming
language, strings are objects
...
Creating Strings:
The most direct way to create a string is to write:
String greeting ="Hello world!";
Whenever it encounters a string literal in your code, the compiler creates a String object with its value, in this case,
"Hello world!'
...
The String
class has eleven constructors that allow you to provide the initial value of the string using different sources, such as
an array of characters:
public class StringDemo{
public static void main(String args[]){
char[] helloArray ={'h','e','l','l','o','
...
out
...
Note: The String class is immutable, so that once it is created a String object cannot be changed
...
String Length:
Methods used to obtain information about an object are known as accessor methods
...
TUTORIALS POINT
Simply Easy Learning
After the following two lines of code have been executed, len equals 17:
public class StringDemo{
public static void main(String args[]){
String palindrome ="Dot saw I was Tod";
int len = palindrome
...
out
...
concat(string2);
This returns a new string that is string1 with string2 added to it at the end
...
concat("Zara");
Strings are more commonly concatenated with the + operator, as in:
"Hello,"+" world"+"!"
which results in:
"Hello, world!"
Let us look at the following example:
public class StringDemo{
public static void main(String args[]){
String string1 ="saw I was ";
System
...
println("Dot "+ string1 +"Tod");
}
}
This would produce the following result:
Dot saw I was Tod
Creating Format Strings:
You have printf() and format() methods to print output with formatted numbers
...
Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to a
one-time print statement
...
out
...
format("The value of the float variable is "+
"%f, while the value of the integer "+
"variable is %d, and the string "+
"is %s", floatVar, intVar, stringVar);
System
...
println(fs);
String Methods:
Here is the list of methods supported by String class:
SN Methods with Description
1
char charAt(int index)
Returns the character at the specified index
...
3
int compareTo(String anotherString)
Compares two strings lexicographically
...
5
String concat(String str)
Concatenates the specified string to the end of this string
...
7
static String copyValueOf(char[] data)
Returns a String that represents the character sequence in the array specified
...
9
boolean endsWith(String suffix)
Tests if this string ends with the specified suffix
...
11
boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations
...
13
byte[] getBytes(String charsetName
Encodes this String into a sequence of bytes using the named charset, storing the result into a
new byte array
...
15
int hashCode()
Returns a hash code for this string
...
17
int indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the
search at the specified index
...
19
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
...
21
int lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character
...
23
int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring
...
25
int length()
Returns the length of this string
...
27
boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
Tests if two string regions are equal
...
29
String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with
newChar
...
31
String replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular expression with the given
replacement
...
33
String[] split(String regex, int limit)
Splits this string around matches of the given regular expression
...
35
boolean startsWith(String prefix, int toffset)
Tests if this string starts with the specified prefix beginning a specified index
...
37
String substring(int beginIndex)
Returns a new string that is a substring of this string
...
39
char[] toCharArray()
Converts this string to a new character array
...
41
String toLowerCase(Locale locale)
Converts all of the characters in this String to lower case using the rules of the given Locale
...
43
String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale
...
45
String trim()
Returns a copy of the string, with leading and trailing whitespace omitted
...
The above mentioned methods are explained here:
char charAt(int index)
Description:
This method returns the character located at the String's specified index
...
Syntax:
Here is the syntax of this method:
public char charAt(int index)
TUTORIALS POINT
Simply Easy Learning
Parameters:
Here is the detail of parameters:
•
index -- Index of the character to be returned
...
Example:
public class Test{
public static void main(String args[]){
String s ="Strings are immutable";
char result = s
...
out
...
First method compares this String to another Object and second
method compares two strings lexicographically
...
anotherString -- the String to be compared
...
Example:
public class Test{
public
String
String
String
static void main(String args[]){
str1 ="Strings are immutable";
str2 ="Strings are immutable";
str3 ="Integers are not immutable";
int result = str1
...
out
...
compareTo( str3 );
System
...
println(result);
result = str3
...
out
...
First method compares this String to another Object and second
method compares two strings lexicographically
...
anotherString -- the String to be compared
...
Example:
public class Test{
public
String
String
String
static void main(String args[]){
str1 ="Strings are immutable";
str2 ="Strings are immutable";
str3 ="Integers are not immutable";
int result = str1
...
out
...
compareTo( str3 );
System
...
println(result);
result = str3
...
out
...
Syntax:
Here is the syntax of this method:
int compareToIgnoreCase(String str)
Parameters:
Here is the detail of parameters:
•
str -- the String to be compared
...
Example:
public class Test{
public
String
String
String
static void main(String args[]){
str1 ="Strings are immutable";
str2 ="Strings are immutable";
str3 ="Integers are not immutable";
int result = str1
...
out
...
compareToIgnoreCase( str3 );
System
...
println(result);
result = str3
...
out
...
The method returns a String with the value of the
String passed in to the method appended to the end of the String used to invoke this method
...
Return Value :
TUTORIALS POINT
Simply Easy Learning
•
This methods returns a string that represents the concatenation of this object's characters followed by the
string argument's characters
...
concat(" all the time");
System
...
println(s);
}
}
This produces the following result:
Strings are immutable all the time
boolean contentEquals(StringBuffer sb)
Description:
This method returns true if and only if this String represents the same sequence of characters as the specified
in StringBuffer
...
Return Value:
•
This method returns true if and only if this String represents the same sequence of characters as the
specified in StringBuffer, otherwise false
...
contentEquals( str3 );
System
...
println(result);
result = str2
...
out
...
public static String copyValueOf(char[] data, int offset, int count): Returns a String that represents
the character sequence in the array specified
...
offset -- initial offset of the subarray
...
Return Value :
•
This method returns a String that contains the characters of the character array
...
copyValueOf(Str1);
System
...
println("Returned String: "+Str2);
Str2=Str2
...
out
...
Syntax:
Here is the syntax of this method:
public boolean endsWith(String suffix)
Parameters:
Here is the detail of parameters:
•
suffix -- the suffix
...
Note that the result will be true if the
argument is the empty string or is equal to this String object as determined by the equals(Object) method
...
endsWith("immutable!!");
System
...
println("Returned Value = "+ retVal );
retVal =Str
...
out
...
The result is true if and only if the argument is not
null and is a String object that represents the same sequence of characters as this object
...
Return Value :
•
This method returns true if the String are equal; false otherwise
...
equals(Str2);
System
...
println("Returned Value = "+ retVal );
retVal =Str1
...
out
...
Two strings are considered
equal ignoring case if they are of the same length, and corresponding characters in the two strings are equal
ignoring case
...
Example:
public class Test{
public static void main(String args[]){
String Str1=new String("This is really not immutable!!");
String Str2=Str1;
String Str3=new String("This is really not immutable!!");
String Str4=new String("This IS REALLY NOT IMMUTABLE!!");
boolean retVal;
retVal =Str1
...
out
...
equals(Str3);
System
...
println("Returned Value = "+ retVal );
retVal =Str1
...
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");
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
byte[] getBytes(String charsetName)
Description:
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)
throws UnsupportedEncodingException
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
...
Syntax:
Here is the syntax of this method:
public void getChars(int srcBegin,
int srcEnd,
char[] dst,
int dstBegin)
Parameters:
Here is the detail of parameters:
•
•
•
•
srcBegin -- index of the first character in the string to copy
...
dst -- the destination array
...
Return Value:
TUTORIALS POINT
Simply Easy Learning
•
It does not return any value but throws IndexOutOfBoundsException
...
io
...
com");
char[]Str2=newchar[7];
try{
Str1
...
out
...
out
...
out
...
");
}
}
}
This produces the following result:
Copied Value = lcome t
int hashCode()
Description:
This method returns a hash code for this string
...
+ s[n-1]
Using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates
exponentiation
...
)
Syntax:
Here is the syntax of this method:
public int hashCode()
Parameters:
Here is the detail of parameters:
• NA
Return Value:
TUTORIALS POINT
Simply Easy Learning
• This method returns a hash code value for this object
...
io
...
com");
System
...
println("Hashcode for Str :"+Str
...
public int indexOf(int ch, int fromIndex): Returns the index within this string of the first occurrence of
the specified character, starting the search at the specified index or -1 if the character does not occur
...
If it does not occur as a substring, -1 is returned
...
If it does not occur, -1 is returned
...
fromIndex -- the index to start the search from
...
Return Value:
•
See the description
...
io
...
com");
StringSubStr1=new String("Tutorials");
StringSubStr2=new String("Sutorials");
System
...
print("Found Index :");
System
...
println(Str
...
out
...
out
...
indexOf('o',5));
System
...
print("Found Index :");
System
...
println(Str
...
out
...
out
...
indexOf(SubStr1,15));
System
...
print("Found Index :");
System
...
println(Str
...
public int indexOf(int ch, int fromIndex): Returns the index within this string of the first occurrence of
the specified character, starting the search at the specified index or -1 if the character does not occur
...
If it does not occur as a substring, -1 is returned
...
If it does not occur, -1 is returned
...
fromIndex -- the index to start the search from
...
Return Value:
•
See the description
...
io
...
com");
SubStr1=new String("Tutorials");
SubStr2=new String("Sutorials");
System
...
print("Found Index :");
System
...
println(Str
...
out
...
out
...
indexOf('o',5));
System
...
print("Found Index :");
System
...
println(Str
...
out
...
out
...
indexOf(SubStr1,15));
System
...
print("Found Index :");
System
...
println(Str
...
public int indexOf(int ch, int fromIndex): Returns the index within this string of the first occurrence of
the specified character, starting the search at the specified index or -1 if the character does not occur
...
If it does not occur as a substring, -1 is returned
...
If it does not occur, -1 is returned
...
fromIndex -- the index to start the search from
...
TUTORIALS POINT
Simply Easy Learning
Return Value:
•
See the description
...
io
...
com");
StringSubStr1=new String("Tutorials");
StringSubStr2=new String("Sutorials");
System
...
print("Found Index :");
System
...
println(Str
...
out
...
out
...
indexOf('o',5));
System
...
print("Found Index :");
System
...
println(Str
...
out
...
out
...
indexOf(SubStr1,15));
System
...
print("Found Index :");
System
...
println(Str
...
public int indexOf(int ch, int fromIndex): Returns the index within this string of the first occurrence of
the specified character, starting the search at the specified index or -1 if the character does not occur
...
If it does not occur as a substring, -1 is returned
...
If it does not occur, -1 is returned
...
fromIndex -- the index to start the search from
...
Return Value:
•
See the description
...
io
...
com");
SubStr1=new String("Tutorials");
SubStr2=new String("Sutorials");
System
...
print("Found Index :");
System
...
println(Str
...
out
...
out
...
indexOf('o',5));
System
...
print("Found Index :");
System
...
println(Str
...
out
...
out
...
indexOf(SubStr1,15));
System
...
print("Found Index :");
System
...
println(Str
...
It follows that for any two strings s and t,
s
...
intern() is true if and only if s
...
Syntax:
Here is the syntax of this method:
public String intern()
Parameters:
Here is the detail of parameters:
•
NA
Return Value:
•
This method returns a canonical representation for the string object
...
io
...
com");
Str2=new String("WELCOME TO SUTORIALSPOINT
...
out
...
out
...
intern());
System
...
print("Canonical representation:");
System
...
println(Str2
...
com
Canonical representation: WELCOME TO SUTORIALSPOINT
...
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{
TUTORIALS POINT
Simply Easy Learning
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(int ch, int fromIndex)
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{
TUTORIALS POINT
Simply Easy Learning
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, int fromIndex)
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
...
The length is equal to the number of 16-bit Unicode characters in
the string
...
Example:
import java
...
*;
public
public
String
String
class Test{
static void main(String args[]){
Str1=new String("Welcome to Tutorialspoint
...
out
...
out
...
length());
System
...
print("String Length :");
System
...
println(Str2
...
An invocation of this
method of the form str
...
matches(regex, str)
...
Return Value:
•
This method returns true if, and only if, this string matches the given regular expression
...
io
...
com");
System
...
print("Return Value :");
System
...
println(Str
...
*)Tutorials(
...
out
...
out
...
matches("Tutorials"));
System
...
print("Return Value :");
System
...
println(Str
...
*)"));
}
}
This produces the following result:
Return Value :true
Return Value :false
Return Value :true
boolean regionMatches(boolean ignoreCase, int toffset,
String other, int ooffset, int len)
Description:
TUTORIALS POINT
Simply Easy Learning
This method has two variants which can be used to test if two string regions are equal
...
other -- the string argument
...
len -- the number of characters to compare
...
Return Value:
•
It returns true if the specified subregion of this string matches the specified subregion of the string
argument; false otherwise
...
Example:
import java
...
*;
public
public
String
String
String
class Test{
static void main(String args[]){
Str1=new String("Welcome to Tutorialspoint
...
out
...
out
...
regionMatches(11,Str2,0,9));
System
...
print("Return Value :");
System
...
println(Str1
...
out
...
out
...
regionMatches(true,11,Str3,0,9));
}
TUTORIALS POINT
Simply Easy Learning
}
This produces the following result:
Return Value :true
Return Value :false
Return Value :true
boolean regionMatches(int toffset, String other, int ooffset,
int len)
Description:
This method has two variants which can be used to test if two string regions are equal
...
other -- the string argument
...
len -- the number of characters to compare
...
Return Value:
•
It returns true if the specified subregion of this string matches the specified subregion of the string
argument; false otherwise
...
Example:
TUTORIALS POINT
Simply Easy Learning
import java
...
*;
public
public
String
String
String
class Test{
static void main(String args[]){
Str1=new String("Welcome to Tutorialspoint
...
out
...
out
...
regionMatches(11,Str2,0,9));
System
...
print("Return Value :");
System
...
println(Str1
...
out
...
out
...
regionMatches(true,11,Str3,0,9));
}
}
This produces the following result:
Return Value :true
Return Value :false
Return Value :true
String replace(char oldChar, char newChar)
Description:
This method returns a new string resulting from replacing all occurrences of oldChar in this string with
newChar
...
newChar -- the new character
...
Example:
import java
...
*;
TUTORIALS POINT
Simply Easy Learning
public class Test{
public static void main(String args[]){
String Str=new String("Welcome to Tutorialspoint
...
out
...
out
...
replace('o','T'));
System
...
print("Return Value :");
System
...
println(Str
...
cTm
Return Value :WeDcome to TutoriaDspoint
...
Syntax:
Here is the syntax of this method:
public String replaceAll(String regex,String replacement)
Parameters:
Here is the detail of parameters:
•
•
regex -- the regular expression to which this string is to be matched
...
Return Value:
•
This method returns the resulting String
...
io
...
com");
System
...
print("Return Value :");
TUTORIALS POINT
Simply Easy Learning
System
...
println(Str
...
*)Tutorials(
...
Syntax:
Here is the syntax of this method:
public String replaceFirst(String regex,String replacement)
Parameters:
Here is the detail of parameters:
•
•
regex -- the regular expression to which this string is to be matched
...
Return Value :
•
This method returns a resulting String
...
io
...
com");
System
...
print("Return Value :");
System
...
println(Str
...
*)Tutorials(
...
out
...
out
...
replaceFirst("Tutorials","AMROOD"));
}
}
This produces the following result:
TUTORIALS POINT
Simply Easy Learning
Return Value :AMROOD
Return Value :Welcome to AMROODpoint
...
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
String[] split(String regex, int limit)
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
to
Tutorialspoint
...
Syntax:
Here is the syntax of this method:
public boolean startsWith(String prefix,int toffset)
or
public boolean startsWith(String prefix)
Parameters:
Here is the detail of parameters:
•
•
prefix -- the prefix to be matched
...
Return Value:
•
It returns true if the character sequence represented by the argument is a prefix of the character
sequence represented by this string; false otherwise
...
io
...
com");
System
...
print("Return Value :");
System
...
println(Str
...
out
...
out
...
startsWith("Tutorials"));
System
...
print("Return Value :");
System
...
println(Str
...
Syntax:
Here is the syntax of this method:
public boolean startsWith(String prefix,int toffset)
or
public boolean startsWith(String prefix)
Parameters:
Here is the detail of parameters:
•
•
prefix -- the prefix to be matched
...
Return Value:
•
It returns true if the character sequence represented by the argument is a prefix of the character
sequence represented by this string; false otherwise
...
io
...
com");
System
...
print("Return Value :");
System
...
println(Str
...
out
...
out
...
startsWith("Tutorials"));
System
...
print("Return Value :");
System
...
println(Str
...
Syntax:
Here is the syntax of this method:
public CharSequence subSequence(int beginIndex,int endIndex)
Parameters:
Here is the detail of parameters:
•
•
beginIndex -- the begin index, inclusive
...
Return Value:
•
This method returns the specified subsequence
...
io
...
com");
System
...
print("Return Value :");
System
...
println(Str
...
out
...
out
...
subSequence(10,15));
}
}
This produces the following result:
Return Value :Welcome to
Return Value : Tuto
TUTORIALS POINT
Simply Easy Learning
String substring(int beginIndex)
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
...
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
...
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
TUTORIALS POINT
Simply Easy Learning
char[] toCharArray()
Description:
This method converts this string to a new character array
...
Example:
import java
...
*;
public class Test{
public static void main(String args[]){
String Str=new String("Welcome to Tutorialspoint
...
out
...
out
...
toCharArray());
}
}
This produces the following result:
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())
...
TUTORIALS POINT
Simply Easy Learning
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
String toLowerCase(Locale locale)
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:
Return Value :welcome to tutorialspoint
...
Example:
import java
...
*;
public class Test{
public static void main(String args[]){
String Str=new String("Welcome to Tutorialspoint
...
out
...
out
...
toString());
}
}
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
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 toUpperCase(Locale locale)
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{
TUTORIALS POINT
Simply Easy Learning
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
...
Syntax:
Here is the syntax of this method:
publicString trim()
Parameters:
Here is the detail of parameters:
•
NA
Return Value:
• It returns a copy of this string with leading and trailing white space removed, or this string if it has no
leading or trailing white space
...
io
...
com
System
...
print("Return Value :");
System
...
println(Str
...
com
TUTORIALS POINT
Simply Easy Learning
");
static String valueOf(primitive data type x)
Description:
This method has followings variants, which depend on the passed parameters
...
•
•
•
•
•
•
•
•
•
valueOf(boolean b): Returns the string representation of the boolean argument
...
valueOf(char[] data): Returns the string representation of the char array argument
...
valueOf(double d): Returns the string representation of the double argument
...
valueOf(int i): Returns the string representation of the int argument
...
valueOf(Object obj): Returns the string representation of the Object argument
...
Return Value :
•
This method returns the string representation
...
io
...
939;
boolean b =true;
long l =1232874;
char[] arr ={'a','b','c','d','e','f','g'};
System
...
println("Return
System
...
println("Return
System
...
println("Return
System
...
println("Return
}
}
Value
Value
Value
Value
This produces the following result:
Return
Return
Return
Return
Value
Value
Value
Value
:
:
:
:
1
...
valueOf(d));
"+String
...
valueOf(l));
"+String
...
An array is used to store a collection of data, but it is often more useful to think of an array as a
collection of variables of the same type
...
, and number99, you declare one array
variable such as numbers and use numbers[0], numbers[1], and
...
This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables
...
Here is the syntax for declaring an array variable:
dataType[] arrayRefVar;// preferred way
...
Note: The style dataType[] arrayRefVar is preferred
...
Example:
The following code snippets are examples of this syntax:
double[] myList;// preferred way
...
Creating Arrays:
You can create an array by using the new operator with the following syntax:
arrayRefVar =new dataType[arraySize];
The above statement does two things:
TUTORIALS POINT
Simply Easy Learning
•
It creates an array using new dataType[arraySize];
•
It assigns the reference of the newly created array to the variable arrayRefVar
...
, valuek};
The array elements are accessed through the index
...
length-1
...
Here, myList holds ten double values and the indices are from 0 to 9
...
Example:
Here is a complete example of showing how to create, initialize and process arrays:
public class TestArray{
public static void main(String[] args){
double[] myList ={1
...
9,3
...
5};
// Print all the array elements
for(int i =0; i < myList
...
out
...
length; i++){
total += myList[i];
}
System
...
println("Total is "+ total);
// Finding the largest element
double max = myList[0];
for(int i =1; i < myList
...
out
...
9
2
...
4
3
...
7
Maxis3
...
5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the
complete array sequentially without using an index variable
...
9,2
...
4,3
...
out
...
9
2
...
4
3
...
For example, the
following method displays the elements in an int array:
TUTORIALS POINT
Simply Easy Learning
public static void printArray(int[] array){
for(int i =0; i < array
...
out
...
For example, the following statement invokes the printArray method to
display 3, 1, 2, 6, 4, and 2:
printArray(newint[]{3,1,2,6,4,2});
Returning an Array from a Method:
A method may also return an array
...
length];
for(int i =0, j = result
...
length; i++, j--){
result[j]= list[i];
}
return result;
}
The Arrays Class:
The java
...
Arrays class contains various static methods for sorting and searching arrays, comparing arrays, and
filling array elements
...
SN Methods with Description
1
public static int binarySearch(Object[] a, Object key)
Searches the specified array of Object ( Byte, Int , double, etc
...
The array must be sorted prior to making this call
...
2
public static boolean equals(long[] a, long[] a2)
Returns true if the two specified arrays of longs are equal to one another
...
This returns true if the two arrays are equal
...
)
3
public static void fill(int[] a, int val)
Assigns the specified int value to each element of the specified array of ints
...
)
4
public static void sort(Object[] a)
Sorts the specified array of objects into ascending order, according to the natural ordering of its elements
...
)
TUTORIALS POINT
Simply Easy Learning
CHAPTER
15
Java Date and Time
J
ava provides the Date class available in java
...
The Date class supports two constructors
...
Date()
The following constructor accepts one argument that equals the number of milliseconds that have elapsed since
midnight, January 1, 1970
Date(long millisec)
Once you have a Date object available, you can call any of the following support methods to play with dates:
SN Methods with Description
1
boolean after(Date date)
Returns true if the invoking Date object contains a date that is later than the one specified by date, otherwise,
it returns false
...
3
Object clone( )
Duplicates the invoking Date object
...
Returns 0 if the values are equal
...
Returns a positive value if the invoking object is later
than date
...
Otherwise, it throws a ClassCastException
...
7
long getTime( )
Returns the number of milliseconds that have elapsed since January 1, 1970
...
9
void setTime(long time)
Sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight,
January 1, 1970
10
String toString( )
Converts the invoking Date object into a string and returns the result
...
You can use a simple Date object with toString()method to
print current date and time as follows:
import java
...
Date;
public class DateDemo{
public static void main(String args[]){
// Instantiate a Date object
Date date =newDate();
// display time and date using toString()
System
...
println(date
...
•
You can use the methods before( ), after( ), and equals( )
...
before(new Date (99, 2, 18)) returns true
...
Date Formatting using SimpleDateFormat:
SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner
...
For example:
import java
...
*;
import java
...
*;
public class DateDemo{
public static void main(String args[]){
Date dNow =newDate();
TUTORIALS POINT
Simply Easy Learning
SimpleDateFormat ft =
newSimpleDateFormat("E yyyy
...
dd 'at' hh:mm:ss a zzz");
System
...
println("Current Date: "+ ft
...
07
...
In this pattern, all ASCII letters are reserved as pattern letters,
which are defined as the following:
Character
Description
Example
G
Era designator
AD
Y
Year in four digits
2001
M
Month in year
July or 07
D
Day in month
10
H
Hour in A
...
/P
...
(1~12)
12
H
Hour in day (0~23)
22
M
Minute in hour
30
S
Second in minute
55
S
Millisecond
234
E
Day in week
Tuesday
D
Day in year
360
F
Day of week in month
2 (second Wed
...
M
...
M
...
M
...
M
...
You use a two-letter format, starting
with t and ending in one of the letters of the table given below
...
util
...
format("Current Date/Time : %tc", date );
System
...
printf(str);
}
}
This would produce the following result:
CurrentDate/Time:SatDec1516:37:57 MST 2012
It would be a bit silly if you had to supply the date multiple times to format each part
...
The index must immediately follow the % and it must be terminated by a $
...
util
...
out
...
It indicates that the same argument as in the preceding format specification
should be used again
...
util
...
out
...
S
...
For more details, you can refer to Java Standard
documentation
...
For example:
import java
...
*;
import java
...
*;
public class DateDemo{
public static void main(String args[]){
SimpleDateFormat ft =new SimpleDateFormat("yyyy-MM-dd");
String input = args
...
out
...
parse(input);
System
...
println(t);
}catch(ParseException e){
System
...
println("Unparseable using "+ ft);
}
}
}
A sample run of the above program would produce the following result:
$ java DateDemo
1818-11-11ParsesasWedNov1100:00:00 GMT 1818
$ java DateDemo2007-12-01
2007-12-01ParsesasSatDec0100:00:00 GMT 2007
Sleeping for a While:
You can sleep for any period of time from one millisecond up to the lifetime of your computer
...
util
...
out
...
sleep(5*60*10);
System
...
println(new Date()+"\n");
}catch(Exception e){
System
...
println("Got an exception!");
TUTORIALS POINT
Simply Easy Learning
}
}
}
This would produce the following result:
SunMay0318:04:41 GMT 2009
SunMay0318:04:51 GMT 2009
Measuring Elapsed Time:
Sometimes, you may need to measure point in time in milliseconds
...
util
...
currentTimeMillis();
System
...
println(new Date()+"\n");
Thread
...
out
...
currentTimeMillis();
long diff =end- start;
System
...
println("Difference is : "+ diff);
}catch(Exception e){
System
...
println("Got an exception!");
}
}
}
This would produce the following result:
SunMay0318:16:51 GMT 2009
SunMay0318:16:57 GMT 2009
Differenceis:5993
GregorianCalendar Class:
GregorianCalendar is a concrete implementation of a Calendar class that implements the normal Gregorian
calendar with which you are familiar
...
The getInstance( ) method of Calendar returns a GregorianCalendar initialized with the current date and time in the
default locale and time zone
...
These represent the two eras
defined by the Gregorian calendar
...
2
GregorianCalendar(int year, int month, int date)
TUTORIALS POINT
Simply Easy Learning
Constructs a GregorianCalendar with the given date set in the default time zone with the default locale
...
4
GregorianCalendar(int year, int month, int date, int hour, int minute, int second)
Constructs a GregorianCalendar with the given date and time set for the default time zone with the default
locale
...
6
GregorianCalendar(TimeZone zone)
Constructs a GregorianCalendar based on the current time in the given time zone with the default locale
...
Here is the list of few useful support methods provided by GregorianCalendar class:
SN Methods with Description
1
void add(int field, int amount)
Adds the specified (signed) amount of time to the given time field, based on the calendar's rules
...
3
protected void computeTime()
Overrides Calendar Converts time field values to UTC as milliseconds
...
5
int get(int field)
Gets the value for a given time field
...
7
int getActualMinimum(int field)
Return the minimum value that this field could have, given the current date
...
9
Date getGregorianChange()
Gets the Gregorian Calendar change date
...
11
int getMaximum(int field)
Returns maximum value for the given field
...
13
long getTimeInMillis()
Gets this Calendar's current time as a long
...
15
int getMinimum(int field)
Returns minimum value for the given field
...
17
boolean isLeapYear(int year)
Determines if the given year is a leap year
...
19
void set(int field, int value)
Sets the time field with the given value
...
21
void set(int year, int month, int date, int hour, int minute)
Sets the values for the fields year, month, date, hour, and minute
...
23
void setGregorianChange(Date date)
Sets the GregorianCalendar change date
...
25
void setTimeInMillis(long millis)
Sets this Calendar's current time from the given long value
...
27
String toString()
Return a string representation of this calendar
...
util
...
GregorianCalendar gcalendar =new GregorianCalendar();
// Display current time and date information
...
out
...
out
...
get(Calendar
...
out
...
get(Calendar
...
out
...
get(Calendar
...
out
...
out
...
get(Calendar
...
out
...
get(Calendar
...
out
...
get(Calendar
...
isLeapYear(year)){
System
...
println("The current year is a leap year");
}
else{
System
...
println("The current year is not a leap year");
}
}
}
This would produce the following result:
Date:Apr222009
Time:11:25:27
The current year is not a leap year
For a complete list of constant available in Calendar class, you can refer to standard Java documentation
...
util
...
Java regular
expressions are very similar to the Perl programming language and very easy to learn
...
They can be used to search, edit, or manipulate text and data
...
util
...
The Pattern class
provides no public constructors
...
These methods accept a regular expression as the first
argument
...
Like the Pattern class, Matcher defines no public constructors
...
•
PatternSyntaxException: A PatternSyntaxException object is an unchecked exception that indicates a
syntax error in a regular expression pattern
...
They are created by placing the characters
to be grouped inside a set of parentheses
...
Capturing groups are numbered by counting their opening parentheses from left to right
...
The
groupCount method returns an int showing the number of capturing groups present in the matcher's pattern
...
This group is not included in
the total reported by groupCount
...
util
...
Matcher;
import java
...
regex
...
String line ="This order was places for QT3000! OK?";
String pattern ="(
...
*)";
// Create a Pattern object
Pattern r =Pattern
...
Matcher m = r
...
find()){
System
...
println("Found value: "+ m
...
out
...
group(1));
System
...
println("Found value: "+ m
...
out
...
$
Matches end of line
...
Matches any single character except newline
...
[
...
[^
...
TUTORIALS POINT
Simply Easy Learning
re*
Matches 0 or more occurrences of preceding expression
...
re{ n}
Matches exactly n number of occurrences of preceding expression
...
re{ n, m}
Matches at least n and at most m occurrences of preceding expression
...
(re)
Groups regular expressions and remembers matched text
...
(?> re)
Matches independent pattern without backtracking
...
\W
Matches nonword characters
...
Equivalent to [\t\n\r\f]
...
\d
Matches digits
...
\D
Matches nondigits
...
\Z
Matches end of string
...
\z
Matches end of string
...
\n
Back-reference to capture group number "n"
\b
Matches word boundaries when outside brackets
...
\B
Matches nonword boundaries
...
Matches newlines, carriage returns, tabs, etc
...
2
public int start(int group)
Returns the start index of the subsequence captured by the given group during the previous match operation
...
4
public int end(int group)
Returns the offset after the last character of the subsequence captured by the given group during the previous
match operation
...
2
public boolean find()
Attempts to find the next subsequence of the input sequence that matches the pattern
...
4
public boolean matches()
Attempts to match the entire region against the pattern
...
2
public StringBuffer appendTail(StringBuffer sb)
Implements a terminal append-and-replace step
...
4
public String replaceFirst(String replacement)
Replaces the first subsequence of the input sequence that matches the pattern with the given replacement
string
...
This method produces a String that will work as a
literal replacement s in the appendReplacement method of the Matcher class
...
util
...
Matcher;
import java
...
regex
...
compile(REGEX);
Matcher m = p
...
find()){
count++;
System
...
println("Match number "+count);
System
...
println("start(): "+m
...
out
...
end());
}
}
}
This would produce the following result:
Match number
start():0
end():3
Match number
start():4
end():7
Match number
start():8
end():11
Match number
start():19
end():22
1
2
3
4
You can see that this example uses word boundaries to ensure that the letters "c" "a" "t" are not merely a substring
in a longer word
...
The start method returns the start index of the subsequence captured by the given group during the previous match
operation, and end returns the index of the last character matched, plus one
...
The difference,
however, is that matches requires the entire input sequence to be matched, while lookingAt does not
...
Here is the example explaining the functionality:
import java
...
regex
...
util
...
Pattern;
public class RegexMatches
{
TUTORIALS POINT
Simply Easy Learning
private
private
private
private
static
static
static
static
final String REGEX ="foo";
final String INPUT ="fooooooooooooooooo";
Pattern pattern;
Matcher matcher;
public static void main(String args[]){
pattern =Pattern
...
matcher(INPUT);
System
...
println("Current REGEX is: "+REGEX);
System
...
println("Current INPUT is: "+INPUT);
System
...
println("lookingAt(): "+matcher
...
out
...
matches());
}
}
This would produce the following result:
Current REGEX is: foo
Current INPUT is: fooooooooooooooooo
lookingAt():true
matches():false
The replaceFirst and replaceAll Methods:
The replaceFirst and replaceAll methods replace text that matches a given regular expression
...
Here is the example explaining the functionality:
import java
...
regex
...
util
...
Pattern;
public class RegexMatches
{
private static String REGEX ="dog";
private static String INPUT ="The dog says meow
...
";
private static String REPLACE ="cat";
public static void main(String[] args){
Pattern p =Pattern
...
matcher(INPUT);
INPUT = m
...
out
...
All cats say meow
...
Here is the example explaining the functionality:
import java
...
regex
...
util
...
Pattern;
public class RegexMatches
{
private static String REGEX ="a*b";
private static String INPUT ="aabfooaabfooabfoob";
private static String REPLACE ="-";
public static void main(String[] args){
Pattern p =Pattern
...
matcher(INPUT);
StringBuffer sb =new StringBuffer();
while(m
...
appendReplacement(sb,REPLACE);
}
m
...
out
...
toString());
}
}
This would produce the following result:
-foo-foo-foo-
PatternSyntaxException Class Methods:
A PatternSyntaxException is an unchecked exception that indicates a syntax error in a regular expression pattern
...
2
public int getIndex()
Retrieves the error index
...
4
public String getMessage()
Returns a multi-line string containing the description of the syntax error and its index, the erroneous regular
expression pattern, and a visual indication of the error index within the pattern
...
When you
call the System
...
println method, for example, the system actually executes several statements in order to display
a message on the console
...
Creating a Method:
In general, a method has the following syntax:
modifier returnValueType methodName(list of parameters){
// Method body;
}
A method definition consists of a method header and a method body
...
This defines the access
type of the method
...
The returnValueType is the data type of the value the method
returns
...
In this case, the
returnValueType is the keyword void
...
The method name and the parameter list together
constitute the method signature
...
When a method is invoked, you pass a value to the
parameter
...
The parameter list refers to the type,
order, and number of the parameters of a method
...
Method Body: The method body contains a collection of statements that define what the method does
...
A method with a nonvoid
return value type is called a function; a method with a void return value type is called a procedure
...
This method takes two parameters num1 and
num2 and returns the maximum between the two:
/** Return the max between two numbers */
public static int max(int num1,int num2){
int result;
if(num1 > num2)
result = num1;
else
result = num2;
return result;
}
Calling a Method:
In creating a method, you give a definition of what the method is to do
...
There are two ways to call a method; the choice is based on whether the method returns a value or not
...
A called method returns
control to the caller when its return statement is executed or when its method-ending closing brace is reached
...
For example:
int larger = max(30,40);
If the method returns void, a call to the method must be a statement
...
The following call is a statement:
System
...
println("Welcome to Java!");
Example:
Following is the example to demonstrate how to define a method and how to call it:
public class TestMax{
/** Main method */
public static void main(String[] args){
TUTORIALS POINT
Simply Easy Learning
int i =5;
int j =2;
int k = max(i, j);
System
...
println("The maximum between "+ i +
" and "+ j +" is "+ k);
}
/** Return the max between two numbers */
public static int max(int num1,int num2){
int result;
if(num1 > num2)
result = num1;
else
result = num2;
return result;
}
}
This would produce the following result:
The maximum between 5and2is5
This program contains the main method and the max method
...
The main method's header is always the same, like the one in this example, with the modifiers public and static,
return value type void, method name main, and a parameter of the String[] type
...
The void Keyword:
This section shows how to declare and invoke a void method
...
Example:
public class TestVoidMethod{
public static void main(String[] args){
printGrade(78
...
0){
System
...
println('A');
}
elseif(score >=80
...
out
...
0){
System
...
println('C');
}
elseif(score >=60
...
out
...
out
...
It does not return any value
...
So, it is invoked as a statement in line 3 in the main method
...
Passing Parameters by Values:
When calling a method, you need to provide arguments, which must be given in the same order as their respective
parameters in the method specification
...
For example, the following method prints a message n times:
public static void nPrintln(String message,int n){
for(int i =0; i < n; i++)
System
...
println(message);
}
Here, you can use nPrintln("Hello", 3) to print "Hello" three times
...
However,
the statement nPrintln(3, "Hello") would be wrong
...
This is referred
to as pass-by-value
...
The variable is not affected, regardless of the changes made to the parameter inside the method
...
Example:
Following is a program that demonstrates the effect of passing by value
...
The swap method is invoked by passing two arguments
...
public class TestPassByValue{
public static void main(String[] args){
int num1 =1;
int num2 =2;
System
...
println("Before swap method, num1 is "+num1 +" and num2 is "+ num2);
// Invoke the swap method
swap(num1, num2);
System
...
println("After swap method, num1 is "+num1 +" and num2 is "+ num2);
}
/** Method to swap two variables */
public static void swap(int n1,int n2){
System
...
println("\tInside the swap method");
System
...
println("\t\tBefore swapping n1 is "+ n1+" n2 is "+ n2);
// Swap n1 with n2
int temp = n1;
TUTORIALS POINT
Simply Easy Learning
n1 = n2;
n2 = temp;
System
...
println("\t\tAfter swapping n1 is "+ n1+" n2 is "+ n2);
}
}
This would produce the following result:
Before swap method, num1 is1and num2 is2
Inside the swap method
Before swapping n1 is1 n2 is2
After swapping n1 is2 n2 is1
After swap method, num1 is1and num2 is2
Overloading Methods:
The max method that was used earlier works only with the int data type
...
This is referred to as method
overloading; that is, two methods have the same name but different parameter lists within one class
...
Overloading methods can
make programs clearer and more readable
...
Overloaded methods must have different parameter lists
...
Sometimes there are two or more possible matches for an invocation of a method due to similar
method signature, so the compiler cannot determine the most specific match
...
The Scope of Variables:
The scope of a variable is the part of the program where the variable can be referenced
...
The scope of a local variable starts from its declaration and continues to the end of the block that contains the
variable
...
A parameter is actually a local variable
...
A variable declared in the initial action part of a for loop header has its scope in the entire loop
...
Using Command-‐Line Arguments:
Sometimes you will want to pass information into a program when you run it
...
A command-line argument is the information that directly follows the program's name on the command line when it
is executed
...
they are stored as strings
in the String array passed to main( )
...
length; i++){
System
...
println("args["+ i +"]: "+args[i]);
}
}
}
Try executing this program as shown here:
java CommandLine this is a command line 200-100
This would produce the following result:
args[0]:this
args[1]:is
args[2]: a
args[3]: command
args[4]: line
args[5]:200
args[6]:-100
TUTORIALS POINT
Simply Easy Learning
The Constructors:
A constructor initializes an object when it is created
...
However, constructors have no explicit return type
...
All classes have constructors, whether you define one or not, because Java automatically provides a default
constructor that initializes all member variables to zero
...
Example:
Here is a simple example that uses a constructor:
// A simple constructor
...
out
...
x +" "+ t2
...
Parameters are added to a constructor
in the same way that they are added to a method, just declare them inside the parentheses after the constructor's
name
...
class MyClass{
int x;
// Following is the constructor
MyClass(int i ){
x = i;
}
}
You would call constructor to initialize objects as follows:
public class ConsDemo{
TUTORIALS POINT
Simply Easy Learning
public static void main(String args[]){
MyClass t1 =new MyClass(10);
MyClass t2 =new MyClass(20);
System
...
println(t1
...
x);
}
}
This would produce the following result:
1020
Variable Arguments(var-‐args):
JDK 1
...
The parameter in the
method is declared as follows:
typeName
...
) Only one variable-length parameter may
be specified in a method, and this parameter must be the last parameter
...
Example:
public class VarargsDemo{
public static void main(String args[]){
// Call method with variable args
printMax(34,3,3,2,56
...
numbers){
if(numbers
...
out
...
length; i++)
if(numbers[i]> result)
result = numbers[i];
System
...
println("The max value is "+ result);
}
}
This would produce the following result:
The max value is 56
...
0
The finalize( ) Method:
It is possible to define a method that will be called just before an object's final destruction by the garbage collector
...
For example, you might use finalize( ) to make sure that an open file owned by that object is closed
...
The Java runtime calls that method whenever
it is about to recycle an object of that class
...
The finalize( ) method has this general form:
protected void finalize()
{
// finalization code here
}
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class
...
For example, if your program ends
before garbage collection occurs, finalize( ) will not execute
...
io package contains nearly every class you might ever need to perform input and output (I/O) in
Java
...
The stream in the java
...
A stream can be defined as a sequence of data
...
Java provides strong but flexible support for I/O related to Files and networks but this tutorial covers very basic
functionality related to streams and I/O
...
Though there are many classes related to
byte streams but the most frequently used classes are , FileInputStream andFileOutputStream
...
io
...
txt");
out = new FileOutputStream("output
...
read()) != -1) {
out
...
close();
}
if (out != null) {
out
...
txt with the following content:
This is test for copy file
...
txt file with the same
content as we have in input
...
So let's put above code in CopyFile
...
java
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, where as Java Characterstreams are used
to perform input and output for 16-bit unicode
...
Though internally FileReader uses FileInputStream
and FileWriter uses FileOutputStream but here major difference is that FileReader reads two bytes at a time and
FileWriter writes two bytes at a time
...
io
...
txt");
out = new FileWriter("output
...
read()) != -1) {
out
...
close();
}
if (out != null) {
out
...
txt with the following content:
This is test for copy file
...
txt file with the same
content as we have in input
...
So let's put above code in CopyFile
...
java
TUTORIALS POINT
Simply Easy Learning
$java CopyFile
Standard Streams
All the programming languages provide support for standard I/O where user's program can take input from a
keyboard and then produce output on the computer screen
...
Similar way Java provides
following three standard streams
•
•
•
Standard Input: This is used to feed the data to user's program and usually a keyboard is used as standard
input stream and represented as System
...
Standard Output: This is used to output the data produced by the user's program and usually a computer
screen is used to standard output stream and represented as System
...
Standard Error: This is used to output the error data produced by the user's program and usually a computer
screen is used to standard error stream and represented as System
...
Following is a simple program which creates InputStreamReader to read standard input stream until the user types
a "q":
import java
...
*;
public class ReadConsole {
public static void main(String args[]) throws IOException
{
InputStreamReader cin = null;
try {
cin = new InputStreamReader(System
...
out
...
");
char c;
do {
c = (char) cin
...
out
...
close();
}
}
}
}
Let's keep above code in ReadConsole
...
This program continues
reading and outputting same character until we press 'q':
$javac ReadConsole
...
1
1
e
e
q
q
TUTORIALS POINT
Simply Easy Learning
Reading and Writing Files:
As described earlier, A stream can be defined as a sequence of data
...
Here is a hierarchy of classes to deal with Input and Output streams
...
Objects can be created using the keyword new and there are
several types of constructors available
...
:
InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read the file
...
SN Methods with Description
1
public void close() throws IOException{}
This method closes the file output stream
...
Throws
an IOException
...
Ensures that the close method of this file output stream is
called when there are no more references to this stream
...
3
public int read(int r)throws IOException{}
TUTORIALS POINT
Simply Easy Learning
This method reads the specified byte of data from the InputStream
...
Returns the next byte of
data and -1 will be returned if it's end of file
...
length bytes from the input stream into an array
...
If end of file -1 will be returned
...
Returns an int
...
The input source is a
byte array
...
ByteArrayInputStream bArray = new ByteArrayInputStream(byte []a,
int off,
int len)
Once you have ByteArrayInputStream object in hand then there is a list of helper methods which can be used to
read the stream or to do other operations on the stream
...
Returns an int as the next byte of
data
...
2
public int read(byte[] r, int off, int len)
This method reads upto len number of bytes starting from off from the input stream into an array
...
If end of file -1 will be returned
...
Returns an int that gives the
number of bytes to be read
...
The parameter gives the maximum limit of
bytes that can be read before the marked position becomes invalid
...
This returns the actual number of bytes skipped
...
io
...
size()!= 10 ) {
// Gets the inputs from the user
bOutput
...
in
...
toByteArray();
System
...
println("Print the content");
for(int x= 0 ; x < b
...
out
...
out
...
out
...
read())!= -1) {
System
...
println(Character
...
reset();
}
}
}
Here is the sample run of the above program:
asdfghjkly
Print the content
a
s
d
f
g
h
j
k
l
y
Converting characters to Upper case
A
S
D
F
G
H
J
K
L
Y
DataInputStream
The DataInputStream is used in the context of DataOutputStream and can be used to read primitives
...
SN Methods with Description
1
public final int read(byte[] r, int off, int len)throws IOException
Reads up to len bytes of data from the input stream into an array of bytes
...
2
Public final int read(byte [] b)throws IOException
Reads some bytes from the inputstream an stores in to the byte array
...
3
(a) public final Boolean readBooolean()throws IOException,
(b) public final byte readByte()throws IOException,
(c) public final short readShort()throws IOException
(d) public final Int readInt()throws IOException
These methods will read the bytes from the contained InputStream
...
4
public String readLine() throws IOException
Reads the next line of text from the input stream
...
Example:
Following is the example to demonstrate DataInputStream and DataInputStream
...
txt and convert those lines into capital letters and finally copies them into another file test1
...
import java
...
*;
public class Test{
public static void main(String args[])throws IOException{
DataInputStream d = new DataInputStream(new
FileInputStream("test
...
txt"));
String count;
while((count = d
...
toUpperCase();
System
...
println(u);
out
...
close();
out
...
The stream would create a file, if it doesn't already
exist, before opening it for output
...
Following constructor takes a file name as a string to create an input stream object to write the file:
OutputStream f = new FileOutputStream("C:/java/hello")
Following constructor takes a file object to create an output stream object to write the file
...
SN Methods with Description
1
public void close() throws IOException{}
This method closes the file output stream
...
Throws
an IOException
...
Ensures that the close method of this file output stream is
called when there are no more references to this stream
...
3
public void write(int w)throws IOException{}
This methods writes the specified byte to the output stream
...
length bytes from the mentioned byte array to the OutputStream
...
There are following forms of constructors to create ByteArrayOutputStream objects
Following constructor creates a buffer of 32 byte:
OutputStream bOut = new ByteArrayOutputStream()
Following constructor creates a buffer of size int a:
OutputStream bOut = new ByteArrayOutputStream(int a)
Once you have ByteArrayOutputStream object in hand then there is a list of helper methods which can be used to
write the stream or to do other operations on the stream
...
2
public byte[] toByteArray()
This method creates a newly allocated Byte array
...
Returns the current contents of the output stream as a byte
array
...
Translation will be done according to the default character encoding
...
4
public void write(int w)
Writes the specified array to the output stream
...
6
public void writeTo(OutputStream outSt)
Writes the entire content of this Stream to the specified stream argument
...
io
...
size()!= 10 ) {
// Gets the inputs from the user
bOutput
...
in
...
toByteArray();
System
...
println("Print the content");
for(int x= 0 ; x < b
...
out
...
out
...
out
...
read())!= -1) {
System
...
println(Character
...
reset();
}
TUTORIALS POINT
Simply Easy Learning
}
}
Here is the sample run of the above program:
asdfghjkly
Print the content
a
s
d
f
g
h
j
k
l
y
Converting characters to Upper case
A
S
D
F
G
H
J
K
L
Y
DataOutputStream
The DataOutputStream stream let you write the primitives to an output source
...
DataOutputStream out = DataOutputStream(OutputStream
out);
Once you have DataOutputStream object in hand, then there is a list of helper methods, which can be used to write
the stream or to do other operations on the stream
...
2
Public final int write(byte [] b)throws IOException
Writes the current number of bytes written to this data output stream
...
3
(a) public final void writeBooolean()throws IOException,
(b) public final void writeByte()throws IOException,
(c) public final void writeShort()throws IOException
(d) public final void writeInt()throws IOException
These methods will write the specific primitive type data into the output stream as bytes
...
5
public final void writeBytes(String s) throws IOException
Writes out the string to the underlying output stream as a sequence of bytes
...
Example:
Following is the example to demonstrate DataInputStream and DataOutputStream
...
txt and converts those lines into capital letters and finally copies them into another file test1
...
TUTORIALS POINT
Simply Easy Learning
import java
...
*;
public class Test{
public static void main(String args[])throws IOException{
DataInputStream d = new DataInputStream(new
FileInputStream("test
...
txt"));
String count;
while((count = d
...
toUpperCase();
System
...
println(u);
out
...
close();
out
...
io
...
txt");
for(int x=0; x < bWrite
...
write( bWrite[x] ); // writes the bytes
}
os
...
txt");
int size = is
...
out
...
read() + "
}
is
...
out
...
txt and would write given numbers in binary format
...
File Navigation and I/O:
There are several other classes that we would be going through to get to know the basics of File Navigation and I/O
...
This class is used for creation of
files and directories, file searching, file deletion etc
...
There are following constructors to create a File
object:
Following syntax creates a new File instance from a parent abstract pathname and a child pathname string
...
File(String pathname)
Following syntax creates a new File instance from a parent pathname string and a child pathname string
...
File(URI uri)
Once you have File object in hand then there is a list of helper methods which can be used manipulate the files
...
2
public String getParent()
Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a
parent directory
...
4
public String getPath()
Converts this abstract pathname into a pathname string
...
Returns true if this abstract pathname is absolute, false
otherwise
6
public String getAbsolutePath()
Returns the absolute pathname string of this abstract pathname
...
Returns true if and only if
the file specified by this abstract pathname exists and can be read by the application; false otherwise
...
Returns true if and
only if the file system actually contains a file denoted by this abstract pathname and the application is
allowed to write to the file; false otherwise
...
Returns true if and only if the file
or directory denoted by this abstract pathname exists; false otherwise
10
public boolean isDirectory()
Tests whether the file denoted by this abstract pathname is a directory
...
11
public boolean isFile()
Tests whether the file denoted by this abstract pathname is a normal file
...
Any non-directory file created by a Java
application is guaranteed to be a normal file
...
12
public long lastModified()
Returns the time that the file denoted by this abstract pathname was last modified
...
13
public long length()
Returns the length of the file denoted by this abstract pathname
...
14
public boolean createNewFile() throws IOException
Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does
not yet exist
...
15
public boolean delete()
Deletes the file or directory denoted by this abstract pathname
...
Returns true if and only if the file or directory is successfully
deleted; false otherwise
...
17
public String[] list()
Returns an array of strings naming the files and directories in the directory denoted by this abstract
pathname
...
20
public File[] listFiles()
Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname
...
22
public boolean mkdir()
Creates the directory named by this abstract pathname
...
23
public boolean mkdirs()
Creates the directory named by this abstract pathname, including any necessary but nonexistent parent
directories
...
24
public boolean renameTo(File dest)
Renames the file denoted by this abstract pathname
...
25
public boolean setLastModified(long time)
Sets the last-modified time of the file or directory named by this abstract pathname
...
26
public boolean setReadOnly()
Marks the file or directory named by this abstract pathname so that only read operations are allowed
...
27
public static File createTempFile(String prefix, String suffix, File directory) throws IOException
Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its
name
...
28
public static File createTempFile(String prefix, String suffix) throws IOException
Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its
name
...
Returns abstract
pathname denoting a newly-created empty file
...
Returns zero if the argument is equal to this abstract
pathname, a value less than zero if this abstract pathname is lexicographically less than the argument, or a
value greater than zero if this abstract pathname is lexicographically greater than the argument
...
Returns zero if the argument is equal to this abstract
pathname, a value less than zero if this abstract pathname is lexicographically less than the argument, or a
value greater than zero if this abstract pathname is lexicographically greater than the argument
...
Returns true if and only if the argument is not
null and is an abstract pathname that denotes the same file or directory as this abstract pathname
...
This is just the string returned by the getPath()
method
...
tutorialspoint;
import java
...
File;
public class FileDemo {
public static void main(String[] args) {
File f = null;
String[] strs = {"test1
...
txt"};
try{
// for each string in string array
for(String s:strs )
{
// create new file
f= new File(s);
// true if the file is executable
boolean bool = f
...
getAbsolutePath();
// prints absolute path
System
...
print(a);
// prints
System
...
println(" is executable: "+ bool);
}
}catch(Exception e){
// if any I/O error occurs
e
...
txt and another file test2
...
txt is executable: true
test2
...
FileReader is used for reading streams of characters
...
Following syntax creates a new FileReader, given the File to read from
...
TUTORIALS POINT
Simply Easy Learning
FileReader(FileDescriptor fd)
Following syntax creates a new FileReader, given the name of the file to read from
...
SN
Methods with Description
1
public int read() throws IOException
Reads a single character
...
2
public int read(char [] c, int offset, int len)
Reads characters into an array
...
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
...
The class is used for writing streams of characters
...
Following syntax creates a FileWriter object given a File object
...
FileWriter(File file, boolean append)
Following syntax creates a FileWriter object associated with a file descriptor
...
FileWriter(String fileName)
Following syntax creates a FileWriter object given a file name with a boolean indicating whether or not to append the
data written
...
SN
Methods with Description
1
public void write(int c) throws IOException
Writes a single character
...
3
public void write(String s, int offset, int len)
Write a portion of a String starting from offset and with a length of len
...
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);
TUTORIALS POINT
Simply Easy Learning
char [] a = new char[50];
fr
...
out
...
close();
}
}
This would produce the following result:
This
is
an
example
Directories in Java:
A directory is a File which can contains a list of other files and directories
...
For complete detail check a list of all the methods which you can call on File
object and what are related to directories
...
Failure indicates that
the path specified in the File object already exists, or that the directory cannot be created because the entire
path does not exist yet
...
Following example creates "/tmp/user/java/bin" directory:
import java
...
File;
public class CreateDir {
public static void main(String args[]) {
String dirname = "/tmp/user/java/bin";
File d = new File(dirname);
// Create directory now
...
mkdirs();
}
}
Compile and execute above code to create "/tmp/user/java/bin"
...
If you use a
forward slash (/) on a Windows version of Java, the path will still resolve correctly
...
io
...
list();
// for each name in the path array
for(String path:paths)
{
// prints filename and directory name
System
...
println(path);
}
}catch(Exception e){
// if any error occurs
e
...
txt
test2
...
java
ReadDir
...
An exception can occur for many
different reasons, including the following:
•
A user has entered invalid data
...
•
A network connection has been lost in the middle of communications or the JVM has run out of memory
...
To understand how exception handling works in Java, you need to understand the three categories of exceptions:
•
•
•
Checked exceptions: A checked exception is an exception that is typically a user error or a problem that
cannot be foreseen by the programmer
...
These exceptions cannot simply be ignored at the time of compilation
...
As opposed to checked exceptions, runtime exceptions are ignored at the time of
compilation
...
Errors are typically ignored in your code because you can rarely do anything about an error
...
They are also ignored at the time of compilation
...
lang
...
The exception class is a subclass of the
Throwable class
...
Errors are not normally trapped form the Java programs
...
Errors are generated to indicate errors generated by the
runtime environment
...
Normally programs cannot recover from errors
...
TUTORIALS POINT
Simply Easy Learning
Here is a list of most common checked and unchecked Java's Built-in Exceptions
...
lang
...
Since java
...
Java defines several other types of exceptions that relate to its various class libraries
...
Exception
Description
ArithmeticException
Arithmetic error, such as divide-by-zero
...
ArrayStoreException
Assignment to an array element of an incompatible type
...
IllegalArgumentException
Illegal argument used to invoke a method
...
IllegalStateException
Environment or application is in incorrect state
...
IndexOutOfBoundsException
Some type of index is out-of-bounds
...
NullPointerException
Invalid use of a null reference
...
SecurityException
Attempt to violate security
...
TUTORIALS POINT
Simply Easy Learning
UnsupportedOperationException
An unsupported operation was encountered
...
lang
...
CloneNotSupportedException
Attempt to clone an object that does not implement the Cloneable
interface
...
InstantiationException
Attempt to create an object of an abstract class or interface
...
NoSuchFieldException
A requested field does not exist
...
Exceptions Methods:
Following is the list of important methods available in the Throwable class
...
This message is initialized in
the Throwable constructor
...
3
public String toString()
Returns the name of the class concatenated with the result of getMessage()
4
public void printStackTrace()
Prints the result of toString() along with the stack trace to System
...
5
public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace
...
6
public Throwable fillInStackTrace()
Fills the stack trace of this Throwable object with the current stack trace, adding to any previous
information in the stack trace
...
A try/catch block is placed
around the code that might generate an exception
...
If an exception occurs in
protected code, the catch block (or blocks) that follows the try is checked
...
Example:
The following is an array is declared with 2 elements
...
// File Name : ExcepTest
...
io
...
out
...
out
...
out
...
lang
...
The syntax for multiple catch blocks looks like the following:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}
The previous statements demonstrate three catch blocks, but you can have any number of them after a single try
...
If the data type
of the exception thrown matches ExceptionType1, it gets caught there
...
This continues until the exception either is caught or falls through all catches, in which
case the current method stops execution and the exception is thrown down to the previous method on the call stack
...
try
{
file =newFileInputStream(fileName);
x =(byte) file
...
printStackTrace();
return-1;
}catch(FileNotFoundException f)//Not valid!
{
f
...
The throws
keyword appears at the end of a method's signature
...
Try to understand the different in throws and throw keywords
...
io
...
For example, the following method declares that it throws a RemoteException and an
InsufficientFundsException:
import java
...
*;
public class className
{
public void withdraw(double amount)throws RemoteException,
InsufficientFundsException
{
// Method implementation
}
//Remainder of class definition
}
The finally Keyword
The finally keyword is used to create a block of code that follows a try block
...
TUTORIALS POINT
Simply Easy Learning
Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what
happens in the protected code
...
}
Example:
public class ExcepTest{
public static void main(String args[]){
int a[]=new int[2];
try{
System
...
println("Access element three :"+ a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System
...
println("Exception thrown :"+ e);
}
finally{
a[0]=6;
System
...
println("First element value: "+a[0]);
System
...
println("The finally statement is executed");
}
}
}
This would produce the following result:
Exception thrown :java
...
ArrayIndexOutOfBoundsException:3
First element value:6
The finally statement is executed
Note the following:
•
A catch clause cannot exist without a try statement
...
•
The try block cannot be present without either catch clause or finally clause
...
TUTORIALS POINT
Simply Easy Learning
Declaring you own Exception:
You can create your own exceptions in Java
...
•
If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you
need to extend the Exception class
...
We can define our own Exception class as below:
class MyExceptio nextends Exception{
}
You just need to extend the Exception class to create your own Exception class
...
The following InsufficientFundsException class is a user-defined exception that extends the
Exception class, making it a checked exception
...
Example:
// File Name InsufficientFundsException
...
io
...
amount = amount;
}
public double getAmount()
{
return amount;
}
}
To demonstrate using our user-defined exception, the following CheckingAccount class contains a withdraw()
method that throws an InsufficientFundsException
...
java
import java
...
*;
public class CheckingAccount
{
private double balance;
private int number;
public CheckingAccount(int number)
{
this
...
program
demonstrates
invoking
the
deposit()
and
withdraw()
// File Name BankDemo
...
out
...
");
c
...
00);
try
{
System
...
println("\nWithdrawing $100
...
withdraw(100
...
out
...
");
c
...
00);
}catch(InsufficientFundsException e)
{
System
...
println("Sorry, but you are short $"
+ e
...
printStackTrace();
}
}
}
Compile all the above three files and run BankDemo, this would produce the following result:
Depositing $500
...
Withdrawing $600
...
0
InsufficientFundsException
at CheckingAccount
...
java:25)
at BankDemo
...
java:13)
TUTORIALS POINT
Simply Easy Learning
methods
of
Common Exceptions:
In Java, it is possible to define two categories of Exceptions and Errors
...
Examples
: NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException,
Programmatic exceptions:- These exceptions are thrown explicitly by the application or the API
programmers
...
TUTORIALS POINT
Simply Easy Learning
CHAPTER
20
Java Inheritance
I
nheritance can be defined as the process where one object acquires the properties of another
...
When we talk about inheritance, the most commonly used keyword would be extends and implements
...
By using these keywords we can make one object
acquire the properties of another object
...
Let us see how the extends keyword is used to achieve
inheritance
...
•
Animal is the superclass of Reptile class
...
•
Dog is the subclass of both Mammal and Animal classes
...
We can assure that Mammal is actually an Animal with the use of the instance operator
...
out
...
out
...
out
...
The implements keyword is used by classes by inherit from interfaces
...
Example:
public interface Animal{}
public class Mammal implements Animal{
}
public class Dog extends Mammal{
}
The instanceof Keyword:
Let us use the instanceof operator to check determine whether Mammal is actually an Animal, and dog is actually
an Animal
interfaceAnimal{}
class Mammal implements Animal{}
public class Dog extends Mammal{
public static void main(String args[]){
TUTORIALS POINT
Simply Easy Learning
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
HAS-‐A relationship:
These relationships are mainly based on the usage
...
This relationship helps to reduce duplication of code as well as bugs
...
By having a separate class for Speed, we do not have to put the entire
code that belongs to speed inside the Van class which makes it possible to reuse the Speed class in multiple
applications
...
To achieve
this, the Van class hides the implementation details from the users of the Van class
...
A very important fact to remember is that Java only supports only single inheritance
...
Therefore following is illegal:
public class extendsAnimal,Mammal{}
However, a class can implement one or more interfaces
...
TUTORIALS POINT
Simply Easy Learning
CHAPTER
21
Java Overriding
I
n the previous chapter, we talked about superclasses and subclasses
...
The benefit of overriding is: ability to define a behavior that's specific to the subclass type which means a subclass
can implement a parent class method based on its requirement
...
Example:
Let us look at an example
...
out
...
out
...
move();// runs the method in Animal class
b
...
The reason for this is: In compile time, the check is made on the reference type
...
Therefore, in the above example, the program will compile properly since Animal class has the method move
...
Consider the following example:
class Animal{
public void move(){
System
...
println("Animals can move");
}
}
class Dog extendsAnimal{
public void move(){
System
...
println("Dogs can walk and run");
}
public void bark(){
System
...
println("Dogs can bark");
}
}
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
b
...
java:30: cannot find symbol
symbol : method bark()
location:class Animal
b
...
Rules for method overriding:
• The argument list should be exactly the same as that of the overridden method
...
TUTORIALS POINT
Simply Easy Learning
• The access level cannot be more restrictive than the overridden method's access level
...
• Instance methods can be overridden only if they are inherited by the subclass
...
• A method declared static cannot be overridden but can be re-declared
...
• A subclass within the same package as the instance's superclass can override any superclass method that is
not declared private or final
...
• An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws
exceptions or not
...
The overriding method can throw narrower or fewer
exceptions than the overridden method
...
Using the super keyword:
When invoking a superclass version of an overridden method the super keyword is used
...
out
...
move();// invokes the super class method
System
...
println("Dogs can walk and run");
}
}
public class TestDog{
public static void main(String args[]){
Animal b =new Dog();// Animal reference but Dog object
b
...
The most common use of polymorphism in
OOP, occurs when a parent class reference is used to refer to a child class object
...
In Java, all Java objects are
polymorphic since any object will pass the IS-A test for their own type and for the class Object
...
A reference
variable can be of only one type
...
The reference variable can be reassigned to other objects provided that it is not declared final
...
A reference variable can refer to any object of its declared type or any subtype of its declared type
...
Example:
Let us look at an example
...
Following are true for the
above example:
•
A Deer IS-A Animal
•
A Deer IS-A Vegetarian
•
A Deer IS-A Deer
•
A Deer IS-A Object
When we apply the reference variable facts to a Deer object reference, the following declarations are legal:
Deer d =new Deer();
Animal a = d;
TUTORIALS POINT
Simply Easy Learning
Vegetarian v = d;
Object o = d;
All the reference variables d,a,v,o refer to the same Deer object in the heap
...
We already have discussed method overriding, where a child class can override a method in its parent
...
/* File name : Employee
...
out
...
name = name;
this
...
number = number;
}
public void mailCheck()
{
System
...
println("Mailing a check to "+this
...
address);
}
public String toString()
{
return name +" "+ address +" "+ number;
}
publicString getName()
{
return name;
}
public String getAddress()
{
return address;
}
public void setAddress(String newAddress)
{
address = newAddress;
}
public int getNumber()
{
return number;
}
}
Now suppose we extend Employee class as follows:
/* File name : Salary
...
out
...
out
...
0)
{
salary = newSalary;
}
}
public double computePay()
{
System
...
println("Computing salary pay for "+ getName());
return salary/52;
}
}
Now, you study the following program carefully and try to determine its output:
/* File name : VirtualDemo
...
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
...
While invoking s
...
Invoking mailCheck() on e is quite different because e is an Employee reference
...
mailCheck(), the compiler sees the mailCheck() method in the Employee class
...
At run time, however,
the JVM invokes mailCheck() in the Salary class
...
All
methods in Java behave in this manner, whereby an overridden method is invoked at run time, no matter what data
type the reference is that was used in the source code at compile time
...
An abstract class is one that cannot be
instantiated
...
You just cannot create an instance of the abstract class
...
This is
typically how abstract classes come about during the design phase
...
Abstract Class:
Use the abstract keyword to declare a class abstract
...
/* File name : Employee
...
out
...
name = name;
this
...
number = number;
}
public double computePay()
{
System
...
println("Inside Employee computePay");
return0
...
out
...
name
+" "+this
...
The class is now abstract, but it still has three fields, seven
methods, and one constructor
...
java */
public class AbstractDemo
{
public static void main(String[] args)
{
/* Following is not allowed and would raise error */
Employee e =new Employee("George W
...
out
...
mailCheck();
}
}
When you would compile above class, then you would get the following error:
Employee
...
","Houston, TX",43);
^
1 error
Extending Abstract Class:
We can extend Employee class in normal way as follows:
/* File name : Salary
...
out
...
out
...
0)
{
salary = newSalary;
}
}
public double computePay()
{
System
...
println("Computing salary pay for "+ getName());
return salary/52;
}
}
Here, we cannot instantiate a new Employee, but if we instantiate a new Salary object, the Salary object will inherit
the three fields and seven methods from Employee
...
java */
public class AbstractDemo
{
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
...
Abstract Methods:
If you want a class to contain a particular method but you want the actual implementation of that method to be
determined by child classes, you can declare the method in the parent class as abstract
...
An abstract method consists of a method
signature, but no method body
...
If a class contains an abstract method, the class must be abstract
as well
...
A child class that inherits an abstract method must override it
...
Eventually, a descendant class has to implement the abstract method; otherwise, you would have a hierarchy of
abstract classes that cannot be instantiated
...
java */
public class Salary extends Employee
{
privatedouble salary;// Annual salary
public double computePay()
{
System
...
println("Computing salary pay for "+ getName());
return salary/52;
}
//Remainder of class definition
}
TUTORIALS POINT
Simply Easy Learning
CHAPTER
Java Encapsulation
E
24
ncapsulation is one of the four fundamental OOP concepts
...
Encapsulation is the technique of making the fields in a class private and providing access to the fields via public
methods
...
For this reason, encapsulation is also referred to as data hiding
...
Access to the data and code is tightly controlled by an interface
...
With this feature Encapsulation gives maintainability, flexibility and extensibility to our code
...
java */
public class EncapTest{
private String name;
private String idNum;
private int age;
public int getAge(){
return age;
}
publicString getName(){
return name;
}
publicString getIdNum(){
return idNum;
}
publicvoid setAge(int newAge){
age = newAge;
}
publicvoid setName(String newName){
TUTORIALS POINT
Simply Easy Learning
name = newName;
}
public void setIdNum(String newId){
idNum = newId;
}
}
The public methods are the access points to this class' fields from the outside java world
...
Therefore any class that wants to access the variables should access them
through these getters and setters
...
java */
public class RunEncap{
public static void main(String args[]){
EncapTest encap =new EncapTest();
encap
...
setAge(20);
encap
...
out
...
getName()+" Age : "+ encap
...
A class can have total control over what is stored in its fields
...
A class can change the data type of a field and
users of the class do not need to change any of their code
...
A class implements an interface, thereby inheriting the
abstract methods of the interface
...
Writing an interface is similar to writing a class, but they are two different concepts
...
An interface contains behaviors that a class implements
...
An interface is similar to a class in the following ways:
• An interface can contain any number of methods
...
java extension, with the name of the interface matching the name of the
file
...
class file
...
However, an interface is different from a class in several ways, including:
• You cannot instantiate an interface
...
• All of the methods in an interface are abstract
...
The only fields that can appear in an interface must be declared
both static and final
...
• An interface can extend multiple interfaces
...
Here is a simple example to declare an interface:
Example:
Let us look at an example that depicts encapsulation:
/* File name : NameOfInterface
...
lang
...
You do not need to use the abstract keyword when declaring an interface
...
• Methods in an interface are implicitly public
...
java */
interface Animal{
public void eat();
public void travel();
}
Implementing Interfaces:
When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the
specific behaviors of the interface
...
Aclass uses the implements keyword to implement an interface
...
/* File name : MammalInt
...
out
...
out
...
eat();
m
...
• The signature of the interface method and the same return type or subtype should be maintained when
overriding the methods
...
When implementation interfaces there are several rules:
• A class can implement more than one interface at a time
...
• An interface can extend another interface, similarly to the way that a class can extend another class
...
The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent
interface
...
//Filename: Sports
...
java
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
//Filename: Hockey
...
Similarly, a class that implements Football needs to define the three methods from
Football and the two methods from Sports
...
Multiple inheritance is not allowed
...
The extends keyword is used once, and the parent interfaces are declared in a comma-separated list
...
For
example, the MouseListener interface in the java
...
event package extended java
...
EventListener, which is
defined as:
package java
...
There are two basic design purposes of
tagging interfaces:
Creates a common parent: As with the EventListener interface, which is extended by dozens of other interfaces in
the Java API, you can use a tagging interface to create a common parent among a group of interfaces
...
Adds a data type to a class: This situation is where the term tagging comes from
...
TUTORIALS POINT
Simply Easy Learning
CHAPTER
26
Java Packages
P
ackages are used in Java inorder to prevent naming conflicts, to control access, to make searching/locating
and usage of classes, interfaces, enumerationsss and annotations easier, etc
...
Some of the existing packages in Java are:
• java
...
io - classes for input , output functions are bundled in this package
Programmers can define their own packages to bundle group of classes/interfaces, etc
...
Since the package creates a new namespace there won't be any name conflicts with names in other packages
...
Creating a package:
When creating a package, you should choose a name for the package and put a package statement with that name
at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you
want to include in the package
...
There can be only one package statement in each
source file, and it applies to all types in the file
...
Example:
Let us look at an example that creates a package called animals
...
Put an interface in the package animals:
/* File name : Animal
...
java */
public class MammalInt implements Animal{
public void eat(){
System
...
println("Mammal eats");
}
public void travel(){
System
...
println("Mammal travels");
}
public int noOfLegs(){
return0;
}
public static void main(String args[]){
MammalInt m =new MammalInt();
m
...
travel();
}
}
Now, you compile these two files and put them in a sub-directory called animals and try to run as follows:
$ mkdir animals
$ cp Animal
...
class animals
$ java animals/MammalInt
Mammal eats
Mammal travels
The import Keyword:
If a class wants to use another class in the same package, the package name does not need to be used
...
Example:
Here, a class named Boss is added to the payroll package that already contains Employee
...
package payroll;
public class Boss
{
publicvoid payEmployee(Employee e)
{
e
...
TUTORIALS POINT
Simply Easy Learning
•
The fully qualified name of the class can be used
...
Employee
•
The package can be imported using the import keyword and the wild card (*)
...
*;
•
The class itself can be imported using the import keyword
...
Employee;
Note: A class file can contain any number of import statements
...
The Directory Structure of Packages:
Two major results occur when a class is placed in a package:
•
The name of the package becomes a part of the name of the class, as we just discussed in the previous
section
...
Here is simple way of managing your files in Java:
Put the source code for a class, interface, enumeration, or annotation type in a text file whose name is the simple
name of the type and whose extension is
...
For example:
// File Name :
Car
...
}
Now, put the source file in a directory whose name reflects the name of the package to which the class belongs:
...
java
Now, the qualified class name and pathname would be as below:
•
Class name -> vehicle
...
java (in windows)
In general, a company uses its reversed Internet domain name for its package names
...
com, then all its package names would start with com
...
Each component of the
package name corresponds to a subdirectory
...
apple
...
java source file, it would be
contained in a series of subdirectories like this:
...
java
TUTORIALS POINT
Simply Easy Learning
At the time of compilation, the compiler creates a different output file for each class, interface and enumeration
defined in it
...
class
For example:
// File Name: Dell
...
apple
...
Dell
...
\com\apple\computers\Dell
...
\com\apple\computers\Ups
...
apple
...
*;
Like the
...
class files should be in a series of directories that reflect the package
name
...
class files does not have to be the same as the path to the
...
You
can arrange your source and class directories separately, as:
...
class
By doing this, it is possible to give the classes directory to other programmers without revealing your sources
...
The full path to the classes directory,
system variable
...
class files by adding the package name
to the class path
...
apple
...
class files in
...
Multiple paths should be separated by a semicolon (Windows) or colon
(UNIX)
...
Set CLASSPATH System Variable:
To display the current CLASSPATH variable, use the following commands in Windows and UNIX (Bourne shell):
•
In Windows -> C:\> set CLASSPATH
TUTORIALS POINT
Simply Easy Learning
•
In UNIX -> % echo $CLASSPATH
To delete the current contents of the CLASSPATH variable, use:
•
In Windows -> C:\> set CLASSPATH=
•
In UNIX -> % unset CLASSPATH; export CLASSPATH
To set the CLASSPATH variable:
•
In Windows -> set CLASSPATH=C:\users\jack\java\classes
•
In UNIX -> % CLASSPATH=/home/jack/java/classes; export CLASSPATH
TUTORIALS POINT
Simply Easy Learning
CHAPTER
Java Data Structures
T
27
he data structures provided by the Java utility package are very powerful and perform a wide range of
functions
...
The Enumeration interface defines a means to retrieve successive elements from a data structure
...
The Enumeration interface defines the methods by which you can enumerate (obtain one at a time) the elements in
a collection of objects
...
Although not deprecated, Enumeration is considered
obsolete for new code
...
The methods declared by Enumeration are summarized in the following table:
TUTORIALS POINT
Simply Easy Learning
SN Methods with Description
1
boolean hasMoreElements( )
When implemented, it must return true while there are still more elements to extract, and false
when all the elements have been enumerated
...
Example:
Following is the example showing usage of Enumeration
...
util
...
util
...
add("Sunday");
dayNames
...
add("Tuesday");
dayNames
...
add("Thursday");
dayNames
...
add("Saturday");
days = dayNames
...
hasMoreElements()){
System
...
println(days
...
This class is very useful in cases, where you need to keep up with a set of Boolean values; you just assign a bit to
each value and set or clear it as appropriate
...
The BitSet array can increase in size as needed
...
This is a legacy class but it has been completely re-engineered in Java 2, version 1
...
The BitSet defines two constructors
...
e
...
All bits are initialized
to zero
...
The result is placed
into the invoking object
...
3
int cardinality( )
Returns the number of set bits in the invoking object
...
5
void clear(int index)
Zeros the bit specified by index
...
1
...
8
boolean equals(Object bitSet)
Returns true if the invoking bit set is equivalent to the one passed in bitSet
...
9
void flip(int index)
Reverses the bit specified by index
...
1
...
12
BitSet get(int startIndex, int endIndex)
Returns a BitSet that consists of the bits from startIndex to endIndex
...
The invoking object is not
changed
...
14
boolean intersects(BitSet bitSet)
Returns true if at least one pair of corresponding bits within the invoking object and bitSet are 1
...
16
int length( )
Returns the number of bits required to hold the contents of the invoking BitSet
...
17
int nextClearBit(int startIndex)
Returns the index of the next cleared bit, (that is, the next zero bit), starting from the index
specified by startIndex
18
int nextSetBit(int startIndex)
Returns the index of the next set bit (that is, the next 1 bit), starting from the index specified by
startIndex
...
1 is returned
...
The result is placed
into the invoking object
...
21
void set(int index, boolean v)
Sets the bit specified by index to the value passed in v
...
22
void set(int startIndex, int endIndex)
Sets the bits from startIndex to endIndex
...
23
void set(int startIndex, int endIndex, boolean v)
Sets the bits from startIndex to endIndex
...
true sets the bits, false clears
the bits
...
25
String toString( )
Returns the string equivalent of the invoking BitSet object
...
The result is placed
into the invoking object
Example:
The following program illustrates several of the methods supported by this data structure:
import java
...
BitSet;
public class BitSetDemo{
public static void main(String args[]){
BitSet bits1 =new BitSet(16);
BitSet bits2 =new BitSet(16);
// set some bits
for(int i=0; i<16; i++){
if((i%2)==0) bits1
...
set(i);
}
System
...
println("Initial pattern in bits1: ");
System
...
println(bits1);
System
...
println("\nInitial pattern in bits2: ");
System
...
println(bits2);
// AND bits
bits2
...
out
...
out
...
or(bits1);
System
...
println("\nbits2 OR bits1: ");
System
...
println(bits2);
// XOR bits
bits2
...
out
...
out
...
Like an array, elements of a Vector object can be accessed via an index into the vector
...
Vector implements a dynamic array
...
•
Vector contains many legacy methods that are not part of the collections framework
...
The Vector class supports four constructors
...
The increment specifies the number of elements to allocate each time that a vector is resized upward:
Vector(int size,int incr)
The fourth form creates a vector that contains the elements of collection c:
Vector(Collection c)
Apart from the methods inherited from its parent classes, Vector defines the following methods:
SN Methods with Description
1
void add(int index, Object element)
Inserts the specified element at the specified position in this Vector
...
3
boolean addAll(Collection c)
Appends all of the elements in the specified Collection to the end of this Vector, in the order that
they are returned by the specified Collection's Iterator
...
5
void addElement(Object obj)
Adds the specified component to the end of this vector, increasing its size by one
...
7
void clear()
Removes all of the elements from this Vector
...
9
boolean contains(Object elem)
Tests if the specified object is a component in this vector
...
11
void copyInto(Object[] anArray)
Copies the components of this vector into the specified array
...
13
Enumeration elements()
Returns an enumeration of the components of this vector
...
15
boolean equals(Object o)
Compares the specified Object with this Vector for equality
...
17
Object get(int index)
Returns the element at the specified position in this Vector
...
19
int indexOf(Object elem)
Searches for the first occurence of the given argument, testing for equality using the equals
method
...
21
void insertElementAt(Object obj, int index)
Inserts the specified object as a component in this vector at the specified index
...
23
Object lastElement()
Returns the last component of the vector
...
25
int lastIndexOf(Object elem, int index)
Searches backwards for the specified object, starting from the specified index, and returns an
index to it
...
27
boolean remove(Object o)
Removes the first occurrence of the specified element in this Vector If the Vector does not contain
the element, it is unchanged
...
29
void removeAllElements()
Removes all components from this vector and sets its size to zero
...
31
void removeElementAt(int index)
removeElementAt(int index)
32
protected void removeRange(int fromIndex, int toIndex)
Removes from this List all of the elements whose index is between fromIndex, inclusive and
toIndex, exclusive
...
34
Object set(int index, Object element)
Replaces the element at the specified position in this Vector with the specified element
...
36
void setSize(int newSize)
Sets the size of this vector
...
38
List subList(int fromIndex, int toIndex)
Returns a view of the portion of this List between fromIndex, inclusive, and toIndex, exclusive
...
40
Object[] toArray(Object[] a)
Returns an array containing all of the elements in this Vector in the correct order; the runtime type
of the returned array is that of the specified array
...
42
void trimToSize()
Trims the capacity of this vector to be the vector's current size
...
util
...
out
...
size());
System
...
println("Initial capacity: "+v
...
addElement(newInteger(1));
v
...
addElement(new Integer(3));
v
...
out
...
capacity());
v
...
45));
System
...
println("Current capacity: "+v
...
addElement(new Double(6
...
addElement(new Integer(7));
System
...
println("Current capacity: "+v
...
addElement(new Float(9
...
addElement(new Integer(10));
System
...
println("Current capacity: "+v
...
addElement(new Integer(11));
v
...
out
...
firstElement());
System
...
println("Last element: "+(Integer)v
...
contains(new Integer(3)))
System
...
println("Vector contains 3
...
Enumeration vEnum = v
...
out
...
hasMoreElements())
System
...
print(vEnum
...
out
...
Elements in vector:
12345
...
0879
...
You can think of a stack literally as a vertical stack of objects; when you add a new element, it gets stacked on top
of the others
...
In other words, the last element you added to the stack
is the first one to come back off
...
Stack only defines the default constructor, which creates an empty stack
...
Stack()
Apart from the methods inherited from its parent class Vector, Stack defines the following methods:
SN Methods with Description
1
boolean empty()
Tests if this stack is empty
...
2
Object peek( )
Returns the element on the top of the stack, but does not remove it
...
4
Object push(Object element)
Pushes element onto the stack
...
5
int search(Object element)
Searches for element in the stack
...
TUTORIALS POINT
Simply Easy Learning
Otherwise,
...
Example:
The following program illustrates several of the methods supported by this collection:
import java
...
*;
public class StackDemo{
static void showpush(Stack st,int a){
st
...
out
...
out
...
out
...
pop();
System
...
println(a);
System
...
println("stack: "+ st);
}
public static void main(String args[]){
Stack st =new Stack();
System
...
println("stack: "+ st);
showpush(st,42);
showpush(st,66);
showpush(st,99);
showpop(st);
showpop(st);
showpop(st);
try{
showpop(st);
}catch(EmptyStackException e){
System
...
println("empty stack");
}
}
}
This would produce the following result:
stack:[]
push(42)
stack:[42]
push(66)
stack:[42,66]
push(99)
stack:[42,66,99]
pop ->99
stack:[42,66]
pop ->66
stack:[42]
pop ->42
stack:[]
pop -> empty stack
TUTORIALS POINT
Simply Easy Learning
The Dictionary
The Dictionary class is an abstract class that defines a data structure for mapping keys to values
...
Since the Dictionary class is abstract, it provides only the framework for a key-mapped data structure rather than a
specific implementation
...
Given a key and value, you can store the value in a Dictionary object
...
Thus, like a map, a dictionary can be thought of as a list of key/value pairs
...
2
Object get(Object key)
Returns the object that contains the value associated with key
...
3
boolean isEmpty( )
Returns true if the dictionary is empty, and returns false if it contains at least one key
...
5
Object put(Object key, Object value)
Inserts a key and its value into the dictionary
...
6
Object remove(Object key)
Removes key and its value
...
If key is not in the dictionary, a
null is returned
...
The Dictionary class is obsolete
...
Map Interface
The Map interface maps unique keys to values
...
•
Given a key and a value, you can store the value in a Map object
...
•
Several methods throw a NoSuchElementException when no items exist in the invoking map
...
•
A ClassCastException is thrown when an object is incompatible with the elements in a map
...
•
An UnsupportedOperationException is thrown when an attempt is made to change an unmodifiable map
...
2
boolean containsKey(Object k)
Returns true if the invoking map contains k as a key
...
3
boolean containsValue(Object v)
Returns true if the map contains v as a value
...
4
Set entrySet( )
Returns a Set that contains the entries in the map
...
Entry
...
5
boolean equals(Object obj)
Returns true if obj is a Map and contains the same entries
...
6
Object get(Object k)
Returns the value associated with the key k
...
8
boolean isEmpty( )
Returns true if the invoking map is empty
...
9
Set keySet( )
Returns a Set that contains the keys in the invoking map
...
10
Object put(Object k, Object v)
Puts an entry in the invoking map, overwriting any previous value associated with the key
...
Returns null if the key did not already exist
...
11
void putAll(Map m)
Puts all the entries from m into this map
...
13
int size( )
Returns the number of key/value pairs in the map
...
This method provides a collection-view of
the values in the map
...
util
...
put("Zara","8");
m1
...
put("Ayan","12");
m1
...
out
...
out
...
out
...
For example, in an address list hash table you could store and sort data based on a key such as ZIP code rather
than on a person's name
...
Hashtable was part of the original java
...
However, Java 2 reengineered Hashtable so that it also implements the Map interface
...
It is similar to HashMap, but is synchronized
...
When using a Hashtable, you specify an object that
is used as a key, and the value that you want linked to that key
...
The Hashtable defines four constructors
...
This ratio must be between 0
...
0, and it determines how full the hashtable can be before it is resized upward
...
The capacity of the hashtable is set to twice the number of elements in m
...
75 is used
...
2
Object clone( )
Returns a duplicate of the invoking object
...
Returns false if the value
isn't found
...
Returns false if the key isn't
found
...
Returns false if the value
isn't found
...
7
Object get(Object key)
Returns the object that contains the value associated with key
...
8
boolean isEmpty( )
Returns true if the hash table is empty; returns false if it contains at least one key
...
10
Object put(Object key, Object value)
Inserts a key and a value into the hash table
...
11
void rehash( )
Increases the size of the hash table and rehashes all of its keys
...
Returns the value associated with key
...
13
int size( )
Returns the number of entries in the hash table
...
Example:
The following program illustrates several of the methods supported by this data structure:
import java
...
*;
public class HashTableDemo{
public static void main(String args[]){
// Create a hash map
Hashtable balance =new Hashtable();
TUTORIALS POINT
Simply Easy Learning
Enumeration names;
String str;
double bal;
balance
...
34));
balance
...
22));
balance
...
00));
balance
...
22));
balance
...
08));
// Show all balances in hash table
...
keys();
while(names
...
nextElement();
System
...
println(str +": "+balance
...
out
...
get("Zara"))
...
put("Zara",new Double(bal+1000));
System
...
println("Zara's new balance: "+balance
...
08
Zara:3434
...
22
Daisy:99
...
0
Zara's new balance: 4434
...
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 is a subclass of Hashtable
...
The Properties class is used by many other Java classes
...
getProperties( ) when obtaining environmental values
...
This variable holds a default property list associated with a
Properties object
...
The first version creates a Properties object that has no default values:
Properties()
The second creates an object that uses propDefault for its default values
...
A null object is returned if key is neither in the list nor in the
default property list
...
defaultProperty is returned if key is neither in the list nor in
the default property list
...
4
void list(PrintWriter streamOut)
Sends the property list to the output stream linked to streamOut
...
6
Enumeration propertyNames( )
Returns an enumeration of the keys
...
7
Object setProperty(String key, String value)
Associates value with key
...
8
void store(OutputStream streamOut, String description)
After writing the string specified by description, the property list is written to the output stream
linked to streamOut
...
util
...
put("Illinois","Springfield");
capitals
...
put("Washington","Olympia");
capitals
...
put("Indiana","Indianapolis");
// Show all states and capitals in hashtable
...
keySet();// get set-view of keys
Iterator itr = states
...
hasNext()){
str =(String) itr
...
out
...
getProperty(str)+"
...
out
...
getProperty("Florida","Not Found");
System
...
println("The capital of Florida is "+ str +"
...
Illinois is Springfield
...
California is Sacramento
...
The capital of Florida is NotFound
...
Although these classes were quite useful, they lacked a central, unifying theme
...
The collections framework was designed to meet several goals
...
The implementations for the fundamental collections (dynamic
arrays, linked lists, trees, and hashtables) are highly efficient
...
•
Extending and/or adapting a collection had to be easy
...
Several
standard implementations such as LinkedList, HashSet, and TreeSet, of these interfaces are provided that you
may use as-is and you may also implement your own collection, if you choose
...
All collections
frameworks contain the following:
•
Interfaces: These are abstract data types that represent collections
...
In object-oriented languages, interfaces
generally form a hierarchy
...
e
...
In
essence, they are reusable data structures
...
The algorithms are said to be polymorphic: that is, the same
method can be used on many different implementations of the appropriate collection interface
...
Maps store key/value pairs
...
The Collection Interfaces:
The collections framework defines several interfaces
...
2
The List Interface
This extends Collection and an instance of List stores an ordered collection of elements
...
6
The Map
...
This is an inner class of Map
...
8
The Enumeration
This is legacy interface and defines the methods by which you can enumerate (obtain one at a
time) the elements in a collection of objects
...
The Collection Classes:
Java provides a set of standard collection classes that implement Collection interfaces
...
The standard collection classes are summarized in the following table:
SN Classes with Description
1
AbstractCollection
Implements most of the Collection interface
...
3
AbstractSequentialList
Extends AbstractList for use by a collection that uses sequential rather than random access of its
elements
...
5
ArrayList
Implements a dynamic array by extending AbstractList
...
7
HashSet
Extends AbstractSet for use with a hash table
...
TUTORIALS POINT
Simply Easy Learning
9
TreeSet
Implements a set stored in a tree
...
10
AbstractMap
Implements most of the Map interface
...
12
TreeMap
Extends AbstractMap to use a tree
...
14
LinkedHashMap
Extends HashMap to allow insertion-order iterations
...
The AbstractCollection, AbstractSet, AbstractList, AbstractSequentialList and AbstractMap classes provide skeletal
implementations of the core collection interfaces, to minimize the effort required to implement them
...
util have been discussed in previous tutorial:
SN Classes with Description
1
Vector
This implements a dynamic array
...
2
Stack
Stack is a subclass of Vector that implements a standard last-in, first-out stack
...
4
Hashtable
Hashtable was part of the original java
...
5
Properties
Properties is a subclass of Hashtable
...
6
BitSet
A BitSet class creates a special type of array that holds bit values
...
The Collection Algorithms:
The collections framework defines several algorithms that can be applied to collections and maps
...
Several of the methods can throw a ClassCastException, which occurs when an attempt is made to compare
incompatible types, or an UnsupportedOperationException, which occurs when an attempt is made to modify an
unmodifiable collection
...
All are immutable
...
How to use an Iterator?
Often, you will want to cycle through the elements in a collection
...
The easiest way to do this is to employ an iterator, which is an object that implements either the Iterator or the
ListIterator interface
...
ListIterator extends Iterator to
allow bidirectional traversal of a list and the modification of elements
...
Using Java Iterator
Often, you will want to cycle through the elements in a collection
...
The easiest way to do this is to employ an iterator, which is an object that implements either the Iterator or the
ListIterator interface
...
ListIterator extends Iterator to
allow bidirectional traversal of a list, and the modification of elements
...
Each of the collection classes provides
an iterator( ) method that returns an iterator to the start of the collection
...
In general, to use an iterator to cycle through the contents of a collection, follow these steps:
•
Obtain an iterator to the start of the collection by calling the collection's iterator( ) method
...
Have the loop iterate as long as hasNext( ) returns true
...
For collections that implement List, you can also obtain an iterator by calling ListIterator
...
Otherwise, returns false
...
Throws NoSuchElementException if there is not a next element
...
Throws IllegalStateException if an attempt is made to call remove( ) that is not
preceded by a call to next( )
...
2
boolean hasNext( )
Returns true if there is a next element
...
3
boolean hasPrevious( )
Returns true if there is a previous element
...
4
Object next( )
Returns the next element
...
5
int nextIndex( )
Returns the index of the next element
...
6
Object previous( )
Returns the previous element
...
7
int previousIndex( )
Returns the index of the previous element
...
8
void remove( )
Removes the current element from the list
...
9
void set(Object obj)
Assigns obj to the current element
...
Example:
Here is an example demonstrating both Iterator and ListIterator
...
Of course, ListIterator is available only to those collections that implement the List interface
...
util
...
add("C");
al
...
add("E");
al
...
add("D");
TUTORIALS POINT
Simply Easy Learning
al
...
out
...
iterator();
while(itr
...
next();
System
...
print(element + " ");
}
System
...
println();
// Modify objects being iterated
ListIterator litr = al
...
hasNext()) {
Object element = litr
...
set(element + "+");
}
System
...
print("Modified contents of al: ");
itr = al
...
hasNext()) {
Object element = itr
...
out
...
out
...
out
...
hasPrevious()) {
Object element = litr
...
out
...
out
...
However, it is the comparator that defines precisely
what sorted order means
...
Also, this interface can be used to sort
any instances of any class(even classes we cannot modify)
...
Using Java Comparator
Both TreeSet and TreeMap store elements in sorted order
...
TUTORIALS POINT
Simply Easy Learning
The Comparator interface defines two methods: compare( ) and equals( )
...
This method returns zero if the objects are equal
...
Otherwise, a negative value is returned
...
For example, to sort in reverse order, you
can create a comparator that reverses the outcome of a comparison
...
The method returns true if obj and the invoking object are both Comparator
objects and use the same ordering
...
Overriding equals( ) is unnecessary, and most simple comparators will not do so
...
name)
...
name);
}
// Overriding the compare method to sort the age
public int compare(Dog d, Dog d1){
return d
...
age;
}
}
TUTORIALS POINT
Simply Easy Learning
public class Example{
public static void main(String args[]){
// Takes a list o Dog objects
List
list
...
add(new Dog("Lacy",2));
list
...
add(new Dog("Tommy",4));
list
...
sort(list);// Sorts the array list
for(Dog a: list)//printing the sorted list of names
System
...
print(a
...
sort(list, new Dog());
System
...
println(" ");
for(Dog a: list)//printing the sorted list of ages
System
...
print(a
...
getDogAge() + ", ");
}
}
This would produce the following result:
Lacy, Roger, Shaggy, Tammy, Tommy,
Tammy : 1, Lacy : 2, Shaggy : 3, Tommy
: 4, Roger
: 10,
Note: Sorting of the Arrays class is as the same as the Collections
...
A collection is an object that can hold references to other objects
...
The classes and interfaces of the collections framework are in package java
...
TUTORIALS POINT
Simply Easy Learning
CHAPTER
29
Java Generics
I
t wouldbe nice if we could write a single sort method that could sort the elements in an Integer array, a String
array or an array of any type that supports ordering
...
Generics also provide compile-time type safety that allows programmers to catch invalid types at compile time
...
Generic Methods:
You can write a single generic method declaration that can be called with arguments of different types
...
Following are the rules to define Generic Methods:
•
All generic method declarations have a type parameter section delimited by angle brackets (< and >) that
precedes the method's return type ( < E > in the next example)
...
A type parameter,
also known as a type variable, is an identifier that specifies a generic type name
...
•
A generic method's body is declared like that of any other method
...
Example:
Following example illustrates how we can print array of different type using a single Generic method:
public class GenericMethodTest
{
// generic method printArray
public static< E >void printArray( E[] inputArray )
{
TUTORIALS POINT
Simply Easy Learning
// Display array elements
for( E element : inputArray ){
System
...
printf("%s ", element );
}
System
...
println();
}
public static void main(String args[])
{
// Create arrays of Integer, Double and Character
Integer[] intArray ={1,2,3,4,5};
Double[] doubleArray ={1
...
2,3
...
4};
Character[] charArray ={'H','E','L','L','O'};
System
...
println("Array integerArray contains:");
printArray( intArray );// pass an Integer array
System
...
println("\nArray doubleArray contains:");
printArray( doubleArray );// pass a Double array
System
...
println("\nArray characterArray contains:");
printArray( charArray );// pass a Character array
}
}
This would produce the following result:
Array integerArray contains:
123456
Array doubleArray contains:
1
...
23
...
4
Array characterArray contains:
H E L L O
Bounded Type Parameters:
There may be times when you'll want to restrict the kinds of types that are allowed to be passed to a type
parameter
...
This is what bounded type parameters are for
...
Example:
Following example illustrates how extends is used in a general sense to mean either "extends" (as in classes) or
"implements" (as in interfaces)
...
compareTo( max )>0){
max = y;// y is the largest so far
}
TUTORIALS POINT
Simply Easy Learning
if( z
...
out
...
out
...
1f,%
...
1f is %
...
6,8
...
7,
maximum(6
...
8,7
...
out
...
6,8
...
7is8
...
As with generic methods, the type parameter section of a generic class can have one or more type parameters
separated by commas
...
Example:
Following example illustrates how we can define a generic class:
public class Box
private T t;
publicvoid add(T t){
this
...
add(newInteger(10));
stringBox
...
out
...
get());
System
...
printf("String Value :%s\n", stringBox
...
After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type
information and bytes that represent the object and its data can be used to recreate the object in memory
...
Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for
serializing and deserializing an object
...
Similarly, the ObjectInputStream class
contains the following method for deserializing an object:
public final Object readObject()throws IOException,
ClassNotFoundException
This method retrieves the next Object out of the stream and deserializes it
...
To demonstrate how serialization works in Java, I am going to use the Employee class that we discussed early on in
the book
...
io
...
out
...
io
...
•
All of the fields in the class must be serializable
...
If you are curious to know if a Java Standard Class is serializable or not, check the documentation for the class
...
io
...
Serializing an Object:
The ObjectOutputStream class is used to serialize an Object
...
When the program is done executing, a file named employee
...
The program does not generate any
output, but study the code and try to determine what the program is doing
...
serextension
...
io
...
name ="Reyan Ali";
e
...
SSN =11122333;
e
...
ser");
ObjectOutputStream out=new ObjectOutputStream(fileOut);
out
...
close();
fileOut
...
printStackTrace();
}
}
}
Deserializing an Object:
The following DeserializeDemo program deserializes the Employee object created in the SerializeDemo program
...
io
...
ser");
ObjectInputStream in=new ObjectInputStream(fileIn);
e =(Employee)in
...
close();
fileIn
...
printStackTrace();
return;
}catch(ClassNotFoundException c)
{
System
...
println("Employee class not found");
c
...
out
...
");
System
...
println("Name: "+ e
...
out
...
address);
System
...
println("SSN: "+ e
...
out
...
number);
}
}
This would produce the following result:
DeserializedEmployee
...
For a JVM to be able to deserialize an object, it must be able to find the bytecode for the class
...
•
Notice that the return value of readObject() is cast to an Employee reference
...
The SSN field of the deserialized Employee object is 0
...
The java
...
The java
...
TCP is typically used over the Internet Protocol, which is referred to as TCP/IP
...
This tutorial gives good understanding on the following two subjects:
•
•
Socket Programming: This is most widely used concept in Networking and it has been explained in very
detail
...
Click here to learn about URL Processing in Java
language
...
This section shows you how to write Java programs that communicate with a URL
...
The path is also referred to as the filename, and the
host is also called the authority
...
amrood
...
htm?language=en#j2se
Notice that this URL does not specify a port, in which case the default port for the protocol is used
...
TUTORIALS POINT
Simply Easy Learning
URL Class Methods:
The java
...
URL class represents a URL and has complete set of methods to manipulate URL in Java
...
Creates a URL by putting together the given parts
...
3
public URL(String url) throws MalformedURLException
Creates a URL from the given String
4
public URL(URL context, String url) throws MalformedURLException
Creates a URL by parsing the together the URL and String arguments
The URL class contains many methods for accessing the various parts of the URL being represented
...
2
public String getQuery()
Returns the query part of the URL
...
4
public int getPort()
Returns the port of the URL
...
6
public String getProtocol()
Returns the protocol of the URL
...
8
public String getHost()
Returns the host of the URL
...
10
public String getRef()
Returns the reference part of the URL
...
TUTORIALS POINT
Simply Easy Learning
Example:
The following URLDemo program demonstrates the various parts of a URL
...
// File Name : URLDemo
...
net
...
io
...
out
...
toString());
System
...
println("protocol is "+ url
...
out
...
getAuthority());
System
...
println("file name is "+ url
...
out
...
getHost());
System
...
println("path is "+ url
...
out
...
getPort());
System
...
println("default port is "+ url
...
out
...
getQuery());
System
...
println("ref is "+ url
...
printStackTrace();
}
}
}
A sample run of the thid program would produce the following result:
$ java URLDemo http://www
...
com/index
...
amrood
...
htm?language=en#j2se
protocol is http
authority is www
...
com
file name is/index
...
amrood
...
htm
port is-1
default port is80
query is language=en
refis j2se
URLConnections Class Methods:
The openConnection() method returns a java
...
URLConnection, an abstract class whose subclasses represent
the various types of URL connections
...
•
If you connect to a URL that represents a JAR file, the openConnection() method returns a JarURLConnection
object
...
The URLConnection class has many methods for setting or determining information about the connection, including
the following:
SN Methods with Description
1
Object getContent()
Retrieves the contents of this URL connection
...
3
String getContentEncoding()
Returns the value of the content-encoding header field
...
5
String getContentType()
Returns the value of the content-type header field
...
7
long getExpiration()
Returns the value of the expires header field
...
9
public void setDoInput(boolean input)
Passes in true to denote that the connection will be used for input
...
10
public void setDoOutput(boolean output)
Passes in true to denote that the connection will be used for output
...
11
public InputStream getInputStream() throws IOException
Returns the input stream of the URL connection for reading from the resource
...
If the URL represents an HTTP resource, the connection is cast to HttpURLConnection, and the data in the resource
is read one line at a time
...
java
import java
...
*;
import java
...
*;
public class URLConnDemo
TUTORIALS POINT
Simply Easy Learning
{
public static void main(String[] args)
{
try
{
URL url =new URL(args[0]);
URLConnection urlConnection = url
...
out
...
");
return;
}
BufferedReader in=new BufferedReader(
new InputStreamReader(connection
...
readLine())!=null)
{
urlString += current;
}
System
...
println(urlString);
}catch(IOException e)
{
e
...
amrood
...
a complete HTML content of home page of amrood
...
Socket Programming:
Sockets provide the communication mechanism between two computers using TCP
...
When the connection is made, the server creates a socket object on its end of the communication
...
The java
...
Socket class represents a socket, and the java
...
ServerSocket class provides a mechanism for the
server program to listen for clients and establish connections with them
...
•
The server invokes the accept() method of the ServerSocket class
...
TUTORIALS POINT
Simply Easy Learning
•
After the server is waiting, a client instantiates a Socket object, specifying the server name and port number to
connect to
...
If
communication is established, the client now has a Socket object capable of communicating with the server
...
After the connections are established, communication can occur using I/O streams
...
The client's OutputStream is connected to the server's InputStream, and the
client's InputStream is connected to the server's OutputStream
...
There are
following usefull classes providing complete set of methods to implement sockets
...
net
...
An exception occurs if the port is
already bound by another application
...
3
public ServerSocket(int port, int backlog, InetAddress address) throws IOException
Similar to the previous constructor, the InetAddress parameter specifies the local IP address to
bind to
...
When using this constructor, use the bind() method when you
are ready to bind the server socket
If the ServerSocket constructor does not throw an exception, it means that your application has successfully bound
to the specified port and is ready for client requests
...
This method is useful if you passed in 0 as
the port number in a constructor and let the server find a port for you
...
This method blocks until either a client connects to the server on the
specified port or the socket times out, assuming that the time-out value has been set using the
setSoTimeout() method
...
3
public void setSoTimeout(int timeout)
Sets the time-out value for how long the server socket waits for a client during the accept()
...
Use this method if
you instantiated the ServerSocket using the no-argument constructor
...
After a client does
connect, the ServerSocket creates a new Socket on an unspecified port and returns a reference to this new Socket
...
Socket Class Methods:
The java
...
Socket class represents the socket that both the client and server use to communicate with each
other
...
The Socket class has five constructors that a client uses to connect to a server:
SN Methods with Description
1
public Socket(String host, int port) throws UnknownHostException, IOException
...
If this constructor
does not throw an exception, the connection is successful and the client is connected to the
server
...
3
public Socket(String host, int port, InetAddress localAddress, int localPort) throws
IOException
...
4
public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws
IOException
...
Use the connect() method to connect this socket to a server
...
Some methods of interest in the Socket class are listed here
...
SN Methods with Description
1
public void connect(SocketAddress host, int timeout) throws IOException
This method connects the socket to the specified host
...
2
public InetAddress getInetAddress()
This method returns the address of the other computer that this socket is connected to
...
4
public int getLocalPort()
Returns the port the socket is bound to on the local machine
...
6
public InputStream getInputStream() throws IOException
Returns the input stream of the socket
...
7
public OutputStream getOutputStream() throws IOException
Returns the output stream of the socket
...
Here are following useful methods, which you would need
while doing socket programming:
SN
Methods with Description
1
static InetAddress getByAddress(byte[] addr)
Returns an InetAddress object given the raw IP address
...
3
static InetAddress getByName(String host)
Determines the IP address of a host, given the host's name
...
5
String getHostName()
Gets the host name for this IP address
...
7
String toString()
Converts this IP address to a String
...
// File Name GreetingClient
...
net
...
io
...
parseInt(args[1]);
try
TUTORIALS POINT
Simply Easy Learning
{
System
...
println("Connecting to "+ serverName+" on port "+ port);
Socket client =new Socket(serverName, port);
System
...
println("Just connected to "+ client
...
getOutputStream();
DataOutputStream out=new DataOutputStream(outToServer);
out
...
getLocalSocketAddress());
InputStream inFromServer = client
...
out
...
readUTF());
client
...
printStackTrace();
}
}
}
Socket Server Example:
The following GreetingServer program is an example of a server application that uses the Socket class to listen for
clients on a port number specified by a command-line argument:
// File Name GreetingServer
...
net
...
io
...
setSoTimeout(10000);
}
public void run()
{
while(true)
{
try
{
System
...
println("Waiting for client on port "+
serverSocket
...
");
Socket server = serverSocket
...
out
...
getRemoteSocketAddress());
DataInputStream in=new DataInputStream(server
...
out
...
readUTF());
DataOutputStream out=new DataOutputStream(server
...
writeUTF("Thank you for connecting to "+
server
...
close();
}catch(SocketTimeoutException s)
{
System
...
println("Socket timed out!");
TUTORIALS POINT
Simply Easy Learning
break;
}catch(IOException e)
{
e
...
parseInt(args[0]);
try
{
Thread t =new GreetingServer(port);
t
...
printStackTrace();
}
}
}
Compile client and server and then start server as follows:
$ java GreetingServer6066
Waitingfor client on port 6066
...
0
...
1:6066
Server says Thank you for connecting to /127
...
0
...
•
You can download latest version of JavaMail (Version 1
...
•
You can download latest version of JAF (Version 1
...
1) from Java's standard website
...
You need to add mail
...
jar files in your CLASSPATH
...
Here it is assumed that your localhostis connected
to the internet and capable enough to send an e-mail
...
java
import
import
import
import
java
...
*;
javax
...
*;
javax
...
internet
...
activation
...
String to ="abcd@gmail
...
com";
// Assuming you are sending email from localhost
String host ="localhost";
// Get system properties
Properties properties =System
...
setProperty("mail
...
host", host);
// Get the default Session object
...
getDefaultInstance(properties);
try{
// Create a default MimeMessage object
...
message
...
message
...
RecipientType
...
setSubject("This is the Subject Line!");
// Now set the actual message
message
...
send(message);
System
...
println("Sent message successfully
...
printStackTrace();
}
}
}
Compile and run this program to send a simple e-mail:
$ java SendEmail
Sent message successfully
...
RecipientType type,
Address[] addresses)
throwsMessagingException
Here is the description of the parameters:
•
•
type: This would be set to TO, CC or BCC
...
Example Message
...
TO
addresses: This is the array of e-mail ID
...
Here, it is assumed that your localhostis
connected to the internet and capable enough to send an e-mail
...
Using this example, you can send as big as HTML content you like
...
java
import java
...
*;
import javax
...
*;
TUTORIALS POINT
Simply Easy Learning
import javax
...
internet
...
activation
...
String to ="abcd@gmail
...
com";
// Assuming you are sending email from localhost
String host ="localhost";
// Get system properties
Properties properties =System
...
setProperty("mail
...
host", host);
// Get the default Session object
...
getDefaultInstance(properties);
try{
// Create a default MimeMessage object
...
message
...
message
...
RecipientType
...
setSubject("This is the Subject Line!");
// Send the actual HTML message, as big as you like
message
...
send(message);
System
...
println("Sent message successfully
...
printStackTrace();
}
}
}
Compile and run this program to send an HTML e-mail:
$ java SendHTMLEmail
Sent message successfully
...
Here, it is assumed that yourlocalhost is
connected to the internet and capable enough to send an e-mail
...
java
import
import
import
import
java
...
*;
javax
...
*;
javax
...
internet
...
activation
...
String to ="abcd@gmail
...
com";
// Assuming you are sending email from localhost
String host ="localhost";
// Get system properties
Properties properties =System
...
setProperty("mail
...
host", host);
// Get the default Session object
...
getDefaultInstance(properties);
try{
// Create a default MimeMessage object
...
message
...
message
...
RecipientType
...
setSubject("This is the Subject Line!");
// Create the message part
BodyPart messageBodyPart =new MimeBodyPart();
// Fill the message
messageBodyPart
...
addBodyPart(messageBodyPart);
TUTORIALS POINT
Simply Easy Learning
// Part two is attachment
messageBodyPart =new MimeBodyPart();
String filename ="file
...
setDataHandler(new DataHandler(source));
messageBodyPart
...
addBodyPart(messageBodyPart);
// Send the complete message parts
message
...
send(message);
System
...
println("Sent message successfully
...
printStackTrace();
}
}
}
Compile and run this program to send an HTML e-mail:
$ java SendFileEmail
Sent message successfully
...
setProperty("mail
...
setProperty("mail
...
TUTORIALS POINT
Simply Easy Learning
CHAPTER
33
Java Multithreading
J
ava is a multithreaded programming language which means we can develop multithreaded program using
Java
...
By definition multitasking is when multiple processes share common processing resources such as a CPU
...
Each of the threads can run in parallel
...
Multithreading enables you to write in a way where multiple activities can proceed concurrently in the same
program
...
For example, a thread is born, started, runs, and then dies
...
TUTORIALS POINT
Simply Easy Learning
Above-mentioned stages are explained here:
•
•
•
•
•
New: A new thread begins its life cycle in the new state
...
It is also referred to as a born thread
...
A thread in this state is
considered to be executing its task
...
A thread transitions back to the runnable state only when another thread signals the waiting
thread to continue executing
...
A thread in
this state transitions back to the runnable state when that time interval expires or when the event it is waiting
for occurs
...
Thread Priorities:
Every Java thread has a priority that helps the operating system determine the order in which threads are
scheduled
...
By default, every thread is given priority NORM_PRIORITY (a constant of 5)
...
However, thread priorities cannot guarantee the order in which threads execute and very much
platform dependentant
...
You will need to follow three basic steps:
TUTORIALS POINT
Simply Easy Learning
STEP 1:
As a first step you need to implement a run() method provided by Runnable interface
...
Following is simple syntax of
run() method:
public void run( )
STEP 2:
At second step you will instantiate a Thread object using the following constructor:
Thread(Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the name
given to the new thread
...
Following is simple syntax of start() method:
void start( );
Example:
Here is an example that creates a new thread and starts it running:
class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo( String name){
threadName = name;
System
...
println("Creating " + threadName );
}
public void run() {
System
...
println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System
...
println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while
...
sleep(50);
}
} 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
...
Thread Thread-2 exiting
...
This approach provides more flexibility in handling multiple threads created using available methods in
Thread class
...
This method provides entry point for the thread
and you will put you complete business logic inside this method
...
Following is simple syntax of start() method:
void start( );
Example:
Here is the preceding program rewritten to extend Thread:
TUTORIALS POINT
Simply Easy Learning
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
ThreadDemo( String name){
threadName = name;
System
...
println("Creating " + threadName );
}
public void run() {
System
...
println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System
...
println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while
...
sleep(50);
}
} 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();
ThreadDemo T2 = new ThreadDemo( "Thread-2");
T2
...
Thread Thread-2 exiting
...
SN Methods with Description
1
public void start()
Starts the thread in a separate path of execution, then invokes the run() method on this Thread object
...
3
public final void setName(String name)
Changes the name of the Thread object
...
4
public final void setPriority(int priority)
Sets the priority of this Thread object
...
5
public final void setDaemon(boolean on)
A parameter of true denotes this Thread as a daemon thread
...
7
public void interrupt()
Interrupts this thread, causing it to continue execution if it was blocked for any reason
...
The previous methods are invoked on a particular Thread object
...
Invoking one of the static methods performs the operation on the currently running thread
...
2
public static void sleep(long millisec)
Causes the currently running thread to block for at least the specified number of milliseconds
...
4
public static Thread currentThread()
Returns a reference to the currently running thread, which is the thread that invokes this method
...
TUTORIALS POINT
Simply Easy Learning
Example:
The following ThreadClassDemo program demonstrates some of these methods of the Thread class
...
java
// Create a thread to implement Runnable
public class DisplayMessage implements Runnable
{
private String message;
public DisplayMessage(String message)
{
this
...
out
...
java
// Create a thread to extentd Thread
public class GuessANumber extends Thread
{
private int number;
public GuessANumber(int number)
{
this
...
random() * 100 + 1);
System
...
println(this
...
out
...
getName()
+ " in " + counter + " guesses
...
java
public class ThreadClassDemo
{
public static void main(String [] args)
{
Runnable hello = new DisplayMessage("Hello");
Thread thread1 = new Thread(hello);
thread1
...
setName("hello");
System
...
println("Starting hello thread
...
start();
Runnable bye = new DisplayMessage("Goodbye");
Thread thread2 = new Thread(bye);
thread2
...
MIN_PRIORITY);
thread2
...
out
...
");
thread2
...
out
...
");
Thread thread3 = new GuessANumber(27);
thread3
...
join();
}catch(InterruptedException e)
{
System
...
println("Thread interrupted
...
out
...
");
Thread thread4 = new GuessANumber(75);
thread4
...
out
...
");
}
}
This would produce the following result
...
Starting hello thread
...
Hello
Hello
Hello
Hello
Hello
Hello
Goodbye
Goodbye
Goodbye
Goodbye
Goodbye
...
For example if multiple
threads try to write within a same file then they may corrupt the data because one of the threads can overrite data or
while one thread is opening the same file at the same time another thread might be closing the same file
...
This is implemented using a concept called monitors
...
Only one thread at a time may hold a lock on a
monitor
...
You keep shared resources within this block
...
Now we are going to see two examples where we will print a counter using two different
threads
...
Multithreading example without Synchronization:
Here is a simple example which may or may not print counter value in sequence and every time we run it, it
produces different result based on CPU availability to a thread
...
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() {
PD
...
out
...
");
}
public void start ()
{
TUTORIALS POINT
Simply Easy Learning
System
...
println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t
...
start();
T2
...
join();
T2
...
out
...
3
2
1
2 exiting
...
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 same result every time you run this program:
Starting Thread - 1
Starting Thread - 2
Counter
--5
Counter
--4
Counter
--3
TUTORIALS POINT
Simply Easy Learning
Counter
--2
Counter
--1
Thread Thread - 1
Counter
--5
Counter
--4
Counter
--3
Counter
--2
Counter
--1
Thread Thread - 2
exiting
...
Handling threads inter communication
If you are aware of interprocess communication then it will be easy for you to understand inter thread
communication
...
There are simply three methods and a little trick which makes thread communication possible
...
2
public void notify()
Wakes up a single thread that is waiting on this object's monitor
...
These methods have been implemented as final methods in Object, so they are available in all the classes
...
Example:
This examples shows how two thread can communicate using wait() and notify() method
...
class Chat {
boolean flag = false;
public synchronized void Question(String msg) {
if (flag) {
try {
wait();
} catch (InterruptedException e) {
e
...
out
...
printStackTrace();
}
}
System
...
println(msg);
flag = false;
notify();
}
}
class T1 implements Runnable {
Chat m;
String[] s1 = { "Hi", "How are you ?", "I am also doing fine!" };
public T1(Chat m1) {
this
...
start();
}
public void run() {
for (int i = 0; i < s1
...
Question(s1[i]);
}
}
}
class T2 implements Runnable {
Chat m;
String[] s2 = { "Hi", "I am good, what about you?", "Great!" };
public T2(Chat m2) {
this
...
start();
}
public void run() {
for (int i = 0; i < s2
...
Answer(s2[i]);
}
}
}
public class TestThread {
public static void main(String[] args) {
Chat m = new Chat();
new T1(m);
new T2(m);
}
}
When above program is complied and executed, it produces following result:
Hi
Hi
How are you ?
I am good, what about you?
I am also doing fine!
Great!
TUTORIALS POINT
Simply Easy Learning
Above example has been taken and then modified from [http://stackoverflow
...
Deadlock
occurs when multiple threads need the same locks but obtain them in different order
...
Here is an example:
Example:
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 {
public void run() {
synchronized (Lock2) {
System
...
println("Thread 2: Holding lock 2
...
sleep(10); }
catch (InterruptedException e) {}
System
...
println("Thread 2: Waiting for lock 1
...
out
...
");
}
}
}
}
}
When you compile and execute above program, you find a deadlock situation and below is the output produced by
the program:
Thread
Thread
Thread
Thread
1:
2:
1:
2:
Holding
Holding
Waiting
Waiting
lock 1
...
for lock 2
...
TUTORIALS POINT
Simply Easy Learning
Above program will hang forever because neither of the threads in position to proceed and waiting for each other to
release the lock, so you can come out of the program by pressing CTRL-C
...
start();
T2
...
out
...
");
try { Thread
...
out
...
");
synchronized (Lock2) {
System
...
println("Thread 1: Holding lock 1 & 2
...
out
...
");
try { Thread
...
out
...
");
synchronized (Lock2) {
System
...
println("Thread 2: Holding lock 1 & 2
...
for lock 2
...
lock 1
...
lock 1 & 2
...
TUTORIALS POINT
Simply Easy Learning
Major thread operatios
Core Java provides a complete control over multithreaded program
...
There are various static
methods which you can use on thread objects to control their behavior
...
2
public void stop()
This method stops a thread completely
...
4
public void wait()
Causes the current thread to wait until another thread invokes the notify()
...
Be aware that latest versions of Java has deprecated the usage of suspend( ), resume( ), and stop( ) methods and
so you need to use available alternatives
...
out
...
out
...
out
...
Thread
...
out
...
");
}
System
...
println("Thread " + threadName + " exiting
...
out
...
start ();
}
}
void suspend() {
suspended = true;
}
synchronized void resume() {
suspended = false;
notify();
}
}
public class TestThread {
public static void main(String args[]) {
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1
...
start();
try {
Thread
...
suspend();
System
...
println("Suspending First Thread");
Thread
...
resume();
System
...
println("Resuming First Thread");
R2
...
out
...
sleep(1000);
R2
...
out
...
out
...
out
...
");
R1
...
join();
R2
...
join();
} catch (InterruptedException e) {
System
...
println("Main thread Interrupted");
}
System
...
println("Main thread exiting
...
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting
...
Main thread exiting
...
An applet can be a fully functional Java
application because it has the entire Java API at its disposal
...
applet
...
•
A main() method is not invoked on an applet, and an applet class will not define main()
...
•
When a user views an HTML page that contains an applet, the code for the applet is downloaded to the
user's machine
...
The JVM can be either a plug-in of the Web browser or a separate
runtime environment
...
•
Applets have strict security rules that are enforced by the Web browser
...
•
Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file
...
It is called after the
param tags inside the applet tag have been processed
...
It is also called whenever
the user returns to the page containing the applet after having gone off to other pages
...
It
can, therefore, be called repeatedly in the same applet
...
Because applets are meant to
live on an HTML page, you should not normally leave resources behind after a user leaves the page that
contains the applet
...
The paint() method is actually inherited from the java
...
A "Hello, World" Applet:
The following is a simple applet named HelloWorldApplet
...
applet
...
awt
...
drawString ("Hello World",25,50);
}
}
These import statements bring the classes into the scope of our applet class:
•
java
...
Applet
...
awt
...
Without those import statements, the Java compiler would not recognize the classes Applet and Graphics, which the
applet class refers to
...
applet
...
The base Applet class provides methods that a derived
Applet class may call to obtain information and services from the browser context
...
The viewer may:
TUTORIALS POINT
Simply Easy Learning
•
request information about the author, version and copyright of the applet
•
request a description of the parameters the applet recognizes
•
initialize the applet
•
destroy the applet
•
start the applet's execution
•
stop the applet's execution
The Applet class provides default implementations of each of these methods
...
The "Hello, World" applet is complete as it stands
...
Invoking an Applet:
An applet may be invoked by embedding directives in an HTML file and viewing the file through an applet viewer or
Java-enabled browser
...
Below is an example that invokes the "Hello,
World" applet:
Based on the above examples, here is the live applet example: Applet
Note: You can refer to HTML
Example
...
The code attribute of the
Based on the above examples, here is the live applet example: Applet
Example
...
applet package
...
public void loop(): Causes the audio clip to replay continually
...
To obtain an AudioClip object, you must invoke the getAudioClip() method of the Applet class
...
The audio file is not
downloaded until an attempt is made to play the audio clip
...
applet
...
awt
...
net
...
getAppletContext();
String audioURL =this
...
au";
}
try
{
URL url =new URL(this
...
getAudioClip(url);
}catch(MalformedURLException e)
{
e
...
showStatus("Could not load audio file!");
}
}
public void start()
{
if(clip !=null)
{
TUTORIALS POINT
Simply Easy Learning
clip
...
stop();
}
}
}
Now, let us call this applet as follows:
wav">
You can use your test
...
TUTORIALS POINT
Simply Easy Learning
CHAPTER
35
Java Documentation
T
he Java Language supports three types of comments:
Comment
Description
/* text */
The compiler ignores everything from /* to */
...
/**
documentation */
This is a documentation comment and in general its called doc comment
...
This tutorial is all about explaining Javadoc
...
What is Javadoc?
Javadoc is a tool which comes with JDK and it is used for generating Java code documentation in HTML format
from Java source code which has required documentation in a predefined format
...
*
* @author Zara Ali
* @version 1
...
System
...
println("Hello World!");
}
}
You can include required HTML tags inside the description part, For example, below example makes use of
...
*
* 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 HelloWorld {
public static void main(String[] args) {
/* Prints Hello, World! on standard output
...
out
...
@author name-text
{@code}
Displays text in code font without interpreting the text as HTML
markup or nested javadoc tags
...
@deprecated deprecated-text
@exception
Adds a Throws subheading to the generated documentation,
with the class-name and description text
...
{@link}
Inserts an in-line link with visible text label that points to the
documentation for the specified package, class or member
name of a referenced class
...
class#member
label}
{@linkplain}
Identical to {@link}, except the link's label is displayed in plain
text than code font
...
class#member label}
@param
Adds a parameter with the specified parameter-name followed
by the specified description to the "Parameters" section
...
@return description
@see
Adds a "See Also" heading with a link or text entry that points
to reference
...
@serial field-description |
TUTORIALS POINT
Simply
Easy
Learning
include | exclude
@serialData
Documents the data written by the writeObject( ) or
writeExternal( ) methods
@serialData data-description
@serialField
Documents an ObjectStreamField component
...
@since release
@throws
The @throws and @exception tags are synonyms
...
class#field}
@version
Adds a "Version" subheading with the specified version-text to
the generated docs when the -version option is used
...
You can make use of
other tags based on your requirements
...
html but same time a master
file with a name index
...
import java
...
*;
/**
*
Add Two Numbers!
* The AddNum program implements an application that
* simply adds two given integer numbers and Prints
* the output on the screen
...
*
* @author Zara Ali
* @version 1
...
This is
* a the simplest form of a class method, just to
* show the usage of various javadoc Tags
...
*/
public int addNum(int numA, int numB) {
return numA + numB;
}
/**
* This is the main method which makes use of addNum method
...
* @return Nothing
...
* @see IOException
*/
public static void main(String args[]) throws IOException
{
AddNum obj = new AddNum();
int sum = obj
...
out
...
java file using javadoc utility as follows:
$ javadoc AddNum
...
java
...
Standard Doclet version 1
...
0_51
Building tree for all the packages and classes
...
html
...
java:36: warning - @return tag cannot be used in method with void return
type
...
html
...
html
...
html
...
html
...
Generating /overview-tree
...
Generating /index-all
...
Generating /deprecated-list
...
Building index for all classes
...
html
...
html
...
html
...
html
...
If you are using JDK 1
...
css, so I suggest to download and use standard stylesheet
fromhttp://docs
...
com/javase/7/docs/api/stylesheet
...
lang, which provides classes that are fundamental to the design of
the Java programming language
...
Here is the list of classes of ackage java
...
These classes are very important to know for a Java programmer
...
For a further drill, you can refer standard Java
documentation
...
3
Character
The Character class wraps a value of the primitive type char in an object
...
5
ClassLoader
A class loader is an object that is responsible for loading classes
...
7
Double
The Double class wraps a value of the primitive type double in an object
...
9
Integer
The Integer class wraps a value of the primitive type int in an object
...
11
Math
The class Math contains methods for performing basic numeric operations such as the elementary
exponential, logarithm, square root, and trigonometric functions
...
13
Object
Class Object is the root of the class hierarchy
...
15
Process
The Runtime
...
16
Runtime
Every Java application has a single instance of class Runtime that allows the application to interface with the
environment in which the application is running
...
18
SecurityManager
The security manager is a class that allows applications to implement a security policy
...
20
StackTraceElement
An element in a stack trace, as returned by Throwable
...
21
StrictMath
The class StrictMath contains methods for performing basic numeric operations such as the elementary
exponential, logarithm, square root, and trigonometric functions
...
23
StringBuffer
A string buffer implements a mutable sequence of characters
...
25
Thread
A thread is a thread of execution in a program
...
27
ThreadLocal
This class provides thread-local variables
...
29
Void
The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the
Java keyword void
Description: Know every rules,steps, guidance and be outstanding in JAVA programming language through the help of this eBook