jawarlal nehru college of technology
TRANSCRIPT
-
8/3/2019 Jawarlal Nehru College of Technology
1/57
JAWARLAL NEHRU COLLEGE OF TECHNOLOGY(Affiliated to R.G.P.V. BHOPAL & approved by A.I.C.T.E.)
Submitted in partial fulfillment of the
Requirement for award of the degree of bachelor of
Engineering In
COMPUTER SCIENCE
MAJOR -TRAINING
2009-2010
A REPORT ON
CORE JAVA
SUBMITTED BY:- UNDER THE GUIDANCE OF:KALPNA DWIVEDI Mr. SURAJ SAHU
(H.O.D., C.S.)
-
8/3/2019 Jawarlal Nehru College of Technology
2/57
Acknowledgement
Every endeavor we understand takes an indomitable urge,
perseverance, and proper guidance especially when it is most needed.
Internally motivated to undertake some appreciable work as our
industrial training, unsure though, but with a hope we took this project
work to be completed. Initially we had hardly ever thought of, the kind
of work we were going to do.
We are thankful to Mr. Suraj Sahu H.O.D. of Computer
Science and Engineering who has been a constant source of
encouragement and helping us whenever required.
We are very much thankful to Mr. Rohit Ahuja under whose
guidance this training has been successfully completed.
Here we think from the core, everybody who has helped us at work. In
true sense, besides our guides we are indebted to many other
members at SIST for their constant help and invaluable contribution on
all occasions when they were most needed. Again, we find the
opportunity to acknowledge our regards and thanks to our family
members and friends who have been true support behind us.
KALPNA DWIVEDICSE VII SEM0306CS081031
JNCT Rewa
-
8/3/2019 Jawarlal Nehru College of Technology
3/57
INTRODUCTION
During the industrial training the topics and knowledge aboutthe technologies which we came to know are as follow:
+ Data Types,Variables,Literals,I/O,Consructs.
+ Classes and Objects.
+ Inheritence.
+ Static,Abstract and Final.
+ String,Arrays And Command Line Arguments.
+ Interface and Packages.
+ Exception Handling.
+ Collection and Generics.
+ Applets.
+ Files and Streams.
+ Swings.
+ Multithreading.
+ Socket Programming.
+ Database.
-
8/3/2019 Jawarlal Nehru College of Technology
4/57
Java Runtime Environments:
Stand-alone programs probably aren't what you'll be writing in the
longer term,even though they're excellent for learning the fundamentals ofJava. Later on you'll be slotting your classes into other Java runtime
environments, some of which areopen source and others are commercial
products.
Server side, there are a number of environment interfaces you may use.
These include:
+Servlets: Executable programs with a web interface
+JSPs: Embedding server executable content within a web page
+RMI and EJBs Providing object servers
Java distributions
The Java 2 Standard Edition (J2SE) provides the essential compiler, tools,
runtimes, and APIs for writing, deploying, and running applets and
applications in the Java programming language.
The Java 2 Enterprise Edition (J2EE) technology and its component-based
model simplifies enterprise development and deployment. The J2EE
platform manages the infrastructure and supports the Web services to enabledevelopment of secure, robust and inter-operable business applications. The
download has essential extra classes and environments to use in addition to
the J2SE, which you will also need.
Java standard packages
+Much of the power of a Java application is vested not in the language
itself, but in all the standard classes provided and optional classes available.
There are so many classes that
they've been organized into bundles (called "packages") foreasier management.
+The first release of Java included eight packages.+Standard package names start "java." or "javax.".
For example:There'sjava.langto provide basic language facilities,
java.netto provide network access,
-
8/3/2019 Jawarlal Nehru College of Technology
5/57
javax.swingto provide the Swing GUI andjavax.servletto provide Servletsupport.
You'll come across many more standard packages as you learn Java;
however, as a rule of thumb, if the
package name starts "java" or "javax", it's standard, but if it starts with
something else like "com", it isn't.
Java versions
Java started off as Java release 1.0, and progressed through to Java 1.5. Sun
were very conservative in moving the release numbers forward, so much so
that the "1." Just became a part of the name. In summer 2004, Java 1.5 was
re-branded Java 5.
Java 1.2 was a major step, with a tripling of the number of packages
provided.
At that point Sun rebranded the new version the "Java 2 Platform".
Methods and classesYou write all your executable java code in "methods", and all methods must
be grouped into "classes".
Optionally, you can group classes into "packages" but we won't
do that until later on. A method is a piece of program code with a name. It
can receive any number of input objects or primitives (known as parameters)
when it is run, and it can return 0 or 1 object or primitive when it completes
running.
A class is a group of methods, all of which are concerned with objects of the
same type.If you're already an experienced programmer from some other
language, you may think that a method sounds very much like a function,
proc, sub, subroutine, macro or command, and you would be right, although
there is a little more to it. Java is an Object Oriented language, where you
run a method on an object.Let's see a first Java class and method in a form that we can run it as if it was
a standalone
program:
//Tiniest of programs to check compile / interprettoolspublic class Hello {public static void main(String[] args) {System.out.println("A program to exercise the Javatools");}}
-
8/3/2019 Jawarlal Nehru College of Technology
6/57
Blocks and statement structure
Within a java source file, we group together program elements into
blocks within curly braces ( {} ) where blocks are frequently nested within
blocks. Our simplest program has two nested blocks. The outer block definesthe class (it's called "Hello") and the inner block defines a method called
"main". We could add other methods if we wanted, and they would go inside
the outer block and outside the inner block. There is no practical limit to the
number of methods we can define in a class, nor to the length of a block.
Within methods, our executable program code will consist of a series of
statements, each of which ends with a ; character. Unless it specifiesotherwise, each statement is performed in turn. The ; is mandatory, andyou can put as much (or as little) white space as you like into a statement.
Declaring classes and methods
If you're declaring a class or a method, you have to tell Java the name
that you want to associate with the class or method, and how accessible it is
to be from elsewhere in your application.
Our class is declared in this example aspublic class Hellowhich means:
It's available to any other class (public) It's a class (class) It's called Hello (Hello)Our method is declared as
public static void main(String[] args) which means:
It's available to run from any other class (public) It's not dependent on any particularobject (static) It doesn't pass anything back to the code that calls it (void) It's called main (main)
It takes one parameter, an array of Strings that it will know as "args" Thiscombination of keywords and choices just happens to be what the JVM for
stand-alone programs is looking for when it's run - i.e. a static method called
"main" that takes a String array of parameters when it's called. If you vary
any part of that specification, then you might still be able to compile
correctly but your code won't be able to run as a stand-alone.
-
8/3/2019 Jawarlal Nehru College of Technology
7/57
Within a statementEach Java executable statement comprises a series ofoperators and operands: System.out.println("A program toexercise the Java tools");
println and "." are operators. The string written in double quotes is an
operand, as is System.out.When a statement is run, each of the operators operates on the operandsbefore, after, or on both sides of it. Our first sample statement tells Java to
print out a copy of the String that's in the brackets to the System.outchannel.println is just one of the thousands of methods available asstandard in Java 1.4. We suggest you get yourself a good reference book that
lists them all in some sort of logical order as there's no way you'll remember
them.
Reserved words:In our example, words like "public" and "class", "static" and "void" are
understood by the Java Virtual Machine. Words like "main" and "println"
are not understood by the JVM, but are nevertheless unchangeable as they
are part of the standard classes and methods provided. On the other hand, the
words "Hello" and "args" are our choice, and we can change them if we
wish. You must not use words that the JVM itself understands (they are
"reserved words") for things you name yourself. You should also avoid
using words that relate to standard classes and methods for things you name.
Commenting your source:The final element of our first program is the very first line. It appears to
break the rules that we've given so far. It's not in a block, it doesn't seem to
have operators, and it doesn't end in a semicolon. It's a comment.
If the java compiler comes across two slashes when it's "tokenizing" the
source code, it ignores subsequent text up to the end of the line. This allows
you to put reminders of how your code works and what it does into your
source. You can also write a comment starting with
/* in which case everything up to the following */ willbe treated as a comment.
The code in operationHaving explained the code in depth, let's see the whole program again, and
then let's compile and run it:bash-2.04$ cat Hello.java
-
8/3/2019 Jawarlal Nehru College of Technology
8/57
//Tiniest of programs to check compile / interprettoolspublic class Hello {public static void main(String[] args) {System.out.println("A program to exercise the Javatools");}}
Variables:Information that's produced by one Java statement and used in laterones is held in variables. In Java, variables must be declared beforethey are used, and you must specify the type of information theycontain.
Operations can be performed on variables, and casting can be usedto convert information of one type to another.First use of variables in Java.Type casting and conversion .Reading input from the user .
First use of variables in JavaIn Java, you have to tell the compiler about variables before you use them.
This is known as declaring a variable. You also have to tell the compiler
what type of information a variable will hold. Java has just eight primitive
types built into the JVM itself.
Here's an example using variables:public class Addup {public static void main(String [] args) {int rovers;int city;int total;rovers = 3;city = 2;
total = rovers + city;System.out.print("Today, Bristol teams scored ");System.out.print(total);System.out.println(" goals");}}We have declared three variables, called "rovers", "city" and "total".
-
8/3/2019 Jawarlal Nehru College of Technology
9/57
The = operator tells Java to evaluate the expression to the right and save itin the variable named on the left, so we set rovers to "3" and city to "2".
Then we add up the contents of rovers and city, and save the result into total.
Finally, we print out our results. You may have noticed that we usedprint
rather thanprintln for two out of the three outputs.Theprintlnmethod adds a new line on the end of the text it outputs, but theprintmethod does not. This allows us to make up a single line of
output using multipleprint statements.
Variable namesAs long as you don't use a reserved word, you can use any variable name
you like within the following rules:
Starts with a letter
followed by as few or as many letters, digits and underscores as you likeRemember that variable names are case sensitive. The variable "rovers" is
notthe same as the variable "Rovers".We suggest that for variables of this type (primitives), you:
Use lower case letters throughout
Make the names descriptive, but not very longbash-2.04$ java AddupToday, Bristol teams scored 5 goalsbash-2.04
Declaring and initialising variables:You can save yourself some lines of code if you declare several variables at
the same time, initialising them at the same time too. You might also like to
note that declarations don't have to be at the top of blocks as they do in some
other languages.public class Add2 {public static void main(String [] args) {int rovers = 1, city = 2;System.out.print("Today, Bristol teams scored ");int total = rovers + city;
System.out.print(total);System.out.println(" goals");}}
-
8/3/2019 Jawarlal Nehru College of Technology
10/57
Primitive types"int" means "integer". In other words, a whole number. In Java, intvariables occupy 4 bytes and so are 32-bit valued. This is a fixed part of the
Java specification.
Whole number primitive variable types are:Byte: 1 byteShort: 2 bytesInt: 4 bytesLong: 8 bytesIf you want to work with numbers with decimal places (i.e. floating point
numbers), Java provides:
float: 4 bytesdouble: 8 bytesThere are two further primitives which don't hold numbers at all:
Char: to hold a characterBoolean: to hold either true or false
Type casting and conversionLet's say that I want to report the average score of our teams:public class Average {public static void main(String [] args) {int rovers = 2, city = 3;System.out.print("Today, Bristol teams averaged ");
float total = rovers + city / 2;System.out.print(total);System.out.println(" goals");}}System.out.println(" goals");}}
Reading input from the userAlthough it's a fundamental requirement of most applications to read data, it
uses some non-basic concepts of Java. Data input is very prone to errors;
users may enter letters rather than numbers, the network connection may go
wrong, and a whole host of other things could happen that need trapping and
handlingnot something that's practical for us to do this early in yourlearning.1 Therefore, we're going to take a different approach. Java is all
-
8/3/2019 Jawarlal Nehru College of Technology
11/57
about using code that other people have written, either as part of the team, or
more generally. Such code is put into classes which are then available to you
(that is, if they're declared public). To get you into the good practice of re-
using other people's code rather than redoing a job that's been done many
times before, we're providing you with a class called "WellHouseInput" that
will read user inputs from the keyboard.javap WellHouseInputpublic class WellHouseInput extendsjava.lang.Object {Compiled from WellHouseInput.javapublic WellHouseInput();public static float readNumber();public static java.lang.String readLine();}
Please beware these methods are notpart of the standard Java distribution,but you're welcome to use them in your own programs if they do what you
want. It's up to you to check that's the case! Let's write a program to read in
an quantity and a unit price, and report on the
grand total to be paid:public class Cost {public static void main(String [] args) {// Prompt - read sequences ( x 2) for inputsSystem.out.print("How much do they cost each? ");float each = WellHouseInput.readNumber();System.out.print("How many do you want to buy? ");float quantity = WellHouseInput.readNumber();// Do the calculationsfloat total = each * quantity;System.out.print("Total cost ");System.out.print(total);System.out.println(" excluding tax and shipping");}
Loops and Conditional Statements:Unless otherwise specified, code runs from top to bottom, very muchin the manner that you read a book. Conditional statements such as"if" allow the programmer to choose whether or not blocks of the codeare to be skipped over, and loops such as "while" allow blocks ofcode to be repeated.
-
8/3/2019 Jawarlal Nehru College of Technology
12/57
Booleans ."if" statement ."while" loop."for" loop .
BooleansWeve read data, calculated with it and printed out the answers so far. A
glorified calculator that performs exactly the same mechanical steps each
time we run it.
But we are going to want to make decisions. "If the temperature is high,
print an advert for ice cream; otherwise, advertise thermal vests!!" Decisions
are based on something being "true" or "false" -- that somethingis called aboolean object. Boolean variables can be declared in just the same way
as a float or an int or the others you have seen so far. Booleanvariables can have values assigned to them in just the same way that other
variables can. Beware: You cant assign a number to a boolean. Fortunately,
more operators are available which operate on numbers, but produce a
boolean answer. The operator >means "is greater than" and yields aboolean result. Other operators include:
< less than= greater than or equal to
== equals!= does not equalAs you can see, some operators are now more than just a single character. In
particular, you need to understand the difference between = and ==.=evaluates the expression to the right of the sign and assigns the resultto the variable named to the left. == evaluates two expressions, and if theyyield the same result, it gives "true". If they do not yield the same result, it
gives "false".boolean temp_level = (yesterday == today);
Compares the contents of the variables yesterday and today. Sets temp_level to "true" if they are the same [number], and to "false"otherwise.
By the way, did you notice?System.out.print("\"It is getting colder\" is ");
"if" statementWe wont (very often!) want to just
-
8/3/2019 Jawarlal Nehru College of Technology
13/57
We wont (very often!) want to just print out the words "true" or "false".Much more likely well want to perform an action ifa boolean is true. Yes,an if statement.public class Firstif
{public static void main(String[] args){System.out.println("Let us warn you if it's gettingcolder!");System.out.print("Yesterday: ");float yesterday=WellHouseInput.readNumber();System.out.print("Today: ");float today=WellHouseInput.readNumber();boolean chilling = (yesterday > today);
if (chilling)System.out.println("It is getting colder");System.out.println("Check completed");}}
"while" loop
As well as providing pieces of code which are only performed if a condition
is true -- conditional code -- we may wish to repeat a section of code, time
and time-again. Take, for example, adding up a series of items on a bill.
What are the elements needed? Some statement to say "the following code
must be repeated." Something to say "this is the end of the section to be
repeated."
And some way of knowing when the repetition is completed and the
program is to continue running beyond the code which has been repeated.
We use awhile statement to say "the following code is to be repeated" We follow thewhile statement with a block of code in curly braces {}
that block indicates how much is to be repeated.
We place an expression in brackets which yields a boolean result after the
wordwhile.
Arrays:A regular variable can hold one piece of information, but an array canhold more than one. Arrays are declared to hold a number ofelements, and data is then written to and read from each elementbased on its position number.
-
8/3/2019 Jawarlal Nehru College of Technology
14/57
Definition and declaration .Use.Array manipulation and replacement .Multidimensional arraysArrays of Objects .
Definition and declaration:Just like other variables we have seen, you must define that the variable
called "costs" is going to contain float information, and you must alsodeclare its going to be an array:
float[] costs; That has defined how the variable name will be used,but has not set aside anymemory for it. Since computers store things one-after-another in memory, we must actually create our array, declaring its
size: costs = new float[5];
In Java, the array is actually an object (well come onto objects soon)created by using the new method. It is important that you understand thedistinction between defining an array and actually allocating the memory for
it, although in practice you could do both in one line:float [] costs = new float [5];
Multidimensional arrays:
public class rushall
{pu/** Two Dimensional Array */blic static void main(String[] args){int [] pack = new int [52];int [] shpack = new int [52];int k,j;for (k=0;k
-
8/3/2019 Jawarlal Nehru College of Technology
15/57
The initial section creates a pack of 52 cards in order. They are then shuffled
by choosing a card at random 52 times over and adding it to the shuffled
pack. As each card is added randomly to the shuffled pack, the last seal%java rushall
Arrays of Objects:Just as you can have arrays of primitives, so you can have arrays of objects
too. The following tells you your longest and shortest films:public class Weekend {public static void main(String [] args) {// Set up a series of film objectsFilm Watch[] = new Film[4];Watch[0] = new Film("Shrek",133);
Watch[1] = new Film("Road to Perdition",117);Watch[2] = new Film("The Truth about Cats andDogs",93);Watch[3] = new Film("Enigma",114);Film Longest = null, Shortest = null; // To avoid agrumpy compilerint longtime = 0, shorttime = 0; // To avoid agrumpy compilerfor (int i=0; i longtime) {
longtime=mins;Longest = Watch[i];}}}System.out.println("Longest film is " +Longest.getcalled() +
-
8/3/2019 Jawarlal Nehru College of Technology
16/57
at "+longtime+" minutes");System.out.println("Shortest film is " +Shortest.getcalled() +" at "+shorttime+" minutes");}}
Objects and Classes:In Java, we place all our code in "classes". Each class contains oneor more named blocks of code known as methods, and the group ofmethods provides all the functionality that's required to handle data(or objects) of a particular type.Using an instance of a class .
Writing your own class .Enhancements to the basic class structure .Naming conventions.
Writing your own class:In order for the application we've just looked at to work, someone had to
write and provide the Film class, not too hard as it's just another class:public class Film {String called;int minutes;public Film (String title, int length) {called = title;minutes = length;}public int getminutes() {return minutes;}public String getcalled() {return called;
}public void setminutes(int length) {minutes = length;}}
First, note there's nomain method. The Filmclass isn't written to run asa standalone application, so it doesn't need such a method. What does it
-
8/3/2019 Jawarlal Nehru College of Technology
17/57
have? It has a method with the same name as the name of the class
"Film".By definition Java, this is the constructor method that is run when thenew keyword is in used on the class.
String called;int minutes;
For each object of type Filmthat we create, two new variables ("called"and "minutes") will be created. When we call any of the other methodsthat we have defined on the class, it will choose which calledor
minutes variable to use depending on which instance of the class we havecalled the method on.
Enhancements to the basic class structureClass or static methods:How many films do we have? In our example, we had two but it's not
immediately obvious how we could find that out from a method call to the
class. We need a new type of variable or methoda class variable ormethod, which applies to the class as a whole and not to any particular
instance of the class. Such variables and methods are referred to as static,since Java always uses the same variable or method no matter which
member of the class they're called on, or indeed if they're called on the class
as a whole.
Overloading:Important to note: In Java, when you call a method you must get thenumber and type of parameters correct. This can be done equally wellwith the constructor,static or dynamic methods.Java supports a Unicode character set that allows for more than65,000 different characters. Single characters can be held in charvariables, and multiple character sequences (strings) can be held inchar arrays, String- Buffer objects and String objects.
Character variable .String constants. .Creating String objecsOperations on strings. .Comparing strings .Accessing characters within strings.Character arrays v String objects .
-
8/3/2019 Jawarlal Nehru College of Technology
18/57
String buffers. .
Character variables:We need to be able to handle characters as well as numbers. We coulduse adata type char for character ...// Well House Consultants,20 04.import java.lang.Math;/** Character Variable*/public class ramsbury{public static void main(String[] args){int card = 1 + (int) (Math.random()*52.0);
System.out.print("You have drawn ");System.out.println(card);int rank = (card-1) / 4;int suit = (card-1) % 4;char [] suites = { 'C','D','H','S'};char [] ranks = {'2','3','4','5','6','7','8','9','T','J','Q','K','A'};char rank_letter = ranks[rank];char suit_letter = suites[suit];System.out.print("You have drawn ");
System.out.print(rank_letter);System.out.print(" of ");System.out.println(suit_letter);
String constantsString constants1 can be multiple characters in length and are writtenusing double quotes.
They can contain as few or as many characters as you like:
9 1 character10 2 characters
Queen 5 characters
Special characters may be included in Strings using an escape sequence
starting with a \ character.Two-character sequences include:
\n new line
-
8/3/2019 Jawarlal Nehru College of Technology
19/57
\t tab\" double quote\\ backslash\b backspace
You can also use unicodes to represent any character. Unicodes are how thestrings are held internally:
\u0068 lower case h\u00a3 signHeres a code chunk showing these codes in action:String [] suites = { "\"Hit \u0068im\"\nhe said","\"worth \u00a3s\"","Hearts","Spades"};seal% java blunsdonYou have drawn 18You have drawn 6 of "worth s"seal%
Comparing strings:We might also want to compare strings. Lets see a code snippet which setsup two strings that we want to compare with each other:String affirm = "yes";System.out.print("Please enter yes or no : ");
String you_said = WellHouseInput.readLine();
if (you_said == affirm) {System.out.println("GOT WHAT I WANTED");} else {System.out.println("Oh dear ....");}but it doesnt. What it actually tests is whetheryou_saidand affirmbothpoint to the same instance on an object of the type String. Two instances of
type String: Although both instances contain identical data using ==, tocompare them will give a falseresult.seal% java ingleshamdemo_one has the value 1010demo_two has the value 20seal%Only in this situation ...
-
8/3/2019 Jawarlal Nehru College of Technology
20/57
will == give a trueresult.If you wish to compare two different String objects to see if the contents are
the
same, use the equal method from one of the objects, giving the other object
as a parameter:if (you_said.equals(affirm)) {System.out.println("GOT WHAT I WANTED");}Lets confirm that in a complete example:// Well House Consultants,20 04./** string comparison*/public class ashton{public static void main(String[] args)
{String affirm = "yes";System.out.print("Please enter yes or no : ");String you_said = WellHouseInput.readLine();System.out.println("you said " + you_said);System.out.println("hoping for " + affirm);// you may guess the following will work but// it will NOT.System.out.print("Trying \"==\" ... ");if (you_said == affirm) {System.out.println("GOT WHAT I WANTED");} else {System.out.println("Oh dear ....");}// But this WILL do what you hope for ...System.out.print("Trying \"equals\" ... ");if (you_said.equals(affirm)) {System.out.println("GOT WHAT I WANTED");
} else {System.out.println("Oh dear ....");}}}
-
8/3/2019 Jawarlal Nehru College of Technology
21/57
Accessing characters within strings:The startsWith method can take a second (integer) parameter to startchecking from somewhere other than the first character. Of course, youllwant to know other things about strings as well, such as:
What is the length of a string?
Where is the first/next/last "x" in a string?For the length, there is a length method.For the first occurrence, use indexOfwith a single parameter, and for the
next occurrence use indexOf with two parameters. Working backwards,use the lastIndexOf method instead. Both indexOf andlastIndexOf will accept either a char or a String object as thesearch pattern.// Well House Consultants,20 04./** string analysis*/public class minety{public static void main(String[] args){System.out.print("Please enter a phrase : ");String you_said = WellHouseInput.readLine();System.out.println("you said " + you_said);System.out.println("length of data " +
you_said.length());
Character arrays v String objects:If you want to perform low-level manipulation of the characters within a
string, you may be advised to use an array of individual characters.
Method toCharArray in public java.lang.String(char[]);public java.lang.String(char[],int,int);public java.lang.String(byte[],int,int,int);publicjava.lang.String(byte[],int,int,java.lang.String)
throws java.io.UnsupportedEncodingException;public java.lang.String(byte[],java.lang.String)throws java.io.UnsupportedEncodingException;public java.lang.String(byte[],int,int);public java.lang.String(byte[]);public java.lang.String(java.lang.StringBuffer);java.lang.String(int,int,char[]);
-
8/3/2019 Jawarlal Nehru College of Technology
22/57
public int length();public char charAt(int);public void getChars(int, int, char[], int);public void getBytes(int, int, byte[], int);public byte getBytes(java.lang.String)[] throwsjava.io.UnsupportedEncodingException;public byte getBytes()[];public boolean equals(java.lang.Object);public boolean equalsIgnoreCase(java.lang.String);public int compareTo(java.lang.String);public int compareTo(java.lang.Object);public int compareToIgnoreCase(java.lang.String);public boolean regionMatches(int, java.lang.String,int, int);
public boolean regionMatches(boolean, int,java.lang.String, int, int);public boolean startsWith(java.lang.String, int);public boolean startsWith(java.lang.String);public boolean endsWith(java.lang.String);public int hashCode();
public int indexOf(class String will convert a String objectinto an array of characters.
Method getChars is more flexible and can be used to extract part of acharacter string (like substring does) and place it starting at anyposition within a characters array.
Method copyValueOf will convert an array of characters into a Stringobject.// Well House Consultants,20 04./** string to char array*/public class crudwell{public static void main(String[] args)
{System.out.print("Please enter a phrase : ");
String buffersA StringBuffer object should be used when you wish to use a stringthat can be changed directly.
-
8/3/2019 Jawarlal Nehru College of Technology
23/57
StringBuffers have many similarities to strings, but do not have the full
capabilities of strings in other areas. Youll often see a StringBuffer used as
a piece of text is built up, and then the resultant buffer being placed into a
String for further handling. Indeed, this is what the compiler itself does
with the operator + on strings! Lets see the creation, extension and copyingback to a string in use in a typical piece of code:// Well House Consultants,20 04./** stringBuffers */public class malmesbury{public static void main(String[] args){System.out.print("Please enter a paragraph : ");
String you_said;// Create a string buffer, and initialize it emptyStringBuffer paragraph = new StringBuffer("");// read from the user until he enters a blank line// build up entries in the stringbufferwhile (!((you_said=WellHouseInput.readLine())).equals("")){paragraph.append(you_said);paragraph.append(" ")Other methods available on StringBuffers include:
charAt to return the character at a particular positiongetChars to place a series from a StringBufferinto an array of characters setCharAt to set the character at a particularposition Insert to insert at a position (first parameter)the (second) named parameter
Packages:Java applications often comprise a very large number of classes. Inorder to provide for management of all these classes, they arearranged into groupings as packages, with each package containinga logical group of related classes.Overview .Package directory structure .Importing classes from a package .
-
8/3/2019 Jawarlal Nehru College of Technology
24/57
Introduction to standard packages .
Overview:As we start to develop more complex programs, well start to use more andmore classes. Some classes will be from standard libraries; others will be
classes which we develop ourselves.
After we get to the point of having classes all over the place, well want to
provide some sort of organisation. Lets return to our card decks. We alreadyhave a class of object for a card pack, but we might also develop other
classes and objects for a hand, and sub-objects for individual cards.
Immediately, the number of different classes starts to multiply!! The solution
Java provides is topackage classes.
Package directory structure:One of the purposes of packaging classes was to allow us to structure our
directories.
Java packages should be stored in subdirectories of the same name as the
package.
Remember that, already, the class file1 must be stored in a file of the same
name as the class so that our packclass within the card_pkgpackage mustbe stored in the file:card_pkg/pack.java
relative to the calling class/method.In our example (and on the authors system) the files pertinent to the currentexample are:
/export/home/graham/JF/sopworth.class/export/home/graham/JF/card_pkg/pack.classComplete listings on the .javafiles follow for reference ...
/export/home/graham/JF/sopworth.java// Well House Consultants,20 04./** Packaged card pack*/public class sopworth
{public static void main(String[] args){System.out.println("Regular pack");card_pkg.pack my_pack = new card_pkg.pack();System.out.println(my_pack.ncards);my_pack.print();
-
8/3/2019 Jawarlal Nehru College of Technology
25/57
System.out.println("Double pack, 5 jokers");my_pack = new card_pkg.pack(2,5);System.out.println(my_pack.ncards);my_pack.print();System.out.println("Short pack, 24 cards removed");my_pack = new card_pkg.pack(1,0,6);System.out.println(my_pack.ncards);my_pack.print();}}
Importing classes from a package:We can use classes and methods from a package. All we have to do is to
give the package name as we create new instances or reference methods
where there is no instance variable to tell Java which package and class touse.
But perhaps we would prefer not to have to state in which package the
method is to be found. Perhaps we would like to have Java find the methods
for us, or to tell Java to use all the methods within a package without
explicitly naming them all the time.
Yes we can.
We can use import statements to pull packages and classes into ourmethods.
Forexample, to bring in all classes in the card_pkgpackage:import card_pkg.*;We can then reduce the code we need from:card_pkg.pack my_pack = new card_pkg.pack();to:pack_pkg my_pack = new pack_pkg();The pack class is unaltered. The new main method:// Well House Consultants,20 04./** Packaged card pack*/import card_pkg.*;
public class sherston{public static void main(String[] args){System.out.println("Regular pack");pack_pkg my_pack = new pack_pkg();System.out.println(my_pack.ncards);
-
8/3/2019 Jawarlal Nehru College of Technology
26/57
my_pack.print();System.out.println("Double pack, 5 jokers");my_pack = new pack_pkg(2,5);System.out.println(my_pack.ncards);my_pack.print();System.out.println("Short pack, 24 cards removed");my_pack = new pack_pkg(1,0,6);System.out.println(my_pack.ncards);my_pack.print();}}Introduction to standard packages:There are various sorts of packages you may wish to use:
Packages unique to an application Packages shared by closely linked applications
Packages shared more widely
Commercial packages Packages supplied as a standard part of Java
Packages so fundamental to Java that they are always neededThe package that we used in our earlier section may well be unique to one
application, or at most, be shared between a few closely linked applications.
In that circumstance, it is fine being located in a subdirectory of the
directory which includes the application. In other circumstances, though ...
with more widely shared.
The CLASSPATH environment variable (CLASSDIR in Java 1.0) is used to
tell Java where to look for the packages you call up -- specify a colon or
semicolon separated list.
Setting CLASSPATH is operating system (and shell) dependent. Here are
some examples:
Unix, C shell:setenv CLASSPATH.:/home/java/lib:/usr/local/lib/java
Unix, Bourne or korn shells:CLASSPATH=.:/home/java/lib:/usr/local/lib/java Windows 98, NT, 2000, XP, etc.:set CLASSPATH = .;c:\java\lib;c:\lib\javaAs you continue to learn about Java, you'll find that much of that learning is
about standard packages, and the classes and methods they contain. You
may well have already seen examples that include:
-
8/3/2019 Jawarlal Nehru College of Technology
27/57
import java.lang.Math;import java.lang.System;
Class Access:Private, public, protected.
Inner classes ."finalize" method. .
Private, public, protected:Recall that when we packaged up our packclass we had to declare theconstructors as public so that they could be accessed from our main method
in our default package? Class methods which are to be made available to
everyone must be declared public. Classes which are not declared as public(nor as private or protected) are available to any class in the same package.
Private classes are only available within the class in which they are defined.
They are very much internal methods that the author wants to make very
certain cannot be used directly from outside. Protected classes are available
to any class in the same package (just like the default), plus any subclasses.
They are not, however, available to any class as are public classes. In other
words, they are a "halfway house" between the default and
public. Its quite simple really
Inner classes:One class per source file can get a little long-winded and there might be
times you want to define a class purely for use from within another class.
This can be done with an inner class.1
Modifying (once again) our axford/card pack example, well add a class forindividual cards; a pack will now be made up from a number of card objects
rather than a number of simple integers. Well provide constructors andother methods for accessing cards, of course ...// Well House Consultants,20 04.
/** inner classes */public class luckington{public static void main(String[] args){System.out.println("Short pack, 24 cards removed");pack_5 my_pack = new pack_5(1,0,6);
-
8/3/2019 Jawarlal Nehru College of Technology
28/57
System.out.println(my_pack.ncards);my_pack.print();}}// Well House Consultants,20 04./** Card pack / Innner class card */public class pack_5{// Instance Variablescard [] cards;int ncards;// Constructorspack_5(int ndecks, int njokers, int shorten){
ncards = (((13 - shorten) * 4 ) * ndecks) + njokers;cards = new card [ncards];int n_at = 0;for (int k=0;k
-
8/3/2019 Jawarlal Nehru College of Technology
29/57
{private int value;// Constructorpublic card(int f_value){value = f_value;}// access datapublic int getcard(){return value;}}}
"finalize" method:Just as all instances that are going to be used are created, so all instances will
be destroyed and their resources released at some time before your Java
program exits.Instance variables which go "out of scope" for example, will
no longer be accessible and Java will release the memory for reuse. If you
want specific actions taken when the memory is recovered, you may supply
a finalize method. Lets add a finalize method into our pack_5class:// finalize methodprotected void finalize(){System.out.println("pack containing " +ncards + " cards released.");}
WARNING: you should not rely on the finalize method to performactions that are necessary as soon as an object is released. The Java Virtual
Machine will only get rid of objects when it needs to reuse the memory that
they are occupying.ExtendingClasses and MoreLearn how to implement inheritance inJava, and how Java handles Polymorphism. Java also provides theconcepts of abstract classes and interfaces,which are also covered by this module.
Extended classes .
-
8/3/2019 Jawarlal Nehru College of Technology
30/57
Abstract Classes .The universal superclass. .Interfaces .The final modifier
Extended classesI'm going to write a new class called "HireFilm", but rather than copy the
code from Film into it, I'm going to declare it to extend Film. Then all the
code of the Film class will be available in my HireFilm class, together with
any extras I provide. If there's something that I really don't want in the
original Film class when it's extended, I can override it in the extended class.
Some terminology: The class on which my new class is based (Film) is
called the BASE CLASS. The new class (HireFilm) which extends my base
class is called the SUBCLASS. You might have expected the subclass and
the base class to be one and the same as they're both "lower" or "down"words, but that's not the case. The subclass has that name because its
members are a subset of members of the base class.
Encapsulation:Once I've extended my class and I'm calling it from other classes, it's
transparent to me in terms of which methods are in which class. Here's the
application class:public class Hires {public static void main(String [] args) {// Set up a series of film objectsHireFilm Watch[] = new HireFilm[2];Watch[1] = new HireFilm("Road toPerdition",117,4.95F);Watch[0] = new HireFilm("The Truth about Cats andDogs",93,2.95F);for (int i=0; i
-
8/3/2019 Jawarlal Nehru College of Technology
31/57
}
Java Programming for the Web Extending Classes and More 5Chapter 2Figure 1 Running public class HiresYou might expect to find
getcalled,getcost
and
getcostperminutemethods in the HireFilmclass, but it turns out that's not the case:public class HireFilm extends Film {float cost;public HireFilm (String title, int length, floatpounds) {super (title,length);this.cost = pounds;}
public float getcost (int people) {return cost;}public float getcostperminute (int people) {return cost/minutes;}}
Where is getcalled? It must be inherited from the class Film... orperhaps from
some class that Filminherits from.public class Film {String called;int minutes;public Film (String title, int length) {called = title;minutes = length;}public int getminutes() {return minutes;
}public String getcalled() {return called;}public void setminutes(int length) {minutes = length;}
-
8/3/2019 Jawarlal Nehru College of Technology
32/57
}bash-2.04$ java HiresThe Truth about Cats and DogsCost is 2.95 value factor is 31.525425Road to PerditionCost is 4.95 value factor is 23.636366bash-2.04$
The super() call is an interesting one. You cannot inherit a constructorinto a subclass,1 but you really don't want to repeat the constructor in all
subclasses.
Abstract Classes:Now extend the application that gives value factors for films to include not
only hire films, but also purchased films and films seen at the cinema. If I
write each of the classes to include a getcost method and a
getcostperminute method, will that work? Yes, as far as it goes itwill. I'll be able call getcost on my cinema film and have it multiply myunitprice by the number of people who will be watching. But What I really
want is to have a whole array or films of various types, call methods on any
film and have Java select the right method depending on the type of film.With the class film as it stands I can't do this but I have another trick up my
sleeve.
If I declare Film to be an abstract class, and define methods which must be
in all my subclasses, I can achieve the desired result.
The universal superclass:If you define a class and don't tell Java that it extends anything at all, then
it's taken to extend the standard base class Object. Since you can nest
inheritance, this means that all your classes will inherit from Object, albeit
indirectly in many cases. Objectthe universal superclassincludes anumber of methods that might be of some use to you, and also a number of
methods which you'll want to override in some circumstances.
equals To see if two objects are the same objectclone To copy an objectgetClass To find the class of an object
-
8/3/2019 Jawarlal Nehru College of Technology
33/57
toString To return an object in string formThe clone method allows us to duplicate an object. In other words to takea copy of all its elements, resulting in a new object. This is a different
operation to just creating a new instance variable and copying an object
reference. If you modify a cloned object, you are not altering the original butif you modify an object that you've set up via a regular assignment from
another, you will be altering the original. Newcomers to Java often want to
find out what type of object is held in a variable, and they devour
getClass. But they're often wrong. If you get your design right, youshouldn't need to find out what type of object you have in this way as you
should be calling methods that have been defined as abstract to ensure that
your application chooses the correct code to run. In the base class object,
toString returns a simple text string describing your object (type ofobject and memory address), and equals tells you if two objects are oneand the same. Beware, these methods are often overridden even in standard
classes. For example
equals on a String compares the contents of the Stringequals on a File compares the file name and returns true if two objectspoint to the same disk file, even if via a different path
toString is intentionally designed to be overridden! If you callprintln on an object, it calls the toString method internally so thatthe object is described in the
best possible way.
Interfaces:In Java, every class inherits from exactly one other class, either a class you
define as being its base class, or from Object. In other languages such as
C++ and Perl, a class can be defined to inherit from more than one class.
Such multiple inheritance makes for a complex and slower language and is
rarely the best solution to requirements. It's quite common to have the
following conversation on a Java course:
Trainee:"Does Java have multiple inheritance?"
Tutor:"No. Why do you want it?"Trainee:"Because C++ has it."
Tutor:"But have you ever used it?"
You define the subclass in which the actual code resides as implementing an
interface, and you create a separate interface class to define what's
necessary. You can think of an interface as being similar to an abstract class
but:
-
8/3/2019 Jawarlal Nehru College of Technology
34/57
1. There is no code in an interface definition.
2. The syntax of an interface is different to that of an abstract class.
3. You can declare a class as implementing as many interfaces as you like
(and it will also extend one classObject or a class of your choice).
Example ... we'll define an insurable interfacepublic interface insurable {void setRisk(String What);String getRisk();}and two classes which implement that interface:public class Car implements insurable {String Risklevel;public Car() {Risklevel = "Third Party, fire and theft";
}public void setRisk(String Level) {Risklevel = Level;}public String getRisk() {return Risklevel;}}-------------------------------------------public class House implements insurable {
String Risklevel;public House() {Risklevel = "";}public void setRisk(String Level) {if (Risklevel.equals("")) {Risklevel = Level;else {Risklevel = Risklevel + "\n" + Level;
}}public String getRisk() {return Risklevel;}}
-
8/3/2019 Jawarlal Nehru College of Technology
35/57
You'll notice that we are allowed to declare an array to hold objects of type
insurable,
even though we can't create an object of that type. After all, we're looking at
an interface and not a class.bash-2.04$ java Ipayclass CarThird Party, fire and theftclass HouseSubsidenceFloodclass CarAny Named Driver
The final modifier:
A final modifier may be used to fix the value of a static member of a class. Itmay also be used to prevent any subclasses overriding a method you have
defined in your class. Whilst it is a good idea to use final modifiers as a
security check, they do not add functionality. Rather, they give rise to
compiler or run-time errors when another method attempts an illegal
override, or to modify a fixed value.
Java in the Web Page
Java programs run in JREs Java Runtime Environments. Thoseruntime environments may be traditional "keyboard to screen"applications, or they may run on servers, or within web clients(browsers). This module shows you how you can incorporate a javaclass (known as an Applet) within a web page, so that the methods ofthe class are run by the browser. Such applets are typically used toprovide intelligent forms and graphics.Structure overview.The methods you may and must provide. .Including Java in your page: HTML tags. .
The Abstract Windowing Toolkit .2Structure overviewThe Java programs which we have studied thus far on this course have all
been run from the command line using a command such as:java corshamIn other words, running the main method in the class corshamas anapplication, courtesy of the Java Virtual Machine supplied with the Java
-
8/3/2019 Jawarlal Nehru College of Technology
36/57
Development Kit. It is likely, though, that you want to use Java to add
interactive content to a web page. In which case youll not be using the
command line; youll want instead to run a Java applet. Lets look at thevarious component parts involved in creating a web page with the Java
applet.
Access to a web server / the site from which the pages will be downloaded Knowledge of how to create a web page using HTML (either directly or
indirectly) and how to load that page onto your web site
Knowledge of the Java language, and how to write Java applets
A Java compiler, although this need not be on the web server system.On this course, we provide a web server on which you can test your work.
A prerequisite of this part of the course is a knowledge of the mechanics of
the web and the ability to create your own page. If your knowledge is patchy
or rusty, your tutor will assist as his time allows.Web pages comprised of HyperText documents written using HTML tags
and pages which include Java applets are no different (apart, of course, from
the tags used!). Here is the HTML source for the page we showed at the start
of this section: A Page that contains an applet Demonstration of a Java AppletIf you are interested in learning about HTML andputting web sites together, ask your tutor
if you are interested in learning about the javaapplets and how to write them, you're on theright course!
The applet tag is a request to run the applet contained in the class boxin arectangular box, 300 x 300 pixels, at the given point in the text flow.
The methods you may and must provide:
-
8/3/2019 Jawarlal Nehru College of Technology
37/57
The main methods you may choose to override in the java.applet class (or its
superclasses) are:
init called when the applet is first loaded
start called when the applet becomes visible
paint called when the applet is to display itself
print called when the applet is to print itself
stop called when the applet becomes invisible
destroy called when the applet is unloaded2.3 Including Java in your page: HTML tagsWhere is an applet placed within a document?
At the location dictated by theandpair of tags!Within the applet tag itself, you will for certain have the following attribute
set:
CODE
which actually tells the browser the URL of the Class file containing theapplet executable.
It is very likely that you will have:
HEIGHT and WIDTH which specify the height and width (in pixels) of the
display area to be used by the applet.
Other attributes you might have in Java, and which will be familiar to
HTML programmers, include: ALIGN, ALT, HSPACE and VSPACE.1
Also in use is CODEBASE, which is rather like a BASE tag, but affects only
the location of applet code.
Also be aware of these new attributes used in Java:ARCHIVE -- which lets you specify that the Java Class downloaded is to be
archived on your local client system -- the suffix of the given file name
indicating whether you are going to use a .zipfile or a .jar(Java archive)file, up and coming, and with extra security features like digital signatures!
ARCHIVE tags -- which are supported only on Netscape at the moment, can
give enormous savings in download time if you use the same applet in
session after session.
MAYSCRIPT -- necessary if the Java applet is to access JavaScriptfeatureswithin the browser.
NAME -- lets you provide unique names for each instance of an applet inyour page. Useful if you have two copies of the same applet running at the
same time, and other applets need to know which to talk to!
TITLE -- used by Internet Explorer when it wants to provide a title for the
applet!!
We have consideredand.Why are there two tags? What can possibly go between them?
-
8/3/2019 Jawarlal Nehru College of Technology
38/57
First, any plain text which occurs between the tags will be ignored by Java-
knowledgable browsers, but will be displayed by browsers which do not
know of Java.
Sample of HTML code
And what is displayed? The result of running the applet graph.class, youhope, except ...
A message to say that the class cannot be accessed if that is the case ... or A
message to tell you that your browser does not know about Java, if that is the
case! Hang on a minute.
Your Browser does not know about Java.
If Java were available, a graph of the share pricewould beThe Abstract Windowing Toolkit
Whats actually new in terms of the Java language in our applet?
Nothing really. Were just providing a number of methods which extend the
java.applet.Appletclass.And yet the class file does look different, mainly because our first (and
simple) example is not doing any great calculations and is comprised almost
entirely of calls to methods that we havent yet met, in classes that are still
new to us! Instead of using System.out.print and other methods that welllearn about before the end of this course, applets produce their graphics
through the Abstract Windowing Toolkit, a big topic which well see indetail on the Java Advancedcourse.
ExceptionsYour program is affected by the environment around it. Itsperformance will vary depending on aspects as diverse as user inputsand the availability of a network service. Java provides you withexceptions, which are a mechanism through which you trap and
handle behaviours that differ from the norm."trying" and "catching" ."throwing" ."finally".Defining your own exceptions .
"trying" and "catching"
-
8/3/2019 Jawarlal Nehru College of Technology
39/57
Before we describe how exceptions work, we should make it clear that they
are a vital part of the Java language and not a mechanism to catch sloppy
programming. The example we are working with could easily be corrected
by resizing an array, but many times exceptions are thrown for
reasons outside the control of the Java programmer: A user types in the word "three" when asked for a number
A program attempts to open a data file in a directory which the user cannotread In practice, the exception mechanism is so much better than adding
"hundreds" ofchecks to your program that youll even end up throwing yourown exceptions.
A card cannot be described as "the n of xxx" -- oops -- an exception. The
exception will be caught by the special code that deals with theJoker! So you think that something might not work in a block of code. For
example, you are concerned about trying to hold too many cards in your
hand. You will try to pick up a card from the deck, but if there isnt roomin your hand,an exception will be thrown. You will catch theexception with a piece ofcode written to handle it. Lets do that withthe example we started with.
Here is the original (failing) code:// Well House Consultants,20 04./** Array too short - shows problem */public class wadswick{public static void main(String[] args){
System.out.println("Short pack of 20 cards");System.out.println("And a set of cluedo suspect cards!");card_7 [] play = new card_7 [15] ;int cardcount = 0;for (int k=0;k
-
8/3/2019 Jawarlal Nehru College of Technology
40/57
ArrayIndexOutOfBoundsExceptionAnd in this case we could have written our catch block with any of thosedeclared as the parameter. We looked for a single specific exception in our
first example but we could easily look for several by adding extra catch
blocks, and/or by catching exceptions at a higher level in the hierarchy.If you have several catch blocks, the order is important. It is pointless tocode:try{}catch (Exception e){}catch (RuntimeException e)
{}since the first catch block always catches all exceptions (includingRuntime exceptions).
"throwing"
There will be occasions when you want your method to pass back the fact
that it encountered a problem, perhaps by passing back the exception. If you
specify that a method can throw one or more exceptions, and then take noaction to handle those exceptions within the method, the exceptions will be
passed back to the calling method for it to deal with.
As an example, lets add a getsuitnamemethod to our playing_cardclass:public String getsuitname()throws ArrayIndexOutOfBoundsException{int suit = (value-1) % 4;if (value < 1) suit = -1;String [] suites = { "Clubs","Diamonds",
"Hearts","Spades"};return suites[suit];}and notice how this new method is specified as throwing anArrayIndexOutOfBoundsException.
// And print out cards!
-
8/3/2019 Jawarlal Nehru College of Technology
41/57
for (int k=0;k
-
8/3/2019 Jawarlal Nehru College of Technology
42/57
System.out.print("Problem finding suit");if (++probcount > 1) return;}finally{System.out.print(".\n");}}}
Defining your own exceptions:You can define your own exceptions and exception classes if you wish.
Indeed, that would have been a good idea in our suit example rather than for
us to take over one of the built-in exceptions classes! As all exceptions arederived from a "throwable" base class, a number of methods are available to
you, including:getMessage() which returns the message describing the currentexceptionprintStackTrace() which outputs to standard error thestack trace where the error message was generated And remember that these
methods are available on standard exceptions, your own exceptions, and any
exceptions provided by other classes you have elected to use.
More Input and Output:
Writing to a file. .Reading from a file.
Streams:A similar logic can be followed through for an input stream But streams do
not apply to:
Graphics / windows output
Input relating to the graphics (mouse movements, etc)
Youll be introduced to the classes we use to handle graphics section of thiscourse, and learn a lot more about them on the There are, in fact, two types
of stream Classes available in
byte streams. Used for handling data accessed by stream character streams. Used for handling data accessed by other stream.
For character streams, we use:
-
8/3/2019 Jawarlal Nehru College of Technology
43/57
OutputStream for writing
InputStream for reading
but both are abstract classes, declaring a basic set of operations
streams, and so cannot be instantised directly.
Similarly, for byte streams we use:
Writer for writing
Reader for reading
both of which (again) are abstract classes.
Writing to a fileThe final type of class youll need will be the File class which (you canguess!) holds information about and provides methods to check andaccess files.Well come back to File objects soon, but lets start with a short
example of writing to a file using a byte stream.Example broughton.java. Same as whitley.java except ...
// And print out cards!FileWriter demofile = new FileWriter("abc.123");for (int k=0;k
-
8/3/2019 Jawarlal Nehru College of Technology
44/57
The fundamental packagesjava.langjava.lang contains the classes that are most central to the languageitself; it's a broad rather than a deep hierarchy, which means that there's a lot
of classes in the package, but they tend to be independent of one another.Firstly, java.lang contains the data wrapper classesimmutable classwrappers around the primitive types which allow you to treat primitives as if
they're objects.1 Strings and StringBuffers are a part ofjava.lang, as arethe Math (and from Java 1.3 StrictMath) classes. All of these classes (except
StringBuffer) implement the Comparable interface, which provides sorting
and searching capabilities. System, Runtime and Process classes provide
low-level methods and an API for performing low-level system functions
and running external processes. java.lang also includes the Threadclass, and Throwables and exception handling; these are major topics (along
with Strings and StringBuffers).java.utilOne of the fundamental packagesthat you'll use in all but the very simplest of Java applications is the java
utility package java.util has been with us since the beginning of Java;it was one of the eight original packages in Java release 1.0. There have been
a number of additions for Java2, and some of those additions have
superseded older objects for certain applications. The utilities in
java.util provide the more complex programming structures that you'llwant to use in any professionally written classes, but aren't in the basic
language. The majority of utility classes are concerned with collections,2 but
the package also includes classes for date and time work, resource bundlehandling, parsing a string (StringTokenizer) and the Timer API that was
introduced at Java 1.3. Java.util also includes sub-packages
java.util.jar and java.util.zip.
Other fundamental packages:The following packages might also be considered to be fundamental in
certainapplications:java.io Classes and interfaces for input and output
java.math Packages for arbitrary precision arithmetic(do NOT confuse with java.lang.Math ;-) )java.net Network access and programming
Data wrappers:What's the difference between a primitive and an object? A primitive is a
variable into which you can save an information of one of eight pre-defined
-
8/3/2019 Jawarlal Nehru College of Technology
45/57
types directly, whereas an object is held in a variable which is a reference1
to a piece or a number of pieces of information. Primitives are accessed
directly through basic facilities provided in Java, whereas objects are
accessed through the object interface. Here's a teaching example that copies
and compares primitives and objects, showing you how their behaviour
differs:public class Obj_v_prim {// Object v Primitive - a comparison examplepublic static void main (String [] args) {float sample = 16.5f;Float Sam2 = new Float(16.5f);System.out.println("Primitive is "+sample);System.out.println("Object is "+Sam2);// copy and compare - appreciate the difference!
float sam_copy = sample;Float Sam2_copy = Sam2;float another = 16.5f;Float Another2 = new Float(16.5f);System.out.println("\nDoing == comparisons");if (sample == sam_copy) {System.out.println("sample and sam_copy areequal");} else {System.out.println("sample and sam_copy differ");
}if (sample == another) {System.out.println("sample and another are equal");} else {System.out.println("sample and another differ");}if (Sam2 == Sam2_copy) {System.out.println("Sam2 and Sam2_copy are equal");} else {
System.out.println("Sam2 and Sam2_copy differ");}if (Sam2 == Another2) {System.out.println("Sam2 and Another2 are equal");} else {1System.out.println("Sam2 and Another2 differ");
-
8/3/2019 Jawarlal Nehru College of Technology
46/57
}System.out.println("\nDoing \".equals\"comparisons");if (Sam2.equals(Sam2_copy)) {System.out.println("Sam2 and Sam2_copy are equal");} else {System.out.println("Sam2 and Sam2_copy differ");}if (Sam2.equals(Another2)) {System.out.println("Sam2 and Another2 are equal");} else {System.out.println("Sam2 and Another2 differ");}}
}This test code starts off by defining a primitive float and an object oftype
Float:1float sample = 16.5f;Float Sam2 = new Float(16.5f);The text program then prints out the values of the variables:System.out.println("Primitive is "+sample);System.out.println("Object is "+Sam2);
Utility objects to hold multiple simple objects:If you want to hold a number of objects in a single composite object, we call
it acollection. The Java language itself (without any additional classes)
supports arrays, which can hold primitives or objects. The java.utilpackage adds a whole further series of classes which can be used to hold
multiple objects in various arrangements and with various facilities. Before
we go on to look at these various collection classes, do note one important
limitationthey hold multiple OBJECTS; if you want to hold multiple
primitives in a collection, you need to use the data type wrappers that we
looked at earlier in this module. The first collection objects we look attheVector, Stack and Hashtable (and the enumeration interface)have beenavailable from the beginnings of Java. A complete Collection framework
was added at Java 1.2; we'll look at those after we've had a brief look at the
older classes.
-
8/3/2019 Jawarlal Nehru College of Technology
47/57
The StringTokenizer:There's often a requirement to split down a string into its component
elements, or tokens, such as splitting a sentence into words or a line of
data into fields. You could roll your own class and methods, but better to use
the StringTokenizer class. The simplest way to use aStringTokenizer is to construct one to parse a string (passed as aparameter to the constructor), then use enumeration methods to handle the
individual tokens.$ java Strtok1: This2: is3: a4: string
5: that6: we7: want8: to9: tokenize$
Sorting:If you try to make practical use of the previous examples, you'll discover
that you really want your output sorted. If there are two or three records to
be listed out, then the order doesn't really matter, but many more and sorting
becomes vital.
Basic sorting in Java:Prior to Java 1.2, if you wanted to sort you had to "roll your own. Notparticularly hard, but sometimes long-winded and you would have had a lot
of work to do if you wanted to write an efficient sort routine.
In Java 1.2,Arrays.sort and Collections.sort1 will sort yourcomposite objects.
Let's sort the hosts from our HashMap example. We've chosen somethingslightly awkward to sort, as HashMaps can't be sorted, so we've got a Set of
keys out from it. Now, a Set object can't be sorted either (for a class to be
sort-able, all the elements need to be in memory; alas, that doesn't happen
with a Set), so we have to put all the elements into... well, we chose a
Vector. At last - something we can sort!import java.util.*;
-
8/3/2019 Jawarlal Nehru College of Technology
48/57
import java.io.*;public class Hmapsort {public static void main(String [] args) throwsIOException {BufferedReader Source = new BufferedReader(new FileReader( args[0]));HashMap HostCount = new HashMap();String Line;while ((Line = Source.readLine()) != null) {String Host = (new Access(Line)).Host;1 those are static methods that can be used on arrays and some utility classes
that are collections.
Servlets:Web applications in Java can be provided by Servlet classes runningin a container on a web server. In this module, you'll learn how towrite simple servlets that allow web users (whether or not they haveJava in their browser) to interact with your Java applications. applications a main method run using a virtual machine such as "java"
from JDK typically inputting from STDIN (keyboard) and output to screen
each application is a class in its own right.
applets extends java.applet.Applet methods such as init, startandpaint run on the web on a client system by the browser typicallyinteracting using the AWT (abstract windowing toolkit).
Applets are ideal for client-side operations, such as dynamic graphing, local
calculations, etc. An applet can contact the server from which it was
downloaded but this does not provide a clean solution for core server-side
applications. If you wish to complete a form on a web page1 and run a Java
program on your server when you press the "Submit" button, you can do so
using a servlet.
Servlets are run on server systems. Certain web servers run them, or they can
be run on a separate program (on a different port to the main server) using
the servletrunner program supplied with the JSDK (Java ServletDevelopment Kit).
Running the serverThe server must be running and accepting connectionsbefore the client application calls for the service. Here's an example of how
we start servletrunner whichyou might like to use as a test:
-
8/3/2019 Jawarlal Nehru College of Technology
49/57
Extending Graphics in Java:The original graphics classes of Java the AWT providefunctionality at a very low level. A lot of coding effort is required toprovide even a simple GUI. The Swing classes are built on top of theAWT and largely supplant it; they provide much higher levelcomponents so that you can rapidly bolt together the look, feel andfunctionallity for a graphic-driven application.Simple Swing.More Complex Swing.
Simple Swing:Hello Swing World
Here's the simplest stand-alone Swing application:import javax.swing.*;public class Swtiny extends JPanel {// Swing main programpublic static void main (String [] args) {JFrame frame = new JFrame ("Tiny, Stand alone");JLabel jl = new JLabel("A Tiny Example");frame.getContentPane().add(jl);
With a flow layout, the components are placed one after another along the
top of the pane. When the right-hand side is reached (which hasn't happened
in this case), a second row is started, and so on. Rather than specify a
window size as we did in the earlier example that wasn't using a layout
manager, we've now left the pack method to arrange the components,which in turn allows the size of the window to be calculated.
Advantage: The window isn't going to be too small, nor have spurious white
space.
Important to note: If an object starts with a capital J, then it's a
Swing object, and if it starts with any other letter it's in the awt.You'll note that getContentPane returns a Container object. This is anunderlying AWT object; the rule is that if an object starts with a capital J,
then it's a Swing object, and if it starts with any other letter it's in the awt.
You will need to know which are which:
To know where to look in the reference material
To know what you need to import
-
8/3/2019 Jawarlal Nehru College of Technology
50/57
To know whether your class is useable in old browsers without the Javaplugin,Let's use another layout manager (a grid layout) in order to set up a
series of buttons like a telephone keypad:import java.awt.*;import javax.swing.*;public class S2 extends JFrame {public static void main (String [] args) {new S2().setVisible(true);}public S2 () {Container cp = getContentPane();cp.setLayout(new GridLayout(4,3));String [] Phone = {"7","8","9","4","5","6","1","2","3","*","0","#"};
for (int i=0;i
-
8/3/2019 Jawarlal Nehru College of Technology
51/57
import java.awt.event.*;class winEvent extends WindowAdapter {public void windowClosing(WindowEvent e) {System.exit(0);}}
Notice that our main program defines our GUI, then defines a number (one!)
of things to be done when an event happens, then appears to "fade out".
Because we've extended a Swing class, the application is left in a listener
loop. It's waiting for an event to happen, and acting on that event when it
gets it.
As well aswindowClosing, we can provide methods such aswindowActi
You might like to note that we had to make the following changes to ourstandalone GUI application to change it into an Applet:
1.main was removed, and init added2. It now extends JApplet rather than JFrame3.pack was removed4. The size of the window is now taken from the HTML rather than from the
size that's needed to hold the components (beware, you may find unwanted
white space, or compressed or overlapping parts of your GUI if you don't
think this one through properly).
5. System.out.println and System.exit were removed. Youcan't print to the user's display, nor can you exit from a browser. Chances are
that results would be passed back via your network to the host from which
the applet was loaded.What if you want to use the same class as both a
stand-alone application and within a browser? That's quite feasible; you
provide both main and init methods.Note whether you're running an applet or not (a good use for a boolean).
You can then put in small adjustments as necessary to cover the points that
we listed as changes above.
Note: We have modified this Dialler example to use a BorderLayout fortheouter frame; this was not a necessary change as we moved across to an
applet. It's done to provide you with an example of a different layout to the
GridLayout.
2.2 More Complex Swing
-
8/3/2019 Jawarlal Nehru College of Technology
52/57
Swing provides you with a huge selection of components that you can use in
your GUI, each with a very wide range of properties and methods available.
The JComponentabstract class is subclassed (directly or indirectly) to ...
JButton
Java Programming for the Web Extending Graphics in JavaJMenuItemJCheckBoxMenuItemJMenuJRadioButtonMenuItemJToggleButtonJCheckBoxJRadioButton
JColorChooserJComboBoxJFileChooserJInternalFrameJLabelJLayeredPaneJDesktopPaneJToolTipJMenuBarJOptionPaneJPanelJPopupMenuJProgressBarJRootPaneJScrollBarJScrollPaneJSeparatorJSliderJSplitPane
JTabbedPaneJTableJToolBarJListJTreeJViewport
-
8/3/2019 Jawarlal Nehru College of Technology
53/57
We'll choose just two of these for a further look in this module; you'll very
much get the idea from these components, and then be able to make good
use of the others from documentation and books available elsewhere (have a
look at our library listed in the back of this manual; we have complete books
on Swing).
JDBCRelational Database Access:Java accesses relational databases, such as Oracle and MySQL,through JDBC classes. A manager class which oversees the processis provided with the Java distribution, but you'll also need to obtain adriver class to talk to the specific database of your choice. UsingMySQL as an example, this module takes you through the sourcing,configuration and use of JDBC so that you can access data in a
relational database from within your Java application. Prerequisites:In order to make the most of this module, trainees need priorknowledge of Java to an intermediate level and a little priorknowledge of SQL.Interfacing MySQL to Java. .Using JDBC to access other databases .Using JDBC on the Web .connectivity to relational databases has been provided through JDBC (Java
Database Connectivity) in the java.sql package. Note that the Java
distribution does not include a full relational database package, nor even the
Java classes to access any particular database, which you will need to obtain
and install in addition to your J2SE in order to have a Java front-ended
relational database. JDBC drivers are not necessarily available for all
databases.
They are available from various vendors for commercial databases such as
Access and Oracle.
Free or inexpensive databases such as PostgreSQL have limited driversavailable at Basic Techniques:
Register the database driver
Obtain a Connection object Use a Statement object to send a statement
Retrieve the results in a ResultSet objectThese basic techniques (and thejava.sql package as a whole) are mostly
interfaces rather than classes.
-
8/3/2019 Jawarlal Nehru College of Technology
54/57
The DriverManager class (a true class, this one!) is responsible formanaging all the classes available and providing the appropriate one for you.
The Class.forName method will register with the DriverManagerfor you.
DriverManager.getConnection will obtain the connection objectfor you; we use a URL of the form:jdbc:subprotocol://host:port/databaseIn a web environment, youll note that the JDBC connection is made from
the client using a TCP service and sockets. It follows that the specific driver
class needs to be available to the browser and the security aspects of
distributing that driver need to be considered.
The getConnection() method takes a user name and password asparameters.
You should consider carefully where you obtain and store this information.
createStatement() does exactly thatit creates an object with whichyou can submit queries using either the executeQuery() method or foran update the executeUpdate() method.Queries are formed and sent in SQL (Structured Query Language).
Finally, the getResultSet() method retrieves an object of typeResultSet.As ever, get methods allow you to collect data row-by-row or column-by-column.
As well as querying and updating data, facilities are available to learn about
the structure of the database.This is known as MetaData; the DatabaseMetaData interface allowsyou to retrievethisinformationusingthe getMetaData methodoftheConnection class.Most database accesses will be either to obtain data or to update data, but
you can go so far as using SQL CREATE TABLE statements to add tablesand structure to your database (i.e. you have both the DDL and the DML
elements available).
Although most queries are handled as one-offs, each query being committed
to the Client Server,Security,SQLdatabase as it is sent, you are able to send queries in sections, for example,
atomic transactions which are combined when you commit().
Interfacing MySQL to Java:
-
8/3/2019 Jawarlal Nehru College of Technology
55/57
Java interfaces to databases through JDBC (Java Database Connectivity).
Your Java Runtime Environment should include thejava.sqlpackage bydefault, which is basically a driver manager class and does not include any
drivers for any specific databases. You then source appropriate drivers from
elsewhere; there's a list of suitable drivers on Sun's site:
http://industry.java.sun.com/products/jdbc/driverswhich currently lists almost 200 drivers, including several for MySQL.
In addition, you could interface MySQL to Java using the JDBC to ODBC
bridge but ... don't; you'll be adding in an extra layer of conversions, and the
drivers listed on the site above are all "type 4" drivers which means that
they're written in native Java code. Here is a complete working example,
using drivers sourced via this web site.public class jdbc1 {public static void main(String [] args) {
java.sql.Connection conn = null;System.out.println("SQL Test");try {Class.forName("org.gjt.mm.mysql.Driver").newInstance();conn = java.sql.DriverManager.getConnection("jdbc:mysql://bhajee/test?user=jtest&password=");}catch (Exception e) {System.out.println(e);System.exit(0);}System.out.println("Connection established");try {java.sql.Statement s = conn.createStatement();java.sql.ResultSet r = s.executeQuery("SELECT code, latitude, longitude FROM dist");while(r.next()) {System.out.println (
r.getString("code") + " " +r.getString("latitude") + " " +r.getString("longitude") );}}catch (Exception e) {System.out.println(e);
-
8/3/2019 Jawarlal Nehru College of Technology
56/57
System.exit(0);}}}
JDBC (JAVA Database Connectivity):
We've chosen MySQL as our example database for this section since we run
it on our training machines, but just to show you how portable the code is,
here's an example that uses the Oracle database:package mypackage1;import java.sql.*;import java.util.*;
public class Bruce09{public Bruce09(){}public static void main(String[] args){Connection conn = null;System.out.println("SQL Test");try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());}catch (Exception e) {System.out.println(e);System.exit(0);
Using JDBC on the WebThese days, most users want to access data (including data held in their
relational databases) from a browser, and Java provides you with tools to
facilitate this.
For example:
-
8/3/2019 Jawarlal Nehru College of Technology
57/57
Data is held in a relational database (such as MySQL), which is managedby an appropriate database engine (such as mysqld).
A Java Class, using JDBC drivers, interfaces to the database engineallowing data to be transferred between that class and the database
The Java class is then referenced by another class which extend the Servletinterface
The Servlet is accessed by Tomcat, which provides the JRE conforming tothe Servlet specification
The Apache Web Server uses Tomcat to.
-----------------------------------------------------------------------------------