Anda di halaman 1dari 72

JAVA IN EASY WAYS

Java in Easy
Ways

Compilation : Randjithkumar, B.Tech


Page 1
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 Virtual Machine

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

Compilation : Randjithkumar, B.Tech


Page 2
JAVA IN EASY WAYS

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.

Java has powerful features. The following are some of them:-


Java is object oriented

Since Java is an object oriented programming language it has following advantages:

 Reusability of Code

 Emphasis on data rather than procedure

 Data is hidden and cannot be accessed by external functions

 Objects can communicate with each other through functions

 New data and functions can be easily added

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

Compilation : Randjithkumar, B.Tech


Page 3
JAVA IN EASY WAYS

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 vs. C++

Java C++
Method bodies must be defined inside the class Method bodies must be defined inside the class

Compilation : Randjithkumar, B.Tech


Page 4
JAVA IN EASY WAYS

to which they belong. to which they belong.


No forward referencing required. Explicit forward referencing required.
No preprocessor. Heavy reliance on preprocessor.
No comma operator. Comma operator.
No variable-length parameter lists. Variable-length parameter lists.
No optional method parameters. Optional function parameters.
No const reference parameters. const reference parameters.
No goto Goto
Labels on break and continue. No labels on break and continue.
Command-line arguments do not include the Command-line arguments do not include the
program name. program name.
Main method cannot return a value. Main function can return a value.
No global variables. Global variables.
Character escape sequences must appear in a
Character escape sequences can appear in a
string
program.
or character literal.
Cannot mask identifiers through scope. Can mask identifiers through scope.

data types in java

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 :

Compilation : Randjithkumar, B.Tech


Page 5
JAVA IN EASY WAYS

 Primitive Data Types 

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:

 int num =50;

 long
 The long data type is a 64-bit signed two's complement integer. It ranges from

Compilation : Randjithkumar, B.Tech


Page 6
JAVA IN EASY WAYS

-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Use this data type with larger range


of values. The syntax of declaring a long type variable is shown as:

 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:

 char caps = 'c';   

 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:

 boolean result = true;

 Integer Data Types


An integer number can hold a whole number. Java provides four different primitive integer data
types that can be defined as  byte, short, int, and long  that can store both positive and negative
values. The  ranges of these data types can be described using the following table:

Compilation : Randjithkumar, B.Tech


Page 7
JAVA IN EASY WAYS

Data Type Size (in bits) Minimum Range Maximum Range

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

Examples of floating-point literals are:

 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

Compilation : Randjithkumar, B.Tech


Page 8
JAVA IN EASY WAYS

Reference Data Types

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();

Compilation : Randjithkumar, B.Tech


Page 9
JAVA IN EASY WAYS

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.

The Simple Assignment Operator

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;

This operator can also be used on objects to assign object references

The Arithmetic Operators

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

The following program, ArithmeticDemo, tests the arithmetic operators.

class ArithmeticDemo {

public static void main (String[] args){

Compilation : Randjithkumar, B.Tech


Page 10
JAVA IN EASY WAYS

int result = 1 + 2; // result is now 3


System.out.println(result);

result = result - 1; // result is now 2


System.out.println(result);

result = result * 2; // result is now 4


System.out.println(result);

result = result / 2; // result is now 2


System.out.println(result);

result = result + 8; // result is now 10


result = result % 7; // result is now 3
System.out.println(result);

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

Bitwise and Bit Shift Operators


The Java programming language also provides operators that perform bitwise and bit shift
operations on integral types. The operators discussed in this section are less commonly used.
Therefore, their coverage is brief; the intent is to simply make you aware that these operators
exist.

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;

Compilation : Randjithkumar, B.Tech


Page 11
JAVA IN EASY WAYS

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 bitwise & operator performs a bitwise AND operation.

The bitwise ^ operator performs a bitwise exclusive OR operation.

The bitwise | operator performs a bitwise inclusive OR operation.

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 {

public static void main(String[] args){


Compilation : Randjithkumar, B.Tech
Page 12
JAVA IN EASY WAYS

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 Conditional Operators

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

The following program, ConditionalDemo1, tests these operators:

class ConditionalDemo1 {

public static void main(String[] args){


int value1 = 1;
int value2 = 2;
if((value1 == 1) && (value2 == 2)) System.out.println("value1 is 1 AND value2 is 2");
if((value1 == 1) || (value2 == 1)) System.out.println("value1 is 1 OR value2 is 1");

}
}

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

Compilation : Randjithkumar, B.Tech


Page 13
JAVA IN EASY WAYS

Decision making in java

There are two types of decision making statements in Java. They are:

 if statements

 switch statements

The if Statement:

An if statement consists of a Boolean expression followed by one or more statements.

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. If not the first set of code after the end of the if statement(after the closing curly brace)
will be executed.

Example:

public class Test {


public static void main(String args[]){
int x = 10;

if( x < 20 ){
System.out.print("This is if statement");
}
}
}

This would produce following result:

This is if statement

Compilation : Randjithkumar, B.Tech


Page 14
JAVA IN EASY WAYS

The if...else Statement:

An if statement can be followed by an optional else statement, which executes when the Boolean
expression is false.

Syntax:

The syntax of a if...else is:

if(Boolean_expression){
//Executes when the Boolean expression is true
}else{
//Executes when the Boolean expression is false
}

Example:

public class Test {


public static void main(String args[]){
int x = 30;

if( x < 20 ){
System.out.print("This is if statement");
}else{
System.out.print("This is else statement");
}
}
}

This would produce following result:

This is else statement

The if...else if...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:

The syntax of a if...else is:

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:

public class Test {


public static void main(String args[]){
int x = 30;

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");
}
}
}

This would produce following result:

Value of X is 30

Nested if...else Statement:

It is always legal to nest if-else statements, which means you can use one if or else if statement
inside another if or else if statement.

Compilation : Randjithkumar, B.Tech


Page 16
JAVA IN EASY WAYS

Syntax:

The syntax for a nested if...else is as follows:

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:

public class Test {


public static void main(String args[]){
int x = 30;
int y = 10;

if( x == 30 ){
if( y == 10 ){
System.out.print("X = 30 and Y = 10");
}
}
}

This would produce following result:

X = 30 and Y = 10

The switch Statement:

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:

The syntax of enhanced for loop is:

switch(expression){
case value :

Compilation : Randjithkumar, B.Tech


Page 17
JAVA IN EASY WAYS

//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
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.

 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:

public class Test {


public static void main(String args[]){
char grade = args[0].charAt(0);

switch(grade)
{
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :

Compilation : Randjithkumar, B.Tech


Page 18
JAVA IN EASY WAYS

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 Java programming language supports the following branching statements:

 The break statement


 The continue statement
 The return statement

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;

The break Statement


The break statement has two forms — unlabeled and labeled. The unlabeled form of the break
statement was used with switch earlier. As noted there, an unlabeled break terminates the
enclosing switch statement, and flow of control transfers to the statement immediately following
the switch. You can also use the unlabeled form of the break statement to terminate a for, while,
or do-while loop. The following sample program, BreakDemo, contains a for loop that searches
for a particular value within an array.

public class BreakDemo {


public static void main(String[] args) {

int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076,


2000, 8, 622, 127 };
int searchfor = 12;

int i = 0;
boolean foundIt = false;

for ( ; i < arrayOfInts.length; i++) {

Compilation : Randjithkumar, B.Tech


Page 19
JAVA IN EASY WAYS

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.

This is the output 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.

public class BreakWithLabelDemo {


public static void main(String[] args) {

int[][] arrayOfInts = { { 32, 87, 3, 589 },


{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;

int i = 0;
int j = 0;
boolean foundIt = false;

search:
for ( ; i < arrayOfInts.length; i++) {

Compilation : Randjithkumar, B.Tech


Page 20
JAVA IN EASY WAYS

for (j = 0; j < arrayOfInts[i].length; j++) {


if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}

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.

The continue Statement


The continue statement is used to skip the current iteration of a for, while , or do-while loop. The
unlabeled form skips to the end of the innermost loop's body and evaluates the boolean
expression that controls the loop, basically skipping the remainder of this iteration of the loop.
The following program, ContinueDemo , steps through a string buffer, checking each letter. If
the current character is not a p, the continue statement skips the rest of the loop and proceeds to
the next character. If it is a p, the program increments a counter and converts the p to an
uppercase letter.

public class ContinueDemo {


public static void main(String[] args) {

StringBuffer searchMe = new StringBuffer(


"peter piper picked a peck of pickled peppers");
int max = searchMe.length();
int numPs = 0;

for (int i = 0; i < max; i++) {


//interested only in p's

Compilation : Randjithkumar, B.Tech


Page 21
JAVA IN EASY WAYS

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.

Found 9 p's in the string.


Peter PiPer Picked a Peck of Pickled PePPers

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.

public class ContinueWithLabelDemo {


public static void main(String[] args) {

String searchMe = "Look for a substring in me";


String substring = "sub";
boolean foundIt = false;

int max = searchMe.length() - substring.length();

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;

Compilation : Randjithkumar, B.Tech


Page 22
JAVA IN EASY WAYS

}
System.out.println(foundIt ? "Found it" :"Didn't find it");
}
}
Here is the output from this program.

Found it

The return Statement


The last of the branching statements is the return statement. You use return to exit from the
current method; the flow of control returns to the statement that follows the original method call.
The return statement has two forms: (1) one that returns a value and (2) one that doesn't. To
return a value, simply put the value (or an expression that calculates the value) after the return
keyword.

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.

The while Loop:

A while loop is a control structure that allows you to repeat a task a certain number of times.

Syntax:

Compilation : Randjithkumar, B.Tech


Page 23
JAVA IN EASY WAYS

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

public class Test {


public static void main(String args[]){
int x= 10;

while( x < 20 ){
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}

This would produce following result:

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

Compilation : Randjithkumar, B.Tech


Page 24
JAVA IN EASY WAYS

The do...while Loop:

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:

The syntax of a do...while loop is:

Do
{
//Statements
}while(Boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the statements in the loop
execute once before the Boolean is tested.

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:

public class Test {


public static void main(String args[]){
int x= 10;

do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}

This would produce following result:

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

Compilation : Randjithkumar, B.Tech


Page 25
JAVA IN EASY WAYS

value of x : 17
value of x : 18
value of x : 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.

A for loop is useful when you know how many times a task is to be repeated.

Syntax:

The syntax of a for loop is:

for(initialization; Boolean_expression; update)


{
//Statements
}

Here is the flow of control in a for loop:

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:

public class Test {


public static void main(String args[]){

Compilation : Randjithkumar, B.Tech


Page 26
JAVA IN EASY WAYS

for(int x = 10; x < 20; x = x+1){


System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}

This would produce following result:

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

Classes and Objects

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.

Compilation : Randjithkumar, B.Tech


Page 27
JAVA IN EASY WAYS

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:

A class is a blue print from which individual objects are created.

A sample of a class is given below:

public class Dog{


String breed;
int age;
String color;

void barking(){
}

void hungry(){
}

void sleeping(){
}
}
A class can contain any of the following variable types.

 Local variables . variables defined inside methods, constructors or blocks are


called local variables. The variable will be declared and initialized within the
method and the variable will be destroyed when the method has completed.

Compilation : Randjithkumar, B.Tech


Page 28
JAVA IN EASY WAYS

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

Save the following code in EmployeeTest.java file

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");

// Invoking methods for each object created


empOne.empAge(26);
empOne.empDesignation("Senior Software Engineer");
empOne.empSalary(1000);
empOne.printEmployee();

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.

Compilation : Randjithkumar, B.Tech


Page 29
JAVA IN EASY WAYS

An array of ten elements

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.

For e.g. employee[5];

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.

Advantages of using Arrays

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.

The various types of arrays in java are:

 One-dimensional arrays
 two-dimensional arrays

One-dimensional Arrays

One-dimensional array is a list of variables of the same data type.

Syntax to declare a one-dimensional array

Compilation : Randjithkumar, B.Tech


Page 30
JAVA IN EASY WAYS

type array_name []; //type is the datatype of the array.

For e.g.

String designations []; // designations is name of the array.

Allocating Memory to Arrays

The new operator is used to allocate memory to an array.

Syntax to allocate memory

array_name = new type[size];

For e.g.

designations = new String[10]; //size of the array is 10.

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.

Syntax to declare a two dimensional array

type array_name = new type[rows][cols];

For e.g.

int multidim[] = new int[3][];

In a two-dimensional array,

1. To need to allocate memory for only the first dimension.


2. To can allocate the remaining dimensions separately.
3. When you allocate memory to the second dimension, you can also allocate different
number to each dimension.

For e.g.

int multidim[] = new int[3][];

multidim[0] = new int[1];

multidim[1] = new int[4];

Compilation : Randjithkumar, B.Tech


Page 31
JAVA IN EASY WAYS

Accessing Arrays

To access various elements of an array to assign, retrieve, and manipulate the values stored in the
array.

Assigning values to the Elements of an Array

To access a specific 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 = new String[2];

designations[0] = “General Manager”;

designations[1]=”Managing Director”;

You can declare and allocate memory to a user-defined array in a single statement.

Syntax

type arr [] = new type[size];

For e.g.

int employees[] = new int[10];

You can also declare and initialize arrays in the same statement.

For e.g.

String designations[] = {“General Manager”, ”Managing Director”};

Accessing values from various Elements of an Array

To access values from elements in the array by referring to the element by its index number.

For e.g.

String designations[];

Compilation : Randjithkumar, B.Tech


Page 32
JAVA IN EASY WAYS

designations = new String[3];

designations[1] = “General Manager”;

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.

Simple Java Application using Arrays

import java.io.*;

class student

int regno,total;

int mark[];

String name;

public student(int r,String n,int m[])

regno=r;

name=n;

mark=new int[3]; //new operator is used to allocate memory to an array.

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

mark[i]=m[i];

if(mark[i]>50)

total+=mark[i];

Compilation : Randjithkumar, B.Tech


Page 33
JAVA IN EASY WAYS

else

total=0;

break;

public void displaystudent()

System.out.println("NAME:"+name);

System.out.println("REGNO:"+regno);

System.out.println("TOTAL:"+total);

class secondsample

public static void main(String args[])

int mk1[]={73,85,95}; // declare and initialize arrays in the same statement.

int mk2[]={71,85,95};

student st[]=new student[2];

st[0]=new student(1,"Ganguly",mk1);

st[1]=new student(2,"Sachin",mk2);

Compilation : Randjithkumar, B.Tech


Page 34
JAVA IN EASY WAYS

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

String Handling in Java

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.

Compilation : Randjithkumar, B.Tech


Page 35
JAVA IN EASY WAYS

Constructors defined in the String class

The String class defines several constructors. The most common constructor of the String class is
the one given below:

public String(String value)

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.

Other constructors defined in the String class are as follows:

public String()

This constructor creates an empty String object. However, the use of this constructor is
unnecessary because String objects are immutable.

public String(char[] value)

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.

public String(char[] value, int startindex, int len)

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.

public String(StringBuffer sbf)

This constructor creates a new String object that contains the same sequence of characters
currently contained in the string buffer argument.

public String(byte[] asciichars)

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.

public String(byte[] asciiChars, int startindex, int len)

Compilation : Randjithkumar, B.Tech


Page 36
JAVA IN EASY WAYS

This constructor creates the String object after decoding the array of bytes and by using the
subarray of bytes.

Special String Operations

 Finding the length of string

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:

public int length()

 String Concatenation using the + operator

The + operator is used to concatenate two strings, producing a new String object as the result.
For example,

String sale = "500";

String s = "Our daily sale is" + sale + "dollars";

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,

int sale = 500;

String s = "Our daily sale is" + sale + "dollars";

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()

Compilation : Randjithkumar, B.Tech


Page 37
JAVA IN EASY WAYS

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:

public boolean equals(Object str)

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:

public String substring(int startindex)

public String substring(int startindex, int endindex)

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:

public String concat(String str)

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:

public String replace(char old_char, char new_char)

trim()

Compilation : Randjithkumar, B.Tech


Page 38
JAVA IN EASY WAYS

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:

public String trim(String str)

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:

public String toUpperCase()

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:

public String toLowerCase()

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:

public int indexOf(int ch)

public int indexOf(int ch, int startindex)

public int indexOf(String str)

public int indexOf(String str, int startindex)

lastIndexOf()

Compilation : Randjithkumar, B.Tech


Page 39
JAVA IN EASY WAYS

PACKAGES AND EXCEPTION HANDLING


Inheritance
Different kinds of objects often have a certain amount in common with each other. Mountain
bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current
speed, current pedal cadence, current gear). Yet each also defines additional features that make
them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop
handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.

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:

Compilation : Randjithkumar, B.Tech


Page 40
JAVA IN EASY WAYS

A hierarchy of bicycle classes.

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:

class MountainBike extends Bicycle {

// new fields and methods defining a mountain bike would go here

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

A Package can be defined as a grouping of related types(classes, interfaces, enumerations and


annotations ) providing access protection and name space management.

Some of the existing packages in Java are::

 java.lang - bundles the fundamental classes

 java.io - classes for input , output functions are bundled in this package

Compilation : Randjithkumar, B.Tech


Page 41
JAVA IN EASY WAYS

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.

Java Package Names and Directory Structure


The Java Package name consists of words separated by periods. The first part of the name
represents the organization which created the package. The remaining words of the Java Package
name reflect the contents of the package. The Java Package name also reflects its directory
structure.

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:

&ltpath>/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

Compilation : Randjithkumar, B.Tech


Page 42
JAVA IN EASY WAYS

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.

The Java comprises three components:

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

Type of Java API

There are three types of API available in Java Technology.

 Official Java Core API


The official core API is part of JDK download. The three editions of the Java
programming language are Java SE, Java ME and Java EE.
              
 Optional Java API
The optional Java API can be downloaded separately. The specification of the API is
defined according to the JSR request.
                 
 Unofficial APIs
These API's are developed by third parties and can downloaded from the owner website.

Official Java Core API list

Package(s) that contain


Name Acronym Description and Version History
the API

Abstract Window
AWT java.awt First released with version 1.0.
Toolkit

Compilation : Randjithkumar, B.Tech


Page 43
JAVA IN EASY WAYS

Swing   javax.swing Included in J2SE 1.2 and later.

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 

Java Database java.sql


JDBC  
Connectivity javax.sql 

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

A set of packages that enable secure Internet


javax.net
Java Secure Socket communications. Included as part of J2SE 1.4 and later,
JSSE javax.net.ssl
Extension JSSE 1.0.3 is an optional package to the Java 2 SDK,
java.security.cert 
versions 1.2 and 1.3.

Allows Java code running in the Java virtual machine


(JVM) to call and be called[1] by native applications
Java Native
JNI   (programs specific to a hardware and operating system
Interface
platform) and libraries written in other languages, such as
C, C++ and assembly.

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.

Put an interface in the package animals:

/* File name : Animal.java */


package animals;

interface Animal {
public void eat();
public void travel();
}

Now put an implementation in the same package animals:

package animals;

/* File name : MammalInt.java */


public class MammalInt implements Animal{

public void eat(){


System.out.println("Mammal eats");
}

public void travel(){


System.out.println("Mammal travels");
}

public int noOfLegs(){


return 0;
}

public static void main(String args[]){


MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

adding class to package

Compilation : Randjithkumar, B.Tech


Page 45
JAVA IN EASY WAYS

Adding a Class to an Existing Java Package


To add a Class to an existing Java Package do the following:

 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 :

% javac -d /GUI/java/classes /GUI/java/src/v2k/awt/MyClass.java

The -d option tells the compiler to place the MyClass.class file in the directory:
/GUI/java/classes/v2k/awt.

 If the CLASSPATH environment is not set, do the following :


% javac -d /GUI/java/classes -classpath
.:/GUI/java/classes:/usr/java/classes
/GUI/java/src/v2k/awt/MyClass.java

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

interfaces define a standardized set of commands that a class will obey

The commands are a set of methods that a class implements

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

Compilation : Randjithkumar, B.Tech


Page 46
JAVA IN EASY WAYS

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

Creating an Interface Definition

To create an interface definition:

 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)

Compilation : Randjithkumar, B.Tech


Page 47
JAVA IN EASY WAYS

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

[public abstract] returnType methodName1(arguments);

// defining constants

[public static final]


type propertyName = value;
}

Example:

Code Sample: Java-Interfaces/Demos/Printable.java

public interface Printable {


void printAll();
}
Code Explanation

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>

Compilation : Randjithkumar, B.Tech


Page 48
JAVA IN EASY WAYS

02 #include <string>

03 using namespace std;

04  

05 //base class

06 class Animal {

07 protected: //derived classes get these

08     int age;

09     string name;

10 public:

11     Animal() {};

12     string getName()        {return name;};

13     int getAge()            {return age;}; 

14 };

15  

16 //Bird is a derived class from Animal

17 class Bird : public virtual Animal {

18 public:

19     void birdNoise()        { cout << "Bird Noise!\n";};

20     Bird() {};

21 };

22  

23 //Horse also derives from Animal

24 class Horse : public virtual Animal {

25 public:

26     void horseNoise()       { cout << "Horse Noise!\n";};

Compilation : Randjithkumar, B.Tech


Page 49
JAVA IN EASY WAYS

27     Horse() {};

28 };

29  

30 class Pegasus : public Bird, public Horse {

31     //reserved for future items

32 public:

33     Pegasus(string n, int a) {name = n; age = a;};

34 };

35  

36 int main()

37 {

38     Pegasus* peggi = new Pegasus("Pegasus", 5); //create the pegasus object

39     cout << peggi->getName() << "'s age is " << peggi->getAge() << endl;

40     peggi->birdNoise();

41     peggi->horseNoise();

42     delete peggi;

43     return 0;

44 }

A possible UML diagram based on the following:

Compilation : Randjithkumar, B.Tech


Page 50
JAVA IN EASY WAYS

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.

Compilation : Randjithkumar, B.Tech


Page 51
JAVA IN EASY WAYS

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.

Checked and Unchecked Exceptions

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:

class MyException extends Exception {


public MyException() { }
public MyException(String message) {
super (message);
}
}
This exception can be thrown with
throw new MyException();

(Or) MyException myExceptionObject = new MyException();

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:

catch (Exception anyException) {

Compilation : Randjithkumar, B.Tech


Page 52
JAVA IN EASY WAYS

Other Design Choices

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:

Compilation : Randjithkumar, B.Tech


Page 53
JAVA IN EASY WAYS

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:

public void GetCustInfo(String Custno) throws IOException

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
{

statements that may cause an error ….


}
catch (exceptionclass objectname)
{
statements that deal with the error
}

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:

Compilation : Randjithkumar, B.Tech


Page 54
JAVA IN EASY WAYS

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 /.
// *********************************************************

public class calc


{

public static void main(String[] args)


{

double Num1=0, Num2=0, Ans=0;


char Op;
// *******************************************************
// Number format checking has now been included here
// *******************************************************
try
{
Num1=Integer.parseInt(args[0]); //First argument is a number
}
catch (NumberFormatException ex)
{
System.out.println (“First No. was not entered in the correct format – please try again”);
System.exit(0);

Compilation : Randjithkumar, B.Tech


Page 55
JAVA IN EASY WAYS

Op=args[1].charAt(0); //First character of second


                                     //argument is the operand
try
{

Num2=Integer.parseInt(args[2]); //Third argument is a number


}
catch (NumberFormatException ex)
{
System.out.println (“Second No. was not entered in the correct format – please try again”);
System.exit(0);

// *********************************************************
// 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);
}

Compilation : Randjithkumar, B.Tech


Page 56
JAVA IN EASY WAYS

user defined exceptions

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

public class NegativeAgeException extends Exception {

private int age;

public NegativeAgeException(int age){


this.age = age;
}

public String toString(){


return "Age cannot be negative" + " " +age ;
}
}

CustomExceptionTest.java

public class CustomExceptionTest {

public static void main(String[] args) throws Exception{

int age = getAge();

if (age < 0){


throw new NegativeAgeException(age);
}else{
System.out.println("Age entered is " + age);
}
}

static int getAge(){


return -10;
}
}

Compilation : Randjithkumar, B.Tech


Page 57
JAVA IN EASY WAYS

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.

Exception in thread "main" Age cannot be negative -10


at
tips.basics.exception.CustomExceptionTest.main(CustomExceptionTest.java:10)

Compilation : Randjithkumar, B.Tech


Page 58
JAVA IN EASY WAYS

THREADS AND APPLETS (Qualitative Analysis)

Java - Multithreading

Java provides built-in support for multithreaded programming. A multithreaded program


contains two or more parts that can run concurrently. Each part of such a program is called a
thread, and each thread defines a separate path of execution.

A multithreading is a specialized form of multitasking. Multitasking threads require less


overhead than multitasking processes.

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.

Life Cycle of a Thread:

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.

Compilation : Randjithkumar, B.Tech


Page 59
JAVA IN EASY WAYS

Above mentioned stages are explained here:

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

Compilation : Randjithkumar, B.Tech


Page 60
JAVA IN EASY WAYS

Thread Priorities:

Every Java thread has a priority that helps the operating system determine the order in which
threads are scheduled.

Java priorities are in the range between MIN_PRIORITY (a constant of 1) and


MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).

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:

Java defines two ways in which this can be accomplished:

 You can implement the Runnable interface.

 You can extend the Thread class, itself.

Create Thread by Implementing Runnable:

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:

public void run( )

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:

Thread(Runnable threadOb, String threadName);

Here threadOb is an instance of a class that implements the Runnable interface and the name of
the new thread is specified by threadName.

Compilation : Randjithkumar, B.Tech


Page 61
JAVA IN EASY WAYS

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:

Here is an example that creates a new thread and starts it running:

// Create a new thread.


class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}

// This is the entry point for the second thread.


public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
// Let the thread sleep for a while.
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}

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.");
}
}

Compilation : Randjithkumar, B.Tech


Page 62
JAVA IN EASY WAYS

This would produce following result:

Child thread: Thread[Demo Thread,5,main]


Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.

Create Thread by Extending Thread:

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:

Here is the preceding program rewritten to extend Thread:

// Create a second thread by extending Thread


class NewThread extends Thread {
NewThread() {
// Create a new, second thread
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // Start the thread
}

// This is the entry point for the second thread.


public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
// Let the thread sleep for a while.
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}

Compilation : Randjithkumar, B.Tech


Page 63
JAVA IN EASY WAYS

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.");
}
}

This would produce following result:

Child thread: Thread[Demo Thread,5,main]


Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.

Thread Methods:

Following is the list of important medthods available in the Thread class.

SN Methods with Description

public void start()


1 Starts the thread in a separate path of execution, then invokes the run() method on this Thread
object.

public void run()


2 If this Thread object was instantiated using a separate Runnable target, the run() method is
invoked on that Runnable object.

Compilation : Randjithkumar, B.Tech


Page 64
JAVA IN EASY WAYS

public final void setName(String name)


3 Changes the name of the Thread object. There is also a getName() method for retrieving the
name.

public final void setPriority(int priority)


4
Sets the priority of this Thread object. The possible values are between 1 and 10.

public final void setDaemon(boolean on)


5
A parameter of true denotes this Thread as a daemon thread.

public final void join(long millisec)


6 The current thread invokes this method on a second thread, causing the current thread to block
until the second thread terminates or the specified number of milliseconds passes.

public void interrupt()


7
Interrupts this thread, causing it to continue execution if it was blocked for any reason.

public final boolean isAlive()


8 Returns true if the thread is alive, which is any time after the thread has been started but before
it runs to completion.

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:

 An applet is a Java class that extends the java.applet.Applet class.

 A main() method is not invoked on an applet, and an applet class will not define main().

 Applets are designed to be embedded within an HTML page.

Compilation : Randjithkumar, B.Tech


Page 65
JAVA IN EASY WAYS

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

Life Cycle of an Applet:

Four methods in the Applet class give you the framework on which you build any serious applet:

 init: This method is intended for whatever initialization is needed for your applet. 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.

Compilation : Randjithkumar, B.Tech


Page 66
JAVA IN EASY WAYS

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

A "Hello, World" Applet:

The following is a simple applet named HelloWorldApplet.java:

import java.applet.*;
import java.awt.*;

public class HelloWorldApplet extends Applet


{
public void paint (Graphics g)
{
g.drawString ("Hello World", 25, 50);
}
}

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.

Getting Applet Parameters:

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.

Compilation : Randjithkumar, B.Tech


Page 67
JAVA IN EASY WAYS

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.

The following is a skeleton of CheckerApplet.java:

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) {}
}

Here are CheckerApplet's init() and private parseSquareSize() methods:

public void init ()


{
String squareSizeParam = getParameter ("squareSize");
parseSquareSize (squareSizeParam);
String colorParam = getParameter ("color");
Color fg = parseColor (colorParam);
setBackground (Color.black);
setForeground (fg);
}
private void parseSquareSize (String param)
{
if (param == null) return;
try {
squareSize = Integer.parseInt (param);
}
catch (Exception e) {
// Let default value remain
}
}

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.

Compilation : Randjithkumar, B.Tech


Page 68
JAVA IN EASY WAYS

Specifying Applet Parameters:

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

Reading and Writing Files:

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.

Here is a hierarchy of classes to deal with Input and Output streams.

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

Compilation : Randjithkumar, B.Tech


Page 69
JAVA IN EASY WAYS

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

InputStream f = new FileInputStream("C:/java/hello");

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:

File f = new File("C:/java/hello");


InputStream f = new FileInputStream(f);

Once you have InputStream object in hand then there is a list of helper methods which can be
used to read to stream or to do other operations on the stream.

SN Methods with Description

public void close() throws IOException{}


1 This method closes the file output stream. Releases any system resources associated with
the file. Throws an IOException.

protected void finalize()throws IOException {}


This method cleans up the connection to the file. Ensures that the close method of this file
2
output stream is called when there are no more references to this stream. Throws an
IOException.

public int read(int r)throws IOException{}


3 This method reads the specified byte of data from the InputStream. Returns an int. Returns
the next byte of data and -1 will be returned if it's end of file.

public int read(byte[] r) throws IOException{}


4 This method reads r.length bytes from the input stream into an array. Returns the total
number of bytes read. If end of file -1 will be returned.

5 public int available() throws IOException{}

Compilation : Randjithkumar, B.Tech


Page 70
JAVA IN EASY WAYS

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

OutputStream f = new FileOutputStream("C:/java/hello")

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:

File f = new File("C:/java/hello");


OutputStream f = new FileOutputStream(f);

Once you have OutputStream object in hand then there is a list of helper methods which can be
used to write to stream or to do other operations on the stream.

SN Methods with Description

public void close() throws IOException{}


1 This method closes the file output stream. Releases any system resources associated with the file.
Throws an IOException.

protected void finalize()throws IOException {}


2 This method cleans up the connection to the file. Ensures that the close method of this file output
stream is called when there are no more references to this stream. Throws an IOException.

Compilation : Randjithkumar, B.Tech


Page 71
JAVA IN EASY WAYS

public void write(int w)throws IOException{}


3
This methods writes the specified byte to the output stream.

public void write(byte[] w)


4
Writes w.length bytes from the mentioned byte array to the OutputStream.

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

 ByteArrayOutputStream

 DataOutputStream

Example:

Following is the example to demonstrate InputStream and OutputStream:

Compilation : Randjithkumar, B.Tech


Page 72

Anda mungkin juga menyukai