java in easy ways
TRANSCRIPT
-
8/6/2019 Java in Easy Ways
1/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 1
Java in Easy
Ways
-
8/6/2019 Java in Easy Ways
2/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 2
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
-
8/6/2019 Java in Easy Ways
3/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 3
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 beimplemented 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:
y Reusability of Codey Emphasis on data rather than procedurey Data is hidden and cannot be accessed by external functionsy Objects can communicate with each other through functionsy 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
-
8/6/2019 Java in Easy Ways
4/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 4
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++
-
8/6/2019 Java in Easy Ways
5/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 5
Method bodies must be defined inside the class
to which they belong.
Method bodies must be defined inside the class
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
program name.
Command-line arguments do not include the
program name.
Main method cannot return a value. Main function can return a value.
No global variables. Global variables.
Character escape sequences can appear in a
program.
Character escape sequences must appear in astring
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 beperformed. 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 :
-
8/6/2019 Java in Easy Ways
6/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 6
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 :
byteThe 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 ofint to increase the limit of the code. The syntax of declaring a byte type variableis shown as:
byte b = 5;
shortThe 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 typevariable is shown as:
short s = 2;
intThe 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 uselong. Thesyntax of declaring a int type variable is shown as:
int num =50;
longThe long data type is a 64-bit signed two's complement integer. It ranges from -
-
8/6/2019 Java in Easy Ways
7/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 7
9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Use this data type with larger rangeof values. The syntax of declaring a long type variable is shown as:
long ln = 746;
floatThe float data type is a single-precision 32-bit IEEE 754 floating point. It ranges from1.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 exactvalues 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 from4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). This datatype is generally the default choice for decimal values. The syntax of declaring a double type
variable is shown as:
double d = 6677.60;
charThe 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 oroff,
yes orno. 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 datatypes 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:
-
8/6/2019 Java in Easy Ways
8/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 8
Data Type Size (in bits) Minimum Range Maximum Range
ByteOccupy 8 bits
in memory-128 +127
ShortOccupy 16 bitsin memory
-32768 +32767
IntOccupy 32 bitsin memory
-2147483648 +2147483647
LongOccupy 64 bits
in memory-9223372036854775808 +9223372036854775807
Examples of floating-point literals are:
0
1123
-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
-
8/6/2019 Java in Easy Ways
9/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 9
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 multipleinheritance 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 typeuntil the object implements the specified interface.
When a class declaration implements an interface, that class inherits all of the variables andmethods 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();
-
8/6/2019 Java in Easy Ways
10/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 10
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. OperatorResult
+ 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){
-
8/6/2019 Java in Easy Ways
11/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 11
int result = 1 + 2; // result is now 3System.out.println(result);
result = result - 1; // result is now 2
System.out.println(result);
result = result * 2; // result is now 4System.out.println(result);
result = result / 2; // result is now 2
System.out.println(result);
result = result + 8; // result is now 10result = result % 7; // result is now 3
System.out.println(result);
}}
You can also combine the arithmetic operators with the simple assignment operator to createcompound 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 operatorsexist.
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;
-
8/6/2019 Java in Easy Ways
12/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 12
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 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 onsign extension.
The bitwise & operator performs a bitwise AND operation.
The bitwise ^ operator performs a bitwise exclusive ORoperation.
The bitwise | operator performs a bitwise inclusive ORoperation.
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 toyou 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
-
8/6/2019 Java in Easy Ways
13/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 13
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
-
8/6/2019 Java in Easy Ways
14/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 14
DECISION MAKING IN JAVA
There are two types of decision making statements in Java. They are:
y if statementsy 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
-
8/6/2019 Java in Easy Ways
15/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 15
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 totest various conditions using single if...else if statement.
When using if , else if , else statements there are few points to keep in mind.
y An if can have zero or one else's and it must come after any else if's.y An if can have zero to many else if's and they must come before the else.
-
8/6/2019 Java in Easy Ways
16/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 16
y 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.
-
8/6/2019 Java in Easy Ways
17/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 17
Syntax:
The syntax for a nested if...else is as follows:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is trueif(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 ifstatement.
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:
Aswitch 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 :
-
8/6/2019 Java in Easy Ways
18/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 18
//Statementsbreak; //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:
y The variable used in a switch statement can only be a byte, short, int, or char.y 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.
y The value for a case must be the same data type as the variable in the switch, and it mustbe a constant or a literal.y When the variable being switched on is equal to a case, the statements following that case
will execute until a breakstatement is reached.
y When a breakstatement is reached, the switch terminates, and the flow of control jumpsto the next line following the switch statement.
y Not every case needs to contain a break. If no break appears, the flow of control willfallthrough to subsequent cases until a break is reached.
y Aswitch statement can have an optional default case, which must appear at the end of theswitch. 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' :System.out.println("Well done");break;
case 'D' :System.out.println("You passed");
case 'F' :System.out.println("Better try again");break;
-
8/6/2019 Java in Easy Ways
19/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 19
default :System.out.println("Invalid grade");
}System.out.println("Your grade is " + grade);
}}
BRANCHING STATEMENTS
The Java programming language supports the following branching statements:
y The break statementy The continue statementy The return statement
The break and continue statements, which are covered next, can be used with or without a label.
A labelis 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++) {if (arrayOfInts[i] == searchfor) {
foundIt = true;
break;}
}
-
8/6/2019 Java in Easy Ways
20/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 20
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 4The 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++) {for (j = 0; j < arrayOfInts[i].length; j++) {
if (arrayOfInts[i][j] == searchfor) {foundIt = true;
break search;}
}
-
8/6/2019 Java in Easy Ways
21/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 21
}
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, 0This 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 thestatement 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'sif (searchMe.charAt(i) != 'p')
continue;
//process p's
numPs++;searchMe.setCharAt(i, 'P');
-
8/6/2019 Java in Easy Ways
22/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 22
}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
-
8/6/2019 Java in Easy Ways
23/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 23
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:
y while Loopy do...while Loopy forLoop
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:
The syntax of a while loop is:
while(Boolean_expression)
{//Statements
}
-
8/6/2019 Java in Easy Ways
24/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 24
When executing, if the boolean_expression result is true then the actions inside the loop will beexecuted. 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 : 11value of x : 12
value of x : 13value of x : 14
value of x : 15value of x : 16
value of x : 17value of x : 18
value of x : 19
The do...while Loop:
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to executeat least one time.
Syntax:
The syntax of a do...while loop is:
-
8/6/2019 Java in Easy Ways
25/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 25
Do{
//Statements}while(Boolean_expression);
Notice that the Boolean expression appears at the end of the loop, so the statements in the loopexecute 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 : 10value of x : 11
value of x : 12value of x : 13
value of x : 14value of x : 15
value of x : 16value 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 toexecute a specific number of times.
-
8/6/2019 Java in Easy Ways
26/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 26
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 declareand 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 statementcan 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 theprocess 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[]){
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 : 10value of x : 11
value of x : 12
-
8/6/2019 Java in Easy Ways
27/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 27
value of x : 13value of x : 14
value of x : 15value of x : 16
value of x : 17value 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 Javasupports the following fundamental concepts:
y Polymorphismy Inheritancey Encapsulationy Abstractiony Classesy Objectsy Instancey Methody Message Parsingy 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.
y Class - A class can be defined as a template/ blue print that describe the behaviors/statesthat object of its type support.
Objects in Java:
y The real-world we can find many objects around us, Cars, Dogs, Humans etc. All theseobjects have a state and behavior.
y If we consider a dog then its state is . name, breed, color, and the behavior is . barking,wagging, running
y If you compare the software object with a real world object, they have very similarcharacteristics.
y Software objects also have a state and behavior. A software object's state is stored infields and behavior is shown via methods.
y So in software development methods operate on the internal state of an object and theobject-to-object communication is done via methods.
-
8/6/2019 Java in Easy Ways
28/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 28
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.
y Local variables . variables defined inside methods, constructors or blocks arecalled local variables. The variable will be declared and initialized within the
method and the variable will be destroyed when the method has completed.y Instance variables . Instance variables are variables within a class but outside any
method. These variables are instantiated when the class is loaded. Instancevariables can be accessed from inside any method, constructor or blocks of that
particular class.y 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 andobjects should be created. We will be creating a separate class for these tasks.
Given below is the EmployeeTestclass 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
-
8/6/2019 Java in Easy Ways
29/73
-
8/6/2019 Java in Easy Ways
30/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 30
The length of an array is fixed at the time of its creation. An array represents related entitieshaving 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 asan 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 asquare bracket.
Advantages of using Arrays
1. You can refer to a large number of elements by just specifying the index number and thearray name.
2. Arrays make it easy to do calculations in a loop.The various types of arrays in java are:
y One-dimensional arraysy 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
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.
-
8/6/2019 Java in Easy Ways
31/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 31
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];
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[];
-
8/6/2019 Java in Easy Ways
32/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 32
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[];
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 elementof the array.
Simple Java Application using Arrays
import java.io.*;
-
8/6/2019 Java in Easy Ways
33/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 33
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;i50)
total+=mark[i];
else
{
total=0;
break;
}
}
}
public void displaystudent()
-
8/6/2019 Java in Easy Ways
34/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 34
{
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);
for(int i=0;i
-
8/6/2019 Java in Easy Ways
35/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 35
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 O bject class and implements the Serializable, Comparable, and CharSequenceinterfaces.
Java implements strings as objects of type String. A string is a sequence of characters. Unlikemost 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 itcontains 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.
Constructors defined in the String class
The String class defines several constructors. The most common constructor of the String class isthe one given below:
public String(String value)
This constructor constructs a new String object initialized with the same sequence of thecharacters 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()
-
8/6/2019 Java in Easy Ways
36/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 36
This constructor creates an empty String object. However, the use of this constructor isunnecessary because String objects are immutable.
public String(char[] value)
This constructor creates a new String object initialized with the same sequence of characterscurrently 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 characterscurrently 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 startindexrepresents 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 characterscurrently 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 characterset. 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 obtainedafter decoding the array.
public String(byte[] asciiChars, int startindex, int len)
This constructor creates the String object after decoding the array of bytes and by using thesubarray of bytes.
Special String Operations
y Finding the length of stringThe 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()
y String Concatenation using the + operator
-
8/6/2019 Java in Easy Ways
37/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 37
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 intvalue contained in the variable sale is automatically converted to String type, and then the +
operator concatenates the two strings.
String Comparison
The String class defines various methods that are used to compare strings or substrings within
strings. Each of them is discussed in the following sections:
equals()
The equals() method is used to check whether the Object that is passed as the argument to the
method is equal to the String object that invokes the method. It returns true if and only if theargument 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 stringwith the required modification:
substring()
-
8/6/2019 Java in Easy Ways
38/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 38
The substring() method creates a new string that is the substring of the string that invokes themethod. 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, thesubstring 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 ofthe 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 particularcharacter 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()
The trim() method creates a new copy of the string after removing any leading and trailingwhitespace. 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()
-
8/6/2019 Java in Easy Ways
39/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 39
Searching Strings
The String class defines two methods that facilitate in searching a particular character orsequence 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 theinvoking 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 followingsignatures:
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()
-
8/6/2019 Java in Easy Ways
40/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 40
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 (currentspeed, 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 drophandlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.
Object-oriented programming allows classes to inheritcommonly used state and behavior fromother 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 directsuperclass, and each superclass has the potential for an unlimited number ofsubclasses:
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
-
8/6/2019 Java in Easy Ways
41/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 41
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::
y java.lang - bundles the fundamental classesy java.io - classes for input , output functions are bundled in this package
Programmers can define their own packages to bundle group of classes/interfaces etc. It is a goodpractice 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 inother 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 AbstractWindow Toolkit. The "java.awt" package resides in a directory structure which reflects the
package name:
<path>/classes/java/awt/*.classAll 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:
-
8/6/2019 Java in Easy Ways
42/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 42
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 classesreside in the following directories:
Source Directory=========================/GUI/java/src/v2k/awt // Abstract Window Toolkit/GUI/java/src/v2k/ddo // Realtime Data Driven Objects/GUI/java/src/v2k/p3d // Three Dimensional
API PACKAGES
An application programming interface (API) is a library of functions that Java provides for
programmers for common tasks like file transfer, networking, and data structures.
ava API is not but a set of classes and interfaces that comes with the JDK. Java API is actually ahuge 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 inJava 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:
y Java Languagey JVM or Java Virtual Machine andy 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 Javalanguage.
Type of Java API
There are three types of API available in Java Technology.
y Official Java Core APIThe official core API is part of JDK download. The three editions of the Java
programming language are Java SE, Java ME and Java EE.
-
8/6/2019 Java in Easy Ways
43/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 43
y Optional Java APIThe optional Java API can be downloaded separately. The specification of the API is
defined according to the JSRrequest.
y Unofficial APIsThese API's are developed by third parties and can downloaded from the owner website.
Official Java Core API list
Name AcronymPackage(s) that contain
the APIDescription and Version History
Abstract Window
ToolkitAWT java.awt First released with version 1.0.
Swing javax.swing Included in J2SE 1.2 and later.
Accessibility javax.accessibility
Drag n Dropjava.awt.datatransfer
java.awt.dnd
Image I/Ojavax.imageio
javax.imageio.*
Sound
javax.sound.midi
javax.sound.midi.spi
javax.sound.sampled
javax.sound.sampled.spi
Java Database
ConnectivityJDBC
java.sql
javax.sql
Java Cryptography
ExtensionJCE
javax.crypto
javax.crypto.interfaces
javax.crypto.spec
Included as part of J2SE 1.4 and later. Available as an
optional package to versions 1.2 and 1.3.
JavaAuthentication and
Authorization
Service
JAAS javax.security.authIncluded in J2SE 1.4 and later, previously released as an
optional package with version 1.3.
Java Secure Socket JSSEjavax.net
javax.net.ssl
A set of packages that enable secure Internet
communications. Included as part of J2SE 1.4 and later
-
8/6/2019 Java in Easy Ways
44/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 44
Extension java.security.cert JSSE 1.0.3 is an optional package to the Java 2 SDK,
versions 1.2 and 1.3.
Java NativeInterface
JNI
Allows Java code running in the Java virtual machine (JVM
to call and be called[1] by native applications (program
specific to a hardware and operating system platform) a
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.
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{
-
8/6/2019 Java in Easy Ways
45/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 45
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
Adding a Class to an Existing Java Package
To add a Class to an existing Java Package do the following:
y 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;y 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/.
y 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 -doption tells the compiler to place the MyClass.class file in the directory:/GUI/java/classes/v2k/awt.
y If the CLASSPATH environment is notset, do the following :
% javac -d /GUI/java/classes -classpath.:/GUI/java/classes:/usr/java/classes
/GUI/java/src/v2k/awt/MyClass.java
-
8/6/2019 Java in Easy Ways
46/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 46
The -d option tells the compiler to place the MyClass.class file in thedirectory: /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
y there is no executable body for any method - that is left to each class that implements theinterface
Once a class implements an interface, the Java compiler knows that an instance of the class willcontain the specified set of methods
y therefore, it will allow you to call those methods for an object referenced by a variablewhose type is the interface
Implementing an interface enables a class to be "plugged in" in any situation that requires aspecific behavior (manifested through the set of methods)
An analogy: a serial interface on a computer defines a set of pin/wire assignments and the controlsignals that will be used
y the actual devices that can be used may do entirely different tasks: mouse, modem, etc.y 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
y in other words, if a class needs two different sets of methods, so it can behave like twodifferent types of things, it could inherit one set from class A, and use an interface B tospecify the other
y you could then reference one of these objects with either an A reference or a B reference
-
8/6/2019 Java in Easy Ways
47/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 47
Interfaces can also specify constants that are public, static, and final
Creating an Interface Definition
To create an interface definition:
y define it like a Java class, in its own file that matches the interface namey use the keyword interface instead of classy declare methods using the same approach as abstract methods
o note the semicolon after each method declaration - and that no executable code issupplied(and no curly braces)
o the elements will automatically be public and abstract, and cannot have any otherstate; it is OK to specify those terms, but not necessary (usually public is specifiedand abstract is not - that makes it easy to copy the list of methods, paste them into
a class, and modify them )
y The access level for the entire interface is usually publico it may be omitted, in which case the interface is only available to other classes in
the same package (i.e., in the same directory)
o note, for the sake of completeness, there are situations where the interfacedefinition 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
-
8/6/2019 Java in Easy Ways
48/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 48
This interface requires only one method. Any class implementing Printable must contain a publicvoid 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 - theseare 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
02 #include
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 };
-
8/6/2019 Java in Easy Ways
49/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 49
15
16 //Bird is a derived class from Animal
17 class Bird : public virtual Animal {
18 public:
19 void birdNoise() { cout
-
8/6/2019 Java in Easy Ways
50/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 50
38 Pegasus* peggi = new Pegasus("Pegasus", 5); //create the pegasus object
39 cout getName() horseNoise();
42 delete peggi;
43 return 0;
44 }
A possible UML diagram based on the following:
-
8/6/2019 Java in Easy Ways
51/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 51
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 javaexceptions are objects of classes that are descendents of Throwable class. There are twopredefined 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 bythe user.
-
8/6/2019 Java in Easy Ways
52/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 52
User programs can define their own exception classes. Convention in Java is that such classes aresubclasses of Exception. There are two predefined descendents of Exception: IOException and
RuntimeException. IOException deals with errors in I/O operation.
In the case ofRuntimeException 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 arenever 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 amethod 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 bepresent and its class must be descendent of Thrwoable. The syntax oftry 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 statementof 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 endof the handler. To ensure that exceptions that can be thrown in a try clause are always handled ina method, a special handler can be written that matches all exceptions. For example:
catch (Exception anyException) {
-
8/6/2019 Java in Easy Ways
53/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 53
}
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 objectthat stores the class name. It has a getName method. The name of the class of the actualparameter 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 fieldsthat might be useful in the handler.
throwsClause
throws clause is overloaded in C++ and conveys two different meanings: one as specificationand 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 orany 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. Amethod 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 anothermethod 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.
ClassNotFoundExceptionIllegalAccessException
IOExceptionEOFException
FileNotFoundExceptionMalformedURLException
ProtocolExceptionSocketException
UnknownHostExceptionUnknownServiceException
These exception classes include data, such as an error message which can be set by theprogrammer, and several useful methods such as:
-
8/6/2019 Java in Easy Ways
54/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 54
printStackTrace(), which prints a trace of where the error occurred, and the methods throughwhich 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 unexpectedsituations. The compiler wont allow you to ignore these exceptions you must do one of twothings. You can eitherpropagate the exception in other words, pass it on for another method
to deal with, or catch it, and deal with it yourself. Well 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 ofthe 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 throwsIOException in its own header.
Catching an Exception: This is done by enclosing the statements that may cause an error in atry 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 tryblock, 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:
-
8/6/2019 Java in Easy Ways
55/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 55
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 toinclude 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;charOp;
// *******************************************************// 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);}
-
8/6/2019 Java in Easy Ways
56/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 56
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);
}
}
-
8/6/2019 Java in Easy Ways
57/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 57
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 thatwe might encounter.
While defining an user defined exception, we need to take care of the following aspects:
y The user defined exception class should extend from Exception class.y 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;
}}
-
8/6/2019 Java in Easy Ways
58/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 58
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 -10at
tips.basics.exception.CustomExceptionTest.main(CustomExceptionTest.java:10)
-
8/6/2019 Java in Easy Ways
59/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 59
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.
-
8/6/2019 Java in Easy Ways
60/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 60
Above mentioned stages are explained here:
y New: A new thread begins its life cycle in the new state. It remains in this state until theprogram starts the thread. It is also referred to as a born thread.
y Runnable: After a newly born thread is started, the thread becomes runnable. A thread inthis state is considered to be executing its task.
y Waiting: Sometimes a thread transitions to the waiting state while the thread waits foranother thread to perform a task.A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue executing.
y Timed waiting: A runnable thread can enter the timed waiting state for a specifiedinterval 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.
yTerminated: A runnable thread enters the terminated state when it completes its task orotherwise terminates.
-
8/6/2019 Java in Easy Ways
61/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 61
Thread Priorities:
Every Java thread has a priority that helps the operating system determine the order in whichthreads 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 priorityNORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated processortime 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:
y You can implement the Runnable interface.y 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 isdeclared 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 themain 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 shownhere:
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.
-
8/6/2019 Java in Easy Ways
62/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 62
After the new thread is created, it will not start running until you call its start( ) method, whichis 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 threadt = 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 threadtry {
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.");
}}
-
8/6/2019 Java in Easy Ways
63/73
JJAAVVAA IINN EEAASSYY WWAAYYSS
Compilation : Randjithkumar, B.TechPage 63
This would produce following result:
Child thread: Thread[Demo Thread,5,main]Main Thread: 5Child Thread: 5
Child Thread: 4Main Thread: 4Child Thread: 3Child Thread: 2Main Thread: 3Child Thread: 1Exiting child thread.Main Thread: 2Main Thread: 1Main 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 tocreate an instance of that class.
The extending class must override the run( ) method, which is the entry point for the new thread