Java in Easy
Ways
JAVA AN INTRODUCTION
Introduction to Java
Java is a simple and yet powerful object oriented programming language and it is in
many respects similar to C++. Java was given birth at Sun Microsystems, Inc. in 1991. Java was
conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at
Sun Microsystems, Inc. It was developed to provide a platform-independent programming
language.
Java (with a capital J) is a high-level, third generation programming language, like C, Fortran,
Smalltalk, Perl, and many others. You can use Java to write computer applications that crunch
numbers, process words, play games, store data or do any of the thousands of other things
computer software can do.
Platform independent
Unlike many other programming languages including C and C++ when Java is compiled, it is not
compiled into platform specific machine, rather into platform independent byte code. This byte
code is distributed over the web and interpreted by Java virtual Machine (JVM) on whichever
platform it is being run.
Compared to other programming languages, Java is most similar to C. However although Java
shares much of C's syntax, it is not C. Knowing how to program in C or, better yet, C++, will
certainly help you to learn Java more quickly, but you don't need to know C to learn Java. Unlike
C++ Java is not a superset of C. A Java compiler won't compile C code, and most large C
programs need to be changed substantially before they can become Java programs.
Java was designed with a concept of ‘write once and run everywhere’. Java Virtual Machine
plays the central role in this concept. The Java Virtual Machine (JVM) is the environment in
which Java programs execute. It is a software that is implemented on top of real hardware and
operating system. When Java source code (.java files) is compiled, it is translated into Java
bytecodes and then placed into (.class) files. The JVM executes Java bytecodes. So Java
bytecodes can be thought of as the machine language of the JVM. A Java virtual machine can
either interpret the bytecode one instruction at a time or the bytecode can be compiled further for
the real microprocessor using what is called a just-in-time compiler. The JVM must be
implemented on a particular platform before compiled Java programs can run on that platform.
Reusability of Code
Java is Distributed
With extensive set of routines to handle TCP/IP protocols like HTTP and FTP java can open and
access the objects across net via URLs.
Java is Multithreaded
One of the powerful aspects of the Java language is that it allows multiple threads of execution to
run concurrently within the same program A single Java program can have many different
threads executing independently and continuously. Multiple Java applets can run on the browser
at the same time sharing the CPU time.
Java is Secure
Java was designed to allow secure execution of code across network. To make Java secure many
of the features of C and C++ were eliminated. Java does not use Pointers. Java programs cannot
access arbitrary addresses in memory.
Garbage collection
Automatic garbage collection is another great feature of Java with which it prevents inadvertent
corruption of memory. Similar to C++, Java has a new operator to allocate memory on the heap
for a new object. But it does not use delete operator to free the memory as it is done in C++ to
free the memory if the object is no longer needed. It is done automatically with garbage
collector.
Application of Java
Java has evolved from a simple language providing interactive dynamic content for web pages to
a predominant enterprise-enabled programming language suitable for developing significant and
critical applications. Today, Java is used for many types of applications including Web based
applications, Financial applications, Gaming applications, embedded systems, Distributed
enterprise applications, mobile applications, Image processors, desktop applications and many
more.
The most special about Java in relation to other programming languages is that it lets you write
special programs called applets that can be downloaded from the Internet and played safely
within a web browser. Traditional computer programs have far too much access to your system
to be downloaded and executed willy-nilly. Although you generally trust the maintainers of
various ftp archives and bulletin boards to do basic virus checking and not to post destructive
software, a lot still slips through the cracks. Even more dangerous software would be
promulgated if any web page you visited could run programs on your system.
Java C++
Method bodies must be defined inside the class Method bodies must be defined inside the class
Data type defines a set of permitted values on which the legal operations can be
performed. In java, all the variables needs to be declared first i.e. before using a particular
variable, it must be declared in the program for the memory allocation process. Like
int pedal = 1;
This statement exists a field named "pedal" that holds the numerical value as 1. The value
assigned to a variable determines its data type, on which the legal operations of java are
performed. This behavior specifies that, Java is a strongly-typed programming language.
The data types in the Java programming language are divided into two categories and can be
explained using the following hierarchy structure :
The primitive data types are predefined data types, which always hold the value of the same
data type, and the values of a primitive data type don't share the state with other primitive
values. These data types are named by a reserved keyword in Java programming language.
There are eight primitive data types supported by Java programming language :
byte
The byte data type is an 8-bit signed two's complement integer. It ranges from -128 to127
(inclusive). This type of data type is useful to save memory in large arrays.. We can also use
byte instead of int to increase the limit of the code. The syntax of declaring a byte type variable
is shown as:
byte b = 5;
short
The short data type is a 16-bit signed two's complement integer. It ranges from -32,768 to
32,767. short is used to save memory in large arrays. The syntax of declaring a short type
variable is shown as:
short s = 2;
int
The int data type is used to store the integer values not the fraction values. It is a 32-bit signed
two's complement integer data type. It ranges from -2,147,483,648 to 2,147,483,647 that is more
enough to store large number in your program. However for wider range of values use long. The
syntax of declaring a int type variable is shown as:
long
The long data type is a 64-bit signed two's complement integer. It ranges from
long ln = 746;
float
The float data type is a single-precision 32-bit IEEE 754 floating point. It ranges from
1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative). Use a float
(instead of double) to save memory in large arrays. We do not use this data type for the exact
values such as currency. For that we have to use java.math.BigDecimal class. The syntax of
declaring a float type variable is:
float f = 105.65;
float f = -5000.12;
double
This data type is a double-precision 64-bit IEEE 754 floating point. It ranges from
4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). This data
type is generally the default choice for decimal values. The syntax of declaring a double type
variable is shown as:
double d = 6677.60;
char
The char data type is a single 16-bit, unsigned Unicode character. It ranges from 0 to 65,535.
They are not integral data type like int, short etc. i.e. the char data type can't hold the numeric
values. The syntax of declaring a char type variable is shown as:
boolean
The boolean data type represents only two values: true and false and occupy is 1-bit in the
memory. These values are keywords in Java and represents the two boolean states: on or off,
yes or no. We use boolean data type for specifying conditional statements as if, while, do, for.
In Java, true and false are not the same as True and False. They are defined constants of the
language. The syntax of declaring a boolean type variable is shown as:
Occupy 8 bits
Byte -128 +127
in memory
Occupy 16
Short bits in -32768 +32767
memory
Occupy 32
Int bits in -2147483648 +2147483647
memory
Occupy 64
Long bits in -9223372036854775808 +9223372036854775807
memory
0
1
123
-42000
Floating-point numbers
A floating-point number represents a real number that may have a fractional values i.e. In the
floating type of variable, you can assign the numbers in an in a decimal or scientific notation.
Floating-point number have only a limited number of digits, where most values can be
represented only approximately. The floating-point types are float and double with a single-
precision 32-bit IEEE 754 floating point and double-precision 64-bit IEEE 754 floating point
respectively. Examples of floating-point literals are:
10.0003
48.9
-2000.15
7.04e12
In Java a reference data type is a variable that can contain the reference or an address of
dynamically created object. These type of data type are not predefined like primitive data type.
The reference data types are arrays, classes and interfaces that are made and handle according
to a programmer in a java program which can hold the three kind of values as:
array type
// Points to an array instance
class type
// Points to an object or a class instance
interface type
// Points to an object and a method, which is
implemented to the corresponding interface
Interface Type:
Java provides an another kind of reference data type or a mechanism to support multiple
inheritance feature called an interface. The name of an interface can be used to specify the type
of a reference. A value is not allowed to be assign to a variable declared using an interface type
until the object implements the specified interface.
When a class declaration implements an interface, that class inherits all of the variables and
methods declared in that interface. So the implementations for all of the methods declared in the
interface must be provided by that class. For example, Java provides an interface called
ActionListener whose method named actionPerformed() is used to handle the different kind of
event . Java also provides a class called Thread that implements Runnable interface.
Thus the following assignment can be allowed:
Runnable r;
r = new Thread();
Operators IN JAVA
Java provides a rich operator environment. Most of its operators can be divided
into the following four groups: arithmetic, bitwise, relational, and logical. Java also
defines some additional operators that handle certain special situations.
One of the most common operators that encounter is the simple assignment operator "=". it
assigns the value on its right to the operand on its left:
int cadence = 0;
int speed = 0;
int gear = 1;
The Java programming language provides operators that perform addition, subtraction,
multiplication, and division. There's a good chance you'll recognize them by their counterparts in
basic mathematics. The only symbol that might look new to you is "%", which divides one
operand by another and returns the remainder as its result. Operator Result
+ Addition
– Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
–= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
– – Decrement
class ArithmeticDemo {
}
}
You can also combine the arithmetic operators with the simple assignment operator to create
compound assignments. For example, x+=1; and x=x+1; both increment the value of x by 1.
The + operator can also be used for concatenating (joining) two strings together, as shown in the
following ConcatDemo program:
class ConcatDemo {
public static void main(String[] args){
String firstString = "This is";
String secondString = " a concatenated string.";
String thirdString = firstString+secondString;
System.out.println(thirdString);
}
}
By the end of this program, the variable thirdString contains "This is a concatenated string.",
which gets printed to standard output.
The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the
integral types, making every "0" a "1" and every "1" a "0". For example, a byte contains 8 bits;
applying this operator to a value whose bit pattern is "00000000" would change its pattern to
"11111111".
The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift
operator ">>" shifts a bit pattern to the right. The bit pattern is given by the left-hand operand,
and the number of positions to shift by the right-hand operand. The unsigned right shift operator
">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on
sign extension.
The following program, BitDemo, uses the bitwise AND operator to print the number "2" to
standard output.
class BitDemo {
public static void main(String[] args) {
int bitmask = 0x000F;
int val = 0x2222;
System.out.println(val & bitmask); // prints "2"
}
}
The Equality and Relational Operators
The equality and relational operators determine if one operand is greater than, less than, equal to,
or not equal to another operand. The majority of these operators will probably look familiar to
you as well. Keep in mind that you must use "==", not "=", when testing if two primitive values
are equal.
== equal to
!= not equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to
The following program, ComparisonDemo, tests the comparison operators:
class ComparisonDemo {
int value1 = 1;
int value2 = 2;
if(value1 == value2) System.out.println("value1 == value2");
if(value1 != value2) System.out.println("value1 != value2");
if(value1 > value2) System.out.println("value1 > value2");
if(value1 < value2) System.out.println("value1 < value2");
if(value1 <= value2) System.out.println("value1 <= value2");
}
}
Output:
value1 != value2
value1 < value2
value1 <= value2
The && and || operators perform Conditional-AND and Conditional-OR operations on two
boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the
second operand is evaluated only if needed.
&& Conditional-AND
|| Conditional-OR
class ConditionalDemo1 {
}
}
Another conditional operator is ?:, which can be thought of as shorthand for an if-then-else
statement (discussed in the Control Flow Statements section of this lesson). This operator is also
known as the ternary operator because it uses three operands. In the following example, this
operator should be read as: "If someCondition is true, assign the value of value1 to result.
Otherwise, assign the value of value2 to result."
There are two types of decision making statements in Java. They are:
if statements
switch statements
The if Statement:
Syntax:
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. If not the first set of code after the end of the if statement(after the closing curly brace)
will be executed.
Example:
if( x < 20 ){
System.out.print("This is if statement");
}
}
}
This is if statement
An if statement can be followed by an optional else statement, which executes when the Boolean
expression is false.
Syntax:
if(Boolean_expression){
//Executes when the Boolean expression is true
}else{
//Executes when the Boolean expression is false
}
Example:
if( x < 20 ){
System.out.print("This is if statement");
}else{
System.out.print("This is else statement");
}
}
}
An if statement can be followed by an optional else if...else statement, which is very usefull to
test various conditions using single if...else if statement.
When using if , else if , else statements there are few points to keep in mind.
An if can have zero or one else's and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
Compilation : Randjithkumar, B.Tech
Page 15
JAVA IN EASY WAYS
Once an else if succeeds, none of he remaining else if's or else's will be tested.
Syntax:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
}else {
//Executes when the none of the above condition is true.
}
Example:
if( x == 10 ){
System.out.print("Value of X is 10");
}else if( x == 20 ){
System.out.print("Value of X is 20");
}else if( x == 30 ){
System.out.print("Value of X is 30");
}else{
System.out.print("This is else statement");
}
}
}
Value of X is 30
It is always legal to nest if-else statements, which means you can use one if or else if statement
inside another if or else if statement.
Syntax:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}
}
You can nest else if...else in the similar way as we have nested if statement.
Example:
if( x == 30 ){
if( y == 10 ){
System.out.print("X = 30 and Y = 10");
}
}
}
X = 30 and Y = 10
A switch statement allows a variable to be tested for equality against a list of values. Each value
is called a case, and the variable being switched on is checked for each case.
Syntax:
switch(expression){
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}
The variable used in a switch statement can only be a byte, short, int, or char.
You can have any number of case statements within a switch. Each case is followed by
the value to be compared to and a colon.
The value for a case must be the same data type as the variable in the switch, and it must
be a constant or a literal.
When the variable being switched on is equal to a case, the statements following that case
will execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control jumps
to the next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true.
No break is needed in the default case.
Example:
switch(grade)
{
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Branching Statements
The break and continue statements, which are covered next, can be used with or without a label.
A label is an identifier placed before a statement; it is followed by a colon (:).
statementName: someStatement;
int i = 0;
boolean foundIt = false;
if (arrayOfInts[i] == searchfor) {
foundIt = true;
break;
}
}
if (foundIt) {
System.out.println("Found " + searchfor
+ " at index " + i);
} else {
System.out.println(searchfor
+ "not in the array");
}
}
}
The break statement, shown in boldface, terminates the for loop when the value is found. The
flow of control transfers to the statement following the enclosing for, which is the print statement
at the end of the program.
Found 12 at index 4
The unlabeled form of the break statement is used to terminate the innermost switch, for, while,
or do-while statement; the labeled form terminates an outer statement, which is identified by the
label specified in the break statement. The following program, BreakWithLabelDemo is similar
to the previous one, but it searches for a value in a two-dimensional array. Two nested for loops
traverse the array. When the value is found, a labeled break terminates the statement labeled
search, which is the outer for loop.
int i = 0;
int j = 0;
boolean foundIt = false;
search:
for ( ; i < arrayOfInts.length; i++) {
if (foundIt) {
System.out.println("Found " + searchfor +
" at " + i + ", " + j);
} else {
System.out.println(searchfor
+ "not in the array");
}
}
}
This is the output of the program.
Found 12 at 1, 0
This syntax can be a little confusing. The break statement terminates the labeled statement; it
does not transfer the flow of control to the label. The flow of control is transferred to the
statement immediately following the labeled (terminated) statement.
if (searchMe.charAt(i) != 'p')
continue;
//process p's
numPs++;
searchMe.setCharAt(i, 'P');
}
System.out.println("Found " + numPs
+ " p's in the string.");
System.out.println(searchMe);
}
}
Here is the output of this program.
The labeled form of the continue statement skips the current iteration of an outer loop marked
with the given label. The following example program, ContinueWithLabelDemo, uses nested
loops to search for a substring within another string. Two nested loops are required: one to iterate
over the substring and one to iterate over the string being searched. This program uses the
labeled form of continue to skip an iteration in the outer loop.
test:
for (int i = 0; i <= max; i++) {
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++)
!= substring.charAt(k++)) {
continue test;
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? "Found it" :"Didn't find it");
}
}
Here is the output from this program.
Found it
return ++count;
The data type of the value returned by return must match the type of the method's declared return
value. When a method is declared void, use the form of return that doesn't return a value.
return;
Java loops
There may be a sitution when we need to execute a block of code several number of times, and is
often referred to as a loop.
Java has very flexible three looping mechanisms. You can use one of the following three loops:
while Loop
do...while Loop
for Loop
As of java 5 the enhanced for loop was introduced. This is mainly used for Arrays.
A while loop is a control structure that allows you to repeat a task a certain number of times.
Syntax:
while(Boolean_expression)
{
//Statements
}
When executing, if the boolean_expression result is true then the actions inside the loop will be
executed. This will continue as long as the expression result is true.
Here key point of the while loop is that the loop might not ever run. When the expression is
tested and the result is false, the loop body will be skipped and the first statement after the while
loop will be executed.
Example:
while( x < 20 ){
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute
at least one time.
Syntax:
Do
{
//Statements
}while(Boolean_expression);
Notice that the Boolean expression appears at the end of the loop, so the statements in the loop
execute once before the Boolean is tested.
If the Boolean expression is true, the flow of control jumps back up to do, and the statements in
the loop execute again. This process repeats until the Boolean expression is false.
Example:
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
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.
A for loop is useful when you know how many times a task is to be repeated.
Syntax:
1. The initialization step is executed first, and only once. This step allows you to declare
and initialize any loop control variables. You are not required to put a statement here, as
long as a semicolon appears.
2. Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If
it is false, the body of the loop does not execute and flow of control jumps to the next
statement past the for loop.
3. After the body of the for loop executes, the flow of control jumps back up to the update
statement. This statement allows you to update any loop control variables. This statement
can be left blank, as long as a semicolon appears after the Boolean expression.
4. The Boolean expression is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then update step,then Boolean expression). After the
Boolean expression is false, the for loop terminates.
Example:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
Java is an Object Oriented Language. 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
Object - Objects have states and behaviors. Example: A dog has states-color, name,
breed as well as behaviors -wagging, barking, eating. An object is an instance of a class.
Class - A class can be defined as a template/ blue print that describe the behaviors/states
that object of its type support.
Objects in Java:
The real-world we can find many objects around us, Cars, Dogs, Humans etc. All these
objects have a state and behavior.
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.
Software objects also have a state and behavior. A software object's state is stored in
fields and behavior is shown via methods.
So in software development methods operate on the internal state of an object and the
object-to-object communication is done via methods.
Classes in Java:
void barking(){
}
void hungry(){
}
void sleeping(){
}
}
A class can contain any of the following variable types.
Instance variables . Instance variables are variables within a class but outside any
method. These variables are instantiated when the class is loaded. Instance
variables can be accessed from inside any method, constructor or blocks of that
particular class.
Class variables . Class variables are variables declared with in a class, outside any
method, with the static keyword.
A class can have any number of methods to access the value of various kind of methods.
In the above example, barking(), hungry() and sleeping() are variables.
Therefore in-order for us to run this Employee class there should be main method and
objects should be created. We will be creating a separate class for these tasks.
Given below is the EmployeeTest class which creates two instances of the class Employee
and invokes the methods for each object to assign values for each variable.
import java.io.*;
public class EmployeeTest{
public static void main(String args[]){
/* Create two objects using constructor */
Employee empOne = new Employee("James Smith");
Employee empTwo = new Employee("Mary Anne");
empTwo.empAge(21);
empTwo.empDesignation("Software Engineer");
empTwo.empSalary(500);
empTwo.printEmployee();
}
}
Arrays
An array is a container object that holds a fixed number of values of a single type. The length of
an array is established when the array is created.
Each item in an array is called an element, and each element is accessed by its numerical index.
As shown in the above illustration, numbering begins with 0. The 9th element, for example,
would therefore be accessed at index 8.
Creating Arrays
The length of an array is fixed at the time of its creation. An array represents related entities
having the same data type in contiguous or adjacent memory locations. The related data having
data items form a group and are referred to by the same name.
Here, the employee is the name of the array and of size 5. The complete set of values is known as
an array and the individual entities are called as elements of the array.
A specific value in an array is accessed by placing the index value of the desired element in a
square bracket.
1. You can refer to a large number of elements by just specifying the index number and the
array name.
2. Arrays make it easy to do calculations in a loop.
One-dimensional arrays
two-dimensional arrays
One-dimensional Arrays
For e.g.
For e.g.
Two-dimensional Arrays
In additions to one-dimensional arrays, you can create two-dimensional arrays. To declare two-
dimensional arrays, you need to specify multiple square brackets after the array name.
For e.g.
In a two-dimensional array,
For e.g.
Accessing Arrays
To access various elements of an array to assign, retrieve, and manipulate the values stored in the
array.
1. Tto specify the name of the array and the index number of the element.
2. The index position of the first element in the array is 0.
For e.g.
String designations[];
designations[1]=”Managing Director”;
You can declare and allocate memory to a user-defined array in a single statement.
Syntax
For e.g.
You can also declare and initialize arrays in the same statement.
For e.g.
To access values from elements in the array by referring to the element by its index number.
For e.g.
String designations[];
designations[2]=”Managing Director”;
designations[0]=designations[2];
In the above example, the value of the third element of the array is assigned to the first element
of the array.
import java.io.*;
class student
int regno,total;
int mark[];
String name;
regno=r;
name=n;
for(int i=0;i<3;i++)
mark[i]=m[i];
if(mark[i]>50)
total+=mark[i];
else
total=0;
break;
System.out.println("NAME:"+name);
System.out.println("REGNO:"+regno);
System.out.println("TOTAL:"+total);
class secondsample
int mk2[]={71,85,95};
st[0]=new student(1,"Ganguly",mk1);
st[1]=new student(2,"Sachin",mk2);
for(int i=0;i<2;i++)
st[i].displaystudent();
Output
javac secondsample.java
java secondsample
NAME:Ganguly
REGNO:1
TOTAL:253
NAME:Sachin
REGNO:2
TOTAL:251
The String class is defined in the java.lang package and hence is implicitly available to all the
programs in Java. The String class is declared as final, which means that it cannot be subclassed.
It extends the Object class and implements the Serializable, Comparable, and CharSequence
interfaces.
Java implements strings as objects of type String. A string is a sequence of characters. Unlike
most of the other languages, Java treats a string as a single value rather than as an array of
characters.
The String objects are immutable, i.e., once an object of the String class is created, the string it
contains cannot be changed. In other words, once a String object is created, the characters that
comprise the string cannot be changed. Whenever any operation is performed on a String object,
a new String object will be created while the original contents of the object will remain
unchanged. However, at any time, a variable declared as a String reference can be changed to
point to some other String object.
The String class defines several constructors. The most common constructor of the String class is
the one given below:
This constructor constructs a new String object initialized with the same sequence of the
characters passed as the argument. In other words, the newly created String object is the copy of
the string passed as an argument to the constructor.
public String()
This constructor creates an empty String object. However, the use of this constructor is
unnecessary because String objects are immutable.
This constructor creates a new String object initialized with the same sequence of characters
currently contained in the array that is passed as the argument to it.
This constructor creates a new String object initialized with the same sequence of characters
currently contained in the subarray. This subarray is derived from the character array and the two
integer values that are passed as arguments to the constructor. The int variable startindex
represents the index value of the starting character of the subarray, and the int variable len
represents the number of characters to be used to form the new String object.
This constructor creates a new String object that contains the same sequence of characters
currently contained in the string buffer argument.
The array of bytes that is passed as an argument to the constructor contains the ASCII character
set. Therefore, this array of bytes is first decoded using the default charset of the platform. Then
the constructor creates a new String object initialized with same sequence of characters obtained
after decoding the array.
This constructor creates the String object after decoding the array of bytes and by using the
subarray of bytes.
The String class defines the length() method that determines the length of a string. The length of
a string is the number of characters contained in the string. The signature of the length() method
is given below:
The + operator is used to concatenate two strings, producing a new String object as the result.
For example,
System.out.println(s);
This code will display the string "Our daily sale is 500 dollars".
The + operator may also be used to concatenate a string with other data types. For example,
System.out.println(s);
This code will display the string "Our daily sale is 500 dollars". In this case, the variable sale is
declared as int rather than String, but the output produced is the same. This is because the int
value contained in the variable sale is automatically converted to String type, and then the +
operator concatenates the two strings.
String Comparison
The String class defines various methods that are used to compare strings or substrings within
strings. Each of them is discussed in the following sections:
equals()
The equals() method is used to check whether the Object that is passed as the argument to the
method is equal to the String object that invokes the method. It returns true if and only if the
argument is a String object that represents the same sequence of characters as represented by the
invoking object. The signature of the equals() method is as follows:
equalsIgnoreCase()
Modifying a String
The String objects are immutable. Therefore, it is not possible to change the original contents of
a string. However, the following String methods can be used to create a new copy of the string
with the required modification:
substring()
The substring() method creates a new string that is the substring of the string that invokes the
method. The method has two forms:
where, startindex specifies the index at which the substring will begin and endindex specifies the
index at which the substring will end. In the first form where the endindex is not present, the
substring begins at startindex and runs till the end of the invoking string.
Concat()
The concat() method creates a new string after concatenating the argument string to the end of
the invoking string. The signature of the method is given below:
replace()
The replace() method creates a new string after replacing all the occurrences of a particular
character in the string with another character. The string that invokes this method remains
unchanged. The general form of the method is given below:
trim()
The trim() method creates a new copy of the string after removing any leading and trailing
whitespace. The signature of the method is given below:
toUpperCase()
The toUpperCase() method creates a new copy of a string after converting all the lowercase
letters in the invoking string to uppercase. The signature of the method is given below:
toLowerCase()
The toLowerCase() method creates a new copy of a string after converting all the uppercase
letters in the invoking string to lowercase. The signature of the method is given below:
Searching Strings
The String class defines two methods that facilitate in searching a particular character or
sequence of characters in a string. They are as follows:
IndexOf()
The indexOf() method searches for the first occurrence of a character or a substring in the
invoking string. If a match is found, then the method returns the index at which the character or
the substring first appears. Otherwise, it returns -1. The indexOf() method has the following
signatures:
lastIndexOf()
Object-oriented programming allows classes to inherit commonly used state and behavior from
other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike,
and TandemBike. In the Java programming language, each class is allowed to have one direct
superclass, and each superclass has the potential for an unlimited number of subclasses:
The syntax for creating a subclass is simple. At the beginning of your class declaration, use the
extends keyword, followed by the name of the class to inherit from:
}
This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to
focus exclusively on the features that make it unique. This makes code for your subclasses easy
to read. However, you must take care to properly document the state and behavior that each
superclass defines, since that code will not appear in the source file of each subclass.
Packages
Packages are used in Java in-order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier etc.
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. It is a good
practice to group related classes implemented by you so that a programmers can easily determine
that the classes, interfaces, enumerations, annotations are related.
Since the package creates a new namespace there won't be any name conflicts with names in
other packages. Using packages, it is easier to provide access control and it is also easier to
locate the related classed.
Take, for example, the Java-supplied package "java.awt". The first part of that package name
"java" represents the organization that developed the package (Sun's Java group). The second
part of the package name "awt" stands for the contents of the package, in this case the Abstract
Window Toolkit. The "java.awt" package resides in a directory structure which reflects the
package name:
<path>/classes/java/awt/*.class
All classes contained in the java.awt package reside in the above directory. For this tutorial, we
will be working with three packages. The organization name "v2k" in the Java Package names
stands for Hubble Space Telescope Vision 2000 GUI group. The three Java Package names are
given below:
Directory Package
========================= =======
/GUI/java/classes/v2k/awt v2k.awt // Abstract Window Toolkit
/GUI/java/classes/v2k/ddo v2k.ddo // Realtime Data Driven Objects
/GUI/java/classes/v2k/p3d v2k.p3d // Three Dimensional
All classes for the Package v2k.awt reside in the above directories. The Java source for these classes
reside in the following directories:
Source Directory
=========================
/GUI/java/src/v2k/awt // Abstract Window Toolkit
/GUI/java/src/v2k/ddo // Realtime Data Driven Objects
/GUI/java/src/v2k/p3d // Three Dimensional
API packages
An application programming interface (API) is a library of functions that Java provides for
programmers for common tasks like file transfer, networking, and data structures.
ava API is not but a set of classes and interfaces that comes with the JDK. Java API is actually a
huge collection of library routines that performs basic programming tasks such as looping,
displaying GUI form etc.
In the Java API classes and interfaces are packaged in packages. All these classes are written in
Java programming language and runs on the JVM. Java classes are platform independent but
JVM is not platform independent. You will find different downloads for each OS.
Java Language
JVM or Java Virtual Machine and
The Java API (Java programming interface)
The Java language defines easy to learn syntax and semantics for Java programming language.
Every programmer must understand these syntax and semantics to write program in Java
language.
Abstract Window
AWT java.awt First released with version 1.0.
Toolkit
Accessibility javax.accessibility
java.awt.datatransfer
Drag n Drop
java.awt.dnd
javax.imageio
Image I/O
javax.imageio.*
javax.sound.midi
javax.sound.midi.spi
Sound
javax.sound.sampled
javax.sound.sampled.spi
javax.crypto
Java Cryptography Included as part of J2SE 1.4 and later. Available as an
JCE javax.crypto.interfaces
Extension optional package to versions 1.2 and 1.3.
javax.crypto.spec
Java
Authentication and Included in J2SE 1.4 and later, previously released as an
JAAS javax.security.auth
Authorization optional package with version 1.3.
Service
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.
Compilation : Randjithkumar, B.Tech
Page 44
JAVA IN EASY WAYS
The package statement should be the first line in the source file. There can be only one package
statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation types
will be put into an unnamed package.
Example:
Let us look at an example that creates a package called animals. It is common practice to use
lowercased names of packages to avoid any conflicts with the names of classes, interfaces.
interface Animal {
public void eat();
public void travel();
}
package animals;
To add the class MyClass to the Java Package v2k.awt, add the following statement to the
MyClass.java source file. (It must be the first non-comment statement of the file):
MyClass.java:
package v2k.awt;
Move the Java source file MyClass.java to the source directory for Package v2k.awt:
UNIX example:
% mv MyClass.java /GUI/java/src/v2k/awt/.
You are ready to compile the new class and make it part of the v2k.awt Java Package. If the
CLASSPATH environment variable is set (the path to search for classes being imported by MyClass.java),
do the following :
The -d option tells the compiler to place the MyClass.class file in the directory:
/GUI/java/classes/v2k/awt.
The -d option tells the compiler to place the MyClass.class file in the
directory: /GUI/java/classes/v2k/awt.
The -classpath option tells the compiler to search for classes being imported by MyClass.java in
the path: .:/GUI/java/classes/.
The class "MyClass" is now part of the Java Package v2k.awt. You can now import this class
using the statement import v2k.awt.MyClass.
interfaces
The interface definition states the names of the methods and their return types and argument
signatures
there is no executable body for any method - that is left to each class that implements the
interface
Once a class implements an interface, the Java compiler knows that an instance of the class will
contain the specified set of methods
therefore, it will allow you to call those methods for an object referenced by a variable
whose type is the interface
Implementing an interface enables a class to be "plugged in" in any situation that requires a
specific behavior (manifested through the set of methods)
An analogy: a serial interface on a computer defines a set of pin/wire assignments and the control
signals that will be used
the actual devices that can be used may do entirely different tasks: mouse, modem, etc.
but they are all controlled through the same digital instruction mechanism; the individual
wires are specified to carry specific signals
Using an interface rather than inheritance to specify a certain set of methods allows a class to
inherit from some other class
in other words, if a class needs two different sets of methods, so it can behave like two
different types of things, it could inherit one set from class A, and use an interface B to
specify the other
you could then reference one of these objects with either an A reference or a B reference
Interfaces can also specify constants that are public, static, and final
define it like a Java class, in its own file that matches the interface name
use the keyword interface instead of class
declare methods using the same approach as abstract methods
o note the semicolon after each method declaration - and that no executable code is
supplied(and no curly braces)
o the elements will automatically be public and abstract, and cannot have any other
state; it is OK to specify those terms, but not necessary (usually public is specified
and abstract is not - that makes it easy to copy the list of methods, paste them into
a class, and modify them )
The access level for the entire interface is usually public
o it may be omitted, in which case the interface is only available to other classes in
the same package (i.e., in the same directory)
o note, for the sake of completeness, there are situations where the interface
definition could be protected or private; these involve what are called inner
classes
Syntax
[modifiers] interface InterfaceName {
// declaring methods
// defining constants
Example:
This interface requires only one method. Any class implementing Printable must contain a public
void printall() method in order to compile
Because the above interface is defined as public, its definition must be in its own file, even
though that file will be tiny
An interface definition may also define properties that are automatically public static final - these
are used as constants
multiple inheritances
It is the ability for a class to be derived from more then one class
C++ allows multiple inheritance easily, depending on how the programmer sets up the base
classes, etc... Consider the following example in C++:
01 #include <iostream>
02 #include <string>
04
05 //base class
06 class Animal {
08 int age;
09 string name;
10 public:
11 Animal() {};
14 };
15
18 public:
20 Bird() {};
21 };
22
25 public:
27 Horse() {};
28 };
29
32 public:
34 };
35
36 int main()
37 {
39 cout << peggi->getName() << "'s age is " << peggi->getAge() << endl;
40 peggi->birdNoise();
41 peggi->horseNoise();
42 delete peggi;
43 return 0;
44 }
Exception handling
Exception handling in Java is based on C++ but is designed to be more in line with OOP. It
includes a collection of predefined exceptions that are implicitly raised by the JVM. All java
exceptions are objects of classes that are descendents of Throwable class. There are two
predefined subclasses of Throwable: Error and Exception.
Error and its descendents are related to errors thrown by JVM. Examples include out of heap
memory. Such an exception is never thrown by the user programs and should not be handled by
the user.
User programs can define their own exception classes. Convention in Java is that such classes are
subclasses of Exception. There are two predefined descendents of Exception: IOException and
RuntimeException. IOException deals with errors in I/O operation.
In the case of RuntimeException there are some predefined exceptions which are, in many cases,
thrown by JVM for errors such as out of bounds, and Null pointer.
Exceptions of class Error and RuntimeException are called unchecked exceptions. They are
never a concern of the compiler. A program can catch unchecked exceptions but it is not
required. All other are checked exceptions. Compiler ensures that all the checked exceptions a
method can throw are either listed in its throws clause or are handled in the method.
Exception Handlers
Exception handler in Java is similar to C++ except that the parameter of every catch must be
present and its class must be descendent of Thrwoable. The syntax of try is exactly same as C++
except that there is finally clause as well. For example:
throw myExceptionObject;
Binding of exception is also similar to C++. If an exception is thrown in the compound statement
of try construct, it is bound to the first handler (catch function) immediately following the try
clause whose parameter is the same class as the thrown object or an ancestor of it. Exceptions
can be handled and then re-thrown by including a throw statement without an operand at the end
of the handler. To ensure that exceptions that can be thrown in a try clause are always handled in
a method, a special handler can be written that matches all exceptions. For example:
The exception handler parameter in C++ has a limited purpose. During program execution, the
Java runtime system stores the class name of every object. getClass can be used to get an object
that stores the class name. It has a getName method. The name of the class of the actual
parameter of the throw statement can be retrieved in the handler as shown below.
anyException.getClass().getName();
In the case of a user defined exception, the thrown object could include any number of data fields
that might be useful in the handler.
throws Clause
throws clause is overloaded in C++ and conveys two different meanings: one as specification
and the other as command. Java is similar in syntax but different in semantics. The appearance of
an exception class name in the throws clause of Java method specifies that the exception class or
any of its descendents can be thrown by the method.
A C++ program unit that does not include a throw clause can throw any exceptions. A Java
method that does not include a throws cannot throw any checked exception it does not handle. A
method cannot declare more exceptions in its throws clause than the methods it overrides, though
it may declare fewer. A method that does not throw a particular exception, but calls another
method that could throw the exception, must list the exception in its throws clause.
predefined exception
Some examples of the predefined exception classes are listed below. A full list is available in the
Java documentation.
ClassNotFoundException
IllegalAccessException
IOException
EOFException
FileNotFoundException
MalformedURLException
ProtocolException
SocketException
UnknownHostException
UnknownServiceException
These exception classes include data, such as an error message which can be set by the
programmer, and several useful methods such as:
printStackTrace(), which prints a trace of where the error occurred, and the methods through
which the program arrived at that point
getMessage(), which retrieves the error message contained in the exception object.
Many of the methods of the Java library classes throw exceptions if they encounter unexpected
situations. The compiler won’t allow you to ignore these exceptions – you must do one of two
things. You can either propagate the exception – in other words, pass it on for another method
to deal with, or ‘catch’ it, and deal with it yourself. We’ll look at how this can be coded.
Propagating an exception: if you know that your method can throw an exception that it will not
handle, the compiler must be informed by adding the clause throws exceptiontype to the end of
the method header, where exceptiontype is the class of the exception object which is thrown.
For example, a method that processes a file is always prone to exceptions. The method header
may be coded:
Many of the methods in library classes do this, especially those that deal with file handling.
Any method that calls the GetCustInfo method must either catch the error or propagate it to the
next level up. If it is to be propagated, then the calling method must also specify throws
IOException in its own header.
Catching an Exception: This is done by enclosing the statements that may cause an error in a
try … catch block, as follows:
try
{
The exception class in the catch block must be either the one thrown by the statements in the try
block, or a superclass of it.
The statements in the catch block can use the methods associated with the object caught in order
to retrieve information from it, for example:
catch(IOException badFile)
{
System.out.println(badFile.getMessage());
badFile.printStackTrace;
etc
}
When an error is detected in the try block, control is passed directly to the catch block, and all
later statements in the try block are ignored.
The following example shows the Calculator program from a previous example modified to
include exception handling, so that if an invalid number is entered on the command line, a user-
friendly error message is displayed.
// ********************************************************
// * This program will carry out a calculation
// * entered on the command line. The calculation
// * should be entered as a number, followed by a
// * space, followed by an operand, followed by a
// * space and a number. Valid operands are +,-,x
// * and /.
// *********************************************************
// *********************************************************
// Decide on the correct calculation depending on
// the operand entered
// **********************************************************
switch(Op)
{
case '+':
Ans=Num1+Num2;
break;
case '-':
Ans=Num1-Num2;
break;
case 'x':
Ans=Num1*Num2;
break;
case '/':
Ans=Num1/Num2;
break;
default:
System.out.println ("Can't do that - I'm only a cheap calculator");
break;
}
System.out.println("Answer is " + Ans);
}
Though Java provides an extensive set of in-built exceptions, there are cases in which we may
need to define our own exceptions in order to handle the various application specific errors that
we might encounter.
While defining an user defined exception, we need to take care of the following aspects:
The user defined exception class should extend from Exception class.
The toString() method should be overridden in the user defined exception class in order
to display meaningful information about the exception.
Let us see a simple example to learn how to define and make use of user defined exceptions.
NegativeAgeException.java
CustomExceptionTest.java
In the CustomExceptionTest class, the age is expected to be a positive number. It would throw
the user defined exception NegativeAgeException if the age is assigned a negative number.
At runtime, we get the following exception since the age is a negative number.
Java - Multithreading
I need to define another term related to threads: process: A process consists of the memory space
allocated by the operating system that can contain one or more threads. A thread cannot exist on
its own; it must be a part of a process. A process remains running until all of the non-daemon
threads are done executing.
Multithreading enables you to write very efficient programs that make maximum use of the
CPU, because idle time can be kept to a minimum.
A thread goes through various stages in its life cycle. For example, a thread is born, started, runs,
and then dies. Following diagram shows complete life cycle of a thread.
New: A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
Runnable: After a newly born thread is started, the thread becomes runnable. A thread in
this state is considered to be executing its task.
Waiting: Sometimes a thread transitions to the waiting state while the thread waits for
another thread to perform a task.A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue executing.
Timed waiting: A runnable thread can enter the timed waiting state for a specified
interval of time. 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.
Terminated: A runnable thread enters the terminated state when it completes its task or
otherwise terminates.
Thread Priorities:
Every Java thread has a priority that helps the operating system determine the order in which
threads are scheduled.
Threads with higher priority are more important to a program and should be allocated processor
time before lower-priority threads. However, thread priorities cannot guarantee the order in
which threads execute and very much platform dependentant.
Creating a Thread:
The easiest way to create a thread is to create a class that implements the Runnable interface.
To implement Runnable, a class need only implement a single method called run( ), which is
declared like this:
You will define the code that constitutes the new thread inside run() method. It is important to
understand that run() can call other methods, use other classes, and declare variables, just like the
main thread can.
After you create a class that implements Runnable, you will instantiate an object of type Thread
from within that class. Thread defines several constructors. The one that we will use is shown
here:
Here threadOb is an instance of a class that implements the Runnable interface and the name of
the new thread is specified by threadName.
After the new thread is created, it will not start running until you call its start( ) method, which
is declared within Thread. The start( ) method is shown here:
void start( );
Example:
class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
The second way to create a thread is to create a new class that extends Thread, and then to
create an instance of that class.
The extending class must override the run( ) method, which is the entry point for the new thread.
It must also call start( ) to begin execution of the new thread.
Example:
class ExtendThread {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
Thread Methods:
Java - Applets
An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java
application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java application,
including the following:
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.
A JVM is required to view an applet. The JVM can be either a plug-in of the Web
browser or a separate runtime environment.
The JVM on the user's machine creates an instance of the applet class and invokes
various methods during the applet's lifetime.
Applets have strict security rules that are enforced by the Web browser. The security of
an applet is often referred to as sandbox security, comparing the applet to a child playing
in a sandbox with various rules that must be followed.
Other classes that the applet needs can be downloaded in a single Java Archive (JAR)
file.
Four methods in the Applet class give you the framework on which you build any serious applet:
init: This method is intended for whatever initialization is needed for your applet. It is
called after the param tags inside the applet tag have been processed.
start: This method is automatically called after the browser calls the init method. It is
also called whenever the user returns to the page containing the applet after having gone
off to other pages.
stop: This method is automatically called when the user moves off the page on which the
applet sits. It can, therefore, be called repeatedly in the same applet.
destroy: This method is only called when the browser shuts down normally. 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.
paint: Invoked immediately after the start() method, and also any time the applet needs
to repaint itself in the browser. The paint() method is actually inherited from the java.awt.
import java.applet.*;
import java.awt.*;
These import statements bring the classes into the scope of our applet class:
java.applet.Applet.
java.awt.Graphics.
Without those import statements, the Java compiler would not recognize the classes Applet and
Graphics, which the applet class refers to.
The following example demonstrates how to make an applet respond to setup parameters
specified in the document. This applet displays a checkerboard pattern of black and a second
color.
The second color and the size of each square may be specified as parameters to the applet within
the document.
CheckerApplet gets its parameters in the init() method. It may also get its parameters in the
paint() method. However, getting the values and saving the settings once at the start of the
applet, instead of at every refresh, is convenient and efficient.
The applet viewer or browser calls the init() method of each applet it runs. The viewer calls init()
once, immediately after loading the applet. (Applet.init() is implemented to do nothing.)
Override the default implementation to insert custom initialization code.
The Applet.getParameter() method fetches a parameter given the parameter's name (the value of
a parameter is always a string). If the value is numeric or other non-character data, the string
must be parsed.
import java.applet.*;
import java.awt.*;
public class CheckerApplet extends Applet
{
int squareSize = 50;// initialized to default size
public void init () {}
private void parseSquareSize (String param) {}
private Color parseColor (String param) {}
public void paint (Graphics g) {}
}
The applet calls parseSquareSize() to parse the squareSize parameter. parseSquareSize() calls the
library method Integer.parseInt(), which parses a string and returns an integer. Integer.parseInt()
throws an exception whenever its argument is invalid.
Therefore, parseSquareSize() catches exceptions, rather than allowing the applet to fail on bad
input.
The applet calls parseColor() to parse the color parameter into a Color value. parseColor() does a
series of string comparisons to match the parameter value to the name of a predefined color. You
need to implement these methods to make this applet works.
The following is an example of an HTML file with a CheckerApplet embedded in it. The HTML
file specifies both parameters to the applet by means of the <param> tag.
<html>
<title>Checkerboard Applet</title>
<hr>
<applet code="CheckerApplet.class" width="480" height="320">
<param name="color" value="blue">
<param name="squaresize" value="30">
</applet>
<hr>
</html>
Java - Streams
A stream can be defined as a sequence of data. The InputStream is used to read data from a
source and the OutputStream is used for writing data to a destination
A stream can be defined as a sequence of data. The InputStream is used to read data from a
source and the OutputStream is used for writing data to a destination.
The two important streams are FileInputStream and FileOutputStream which would be discussed
in this tutorial:
FileInputStream:
This stream is used for reading data from the files. Objects can be created using the keyword new
and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the
file.:
Following constructor takes a file object to create an input stream object to read the file. First we
create a file object using File() method as follows:
Once you have InputStream object in hand then there is a list of helper methods which can be
used to read to stream or to do other operations on the stream.
Gives the number of bytes that can be read from this file input stream. Returns an int.
There are other important input streams available, for more detail you can refer to the following
links:
ByteArrayInputStream
DataInputStream
FileOutputStream:
FileOutputStream is used to create a file and write data into it.The stream would create a file, if it
doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write the
file.:
Following constructor takes a file object to create an output stream object to write the file. First
we create a file object using File() method as follows:
Once you have OutputStream object in hand then there is a list of helper methods which can be
used to write to stream or to do other operations on the stream.
There are other important output streams available, for more detail you can refer to the following
links:
ByteArrayOutputStream
DataOutputStream
Example: