Tuesday, May 17, 2011

DAD CATCHES DAUGHTERS ON WEBCAM - Beware Facebook Viral Scam

As Facebook is one of the most widely used social networking website around, It is being hit by lots of viral scams, Today I just came across one of those viral scams when one of my friend on facebook shared a link on his wall, "[VIDEO] DAD CATCHES DAUGHTERS ON WEBCAM [OMGGGG].AVI", The title of the link looked suspicious to me so i thought to figure out exactly what was going around.



[VIDEO] DAD CATCHES DAUGHTERS ON WEBCAM [OMGGGG].AVI[LINK]two naughty girls get caught in the WORST moment while making a vid on their webcam! omg!!
When I clicked on it, I was redirected to a page where I was asked to click a button to play the video, The moment I saw it I noticed that it was a flash file and was not a real video.


This was just to fool the users and making them download the adobe flash plugin in order to play the video, Once I clicked on the button "Download Codec", A file named Freecodec.exe started to download, which made me think if it's a keylogger or a trojan but the file happened to be clean according to the "No virus thanks 32 Scanner".

Ultimately I was redirected to a webpage which was promoting a tool called Profile Stylez and the Freecodec.exe was the installation file for the Profile Stylez tool.



After viewing the source code of the page I found the following line of code which was responsible for spreading the link to your facebook wall, Any one with the basic knowledge of Html and IFrame would certainly know what this code is exactly doing, Here we actually discover a vulnerability in like.php code which abuses users trust for viral spreading of the links.

<iframe allowtransparency="true" frameborder="0" scrolling="no" src="http://www.facebook.com/plugins/like.php?href=www.blackinfopages.com%2Fi?4dcef0f134a10&amp;send=true&amp;layout=standard&amp;width=450&amp;show_faces=true&amp;action=like&amp;colorscheme=light&amp;font&amp;height=80" style="border: none; height: 80px; overflow: hidden; width: 450px;"></iframe>
Lastly I scanned the file Freecodec.exe on http://www.virustotal.com as I was a bit unsatisfied Novirusthanks due to my experience in past and guess what Symantec antivirus and VBA32 recognized it as a Trojan.Dropper.



Master Plan

So according to me the master plan was actually promote the tool and at the same time install malware in to victims computer and control their computers at the same time.

Security Measures

  • Avoid clicking on those posts titles which have words such as "OMG, WOW, DAMN" they are most likely to do the same thing
  • Always install any kind of Plugins and codecs from the official website, You might be installing malware along with the plugin.
  • Always scan a file with an online virus scanner such as virustotal before running it on your own computer.
Hope you have liked my post and I hope in you won't fall for these scams in your near future, If you want to reproduce this article, make sure you give the credit to the original author and the website.

Monday, May 9, 2011

The.Hit.List.2011.BluRay.720p.DTS.x264[暗杀名单]

http://www.filefactory.com/file/cb3a924/n/The.Hit.List.2011.BluRay.720p.DTS.x264[������������]_7E66E46D78.rmvb.001
http://www.filefactory.com/file/cb3a9d3/n/The.Hit.List.2011.BluRay.720p.DTS.x264[������������]_7E66E46D78.rmvb.002
http://www.filefactory.com/file/cb3a949/n/The.Hit.List.2011.BluRay.720p.DTS.x264[������������]_7E66E46D78.rmvb.003

Sniper.Reloaded.2010.BluRay.720p.DTS.x264[狙击精英.重装上阵]

http://www.filefactory.com/file/cb3a8e2/n/Sniper.Reloaded.2010.BluRay.720p.DTS.x264[������������.������������]_1F12046DDF.rmvb.001
http://www.filefactory.com/file/cb3a883/n/Sniper.Reloaded.2010.BluRay.720p.DTS.x264[������������.������������]_1F12046DDF.rmvb.002
http://www.filefactory.com/file/cb3a773/n/Sniper.Reloaded.2010.BluRay.720p.DTS.x264[������������.������������]_1F12046DDF.rmvb.003

Season.of.the.witch.2010.720p[女巫季节]_

http://www.filefactory.com/file/cb3a7d6/n/Season.of.the.witch.2010.720p[������������]_7CC03DB85D.rmvb.001
http://www.filefactory.com/file/cb3a606/n/Season.of.the.witch.2010.720p[������������]_7CC03DB85D.rmvb.002
http://www.filefactory.com/file/cb3a5e0/n/Season.of.the.witch.2010.720p[������������]_7CC03DB85D.rmvb.003

Monsters.2010.Blu-ray.RE.X264.720.DTS.MySilu[异兽禁区]

http://www.filefactory.com/file/cce177c/n/Monsters.2010.Blu-ray.RE.X264.720.DTS.MySilu[������������]_7B047993C8.rmvb.001
http://www.filefactory.com/file/c45e9bc/n/Monsters.2010.Blu-ray.RE.X264.720.DTS.MySilu[������������]_7B047993C8.rmvb.002
http://www.filefactory.com/file/cb3a37c/n/Monsters.2010.Blu-ray.RE.X264.720.DTS.MySilu[������������]_7B047993C8.rmvb.003

The.Haunting.2009.PROPER.DVDRip.XviD[鬼迷心窍]

http://www.filefactory.com/file/cb3a187/n/The.Haunting.2009.PROPER.DVDRip.XviD[������������]_D40C9C8D19.rmvb.001
http://www.filefactory.com/file/cb3a199/n/The.Haunting.2009.PROPER.DVDRip.XviD[������������]_D40C9C8D19.rmvb.002

My.Darling.is.a.Foreigner.2010.BD.x264.720p.DTS[达令是外国人]



http://www.filefactory.com/file/c1e36a0/n/My.Darling.is.a.Foreigner.2010.BD.x264.720p.DTS[������������������]_FF13912C83.rmvb.001
http://www.filefactory.com/file/cb3a1d5/n/My.Darling.is.a.Foreigner.2010.BD.x264.720p.DTS[������������������]_FF13912C83.rmvb.002
http://www.filefactory.com/file/cb3a179/n/My.Darling.is.a.Foreigner.2010.BD.x264.720p.DTS[������������������]_FF13912C83.rmvb.003

And.Soon.the.Darkness.2010.BluRay.a720.x264.DD51[黑暗来临]

http://www.filefactory.com/file/cb3a0b2/n/And.Soon.the.Darkness.2010.BluRay.a720.x264.DD51[������������]_3B38FD22E6.rmvb.001
http://www.filefactory.com/file/cb3a0bd/n/And.Soon.the.Darkness.2010.BluRay.a720.x264.DD51[������������]_3B38FD22E6.rmvb.002
http://www.filefactory.com/file/cc71246/n/And.Soon.the.Darkness.2010.BluRay.a720.x264.DD51[������������]_3B38FD22E6.rmvb.003

Sunday, May 8, 2011

Battle.Los.Angeles.2011.R5.XViD[洛杉矶之战]

http://www.filefactory.com/file/cb25eba/n/Battle.Los.Angeles.2011.R5.XViD[���������������]_342D28FA1A.rmvb.001
http://www.filefactory.com/file/cb25ebb/n/Battle.Los.Angeles.2011.R5.XViD[���������������]_342D28FA1A.rmvb.002
http://www.filefactory.com/file/cb25ef4/n/Battle.Los.Angeles.2011.R5.XViD[���������������]_342D28FA1A.rmvb.003

The.Lost.Future.2010.720p.BluRay.x264[失落的未来]

http://www.filefactory.com/file/cb25d9a/n/The.Lost.Future.2010.720p.BluRay.x264[���������������]_5F47A80D40.rmvb.001
http://www.filefactory.com/file/cb25d52/n/The.Lost.Future.2010.720p.BluRay.x264[���������������]_5F47A80D40.rmvb.002
http://www.filefactory.com/file/cb25d21/n/The.Lost.Future.2010.720p.BluRay.x264[���������������]_5F47A80D40.rmvb.003

Tron.Legacy.2010.BluRay.720p.x264.DTS-MySiLU[创战纪]

http://www.filefactory.com/file/cb25c8c/n/Tron.Legacy.2010.BluRay.720p.x264.DTS-MySiLU[���������]_A761F7290D.rmvb.001
http://www.filefactory.com/file/cb25c56/n/Tron.Legacy.2010.BluRay.720p.x264.DTS-MySiLU[���������]_A761F7290D.rmvb.002
http://www.filefactory.com/file/cb25c50/n/Tron.Legacy.2010.BluRay.720p.x264.DTS-MySiLU[���������]_A761F7290D.rmvb.003
http://www.filefactory.com/file/cb25ddf/n/Tron.Legacy.2010.BluRay.720p.x264.DTS-MySiLU[���������]_A761F7290D.rmvb.004

Mr.3.Minutes.2006.BluRay.720p.AC3.HK.x264[3分钟先生]

http://www.filefactory.com/file/cb25b9c/n/Mr.3.Minutes.2006.BluRay.720p.AC3.HK.x264[3������������]_2362046CBE.rmvb.001
http://www.filefactory.com/file/cb25bda/n/Mr.3.Minutes.2006.BluRay.720p.AC3.HK.x264[3������������]_2362046CBE.rmvb.002
http://www.filefactory.com/file/cb25b00/n/Mr.3.Minutes.2006.BluRay.720p.AC3.HK.x264[3������������]_2362046CBE.rmvb.003
http://www.filefactory.com/file/cb25a57/n/Mr.3.Minutes.2006.BluRay.720p.AC3.HK.x264[3������������]_2362046CBE.rmvb.004

Ladyhawke.1985.BluRay.720p.x264.DTS[鹰狼传奇]

http://www.filefactory.com/file/cb249e2/n/Ladyhawke.1985.BluRay.720p.x264.DTS[������������]_4312C4DBDD.rmvb.001
http://www.filefactory.com/file/cb24992/n/Ladyhawke.1985.BluRay.720p.x264.DTS[������������]_4312C4DBDD.rmvb.002
http://www.filefactory.com/file/cb24949/n/Ladyhawke.1985.BluRay.720p.x264.DTS[������������]_4312C4DBDD.rmvb.003
http://www.filefactory.com/file/cb249e0/n/Ladyhawke.1985.BluRay.720p.x264.DTS[������������]_4312C4DBDD.rmvb.004

London.Boulevard.2010.720p.BluRay.X264[伦敦大道]_0C6688715F

http://www.filefactory.com/file/cb248a8/n/London.Boulevard.2010.720p.BluRay.X264[������������]_0C6688715F.rmvb.001
http://www.filefactory.com/file/cb248a5/n/London.Boulevard.2010.720p.BluRay.X264[������������]_0C6688715F.rmvb.002
http://www.filefactory.com/file/cb24849/n/London.Boulevard.2010.720p.BluRay.X264[������������]_0C6688715F.rmvb.003

Just.Go.With.It.2011.R5.LiNE.XviD[爱情大临演]

http://www.filefactory.com/file/cb24715/n/Just.Go.With.It.2011.R5.LiNE.XviD[���������������]_5B24F2E11E.rmvb.001
http://www.filefactory.com/file/cb2470f/n/Just.Go.With.It.2011.R5.LiNE.XviD[���������������]_5B24F2E11E.rmvb.002
http://www.filefactory.com/file/cb247bf/n/Just.Go.With.It.2011.R5.LiNE.XviD[���������������]_5B24F2E11E.rmvb.003

3D肉蒲团之极乐宝鉴_3D.Sex.and.Zen.Extreme.Ecstasy_2011

http://www.filefactory.com/file/cb246de/n/3D������������������������_3D.Sex.and.Zen.Extreme.Ecstasy_2011_TS_3A71EA08CB.rmvb.001
http://www.filefactory.com/file/cb246a6/n/3D������������������������_3D.Sex.and.Zen.Extreme.Ecstasy_2011_TS_3A71EA08CB.rmvb.002
http://www.filefactory.com/file/cb24541/n/3D������������������������_3D.Sex.and.Zen.Extreme.Ecstasy_2011_TS_3A71EA08CB.rmvb.003

Saturday, May 7, 2011

Robo.2010.Bluray.720p.DTS.x264-CHD[宝莱坞机器人之恋]

http://www.filefactory.com/file/cb2439b/n/Robo.2010.Bluray.720p.DTS.x264-CHD[������������������������]_2F3802736A.rmvb.001
http://www.filefactory.com/file/cb24379/n/Robo.2010.Bluray.720p.DTS.x264-CHD[������������������������]_2F3802736A.rmvb.002
http://www.filefactory.com/file/cb24378/n/Robo.2010.Bluray.720p.DTS.x264-CHD[������������������������]_2F3802736A.rmvb.003
http://www.filefactory.com/file/cb244ee/n/Robo.2010.Bluray.720p.DTS.x264-CHD[������������������������]_2F3802736A.rmvb.004
http://www.filefactory.com/file/cb24484/n/Robo.2010.Bluray.720p.DTS.x264-CHD[������������������������]_2F3802736A.rmvb.005
http://www.filefactory.com/file/cb2450f/n/Robo.2010.Bluray.720p.DTS.x264-CHD[������������������������]_2F3802736A.rmvb.006

REVIEW QUESTIONS

5.1 Write a Java program that divides the number 74.3 by 12.6 and reports the result of the division. Store
the dividend and divisor in variables named dividend and divisor before performing the division.
What will be the type of these variables? What will be the type of the result? What is the quotient?
5.2 Write a Java program to compute the area of a circle whose radius is 5. For the value of PI, use 3.14.
Now rewrite your program so that it uses the very precise value of PI available as a static constant in
the Math class that comes with Java. Here is how you use the Math class constant:
double pi = Math.PI;
How much does your result change?
5.3 Write a Java program that prompts the user for a number, and then tells the user whether the number is
an even multiple of 5. Use Scanner to read the number from the user, and use the modulo operator
(%) to decide whether the number is a multiple of 5.
5.4 Write a Java program that asks a user to enter five Strings, one at a time. Have it save the Strings
in an array of strings. Then have the program display the words in reverse order. Use a for, or a
while, or a do while loop to read in the Strings, and another for, while, or do while loop
to print them out.
5.5 Write a Java program that can categorize vehicles based on the number of wheels the vehicle has.
Your program should prompt the user for the number of wheels on the vehicle, and then read the number
into an int variable. If the user says the vehicle has 2 or 3 wheels, the program will report that it is a
motorcycle, if it has 4 wheels the vehicle will be labeled a “car or light truck,” if it has 6, 8, 10, 12, 14,
16, or 18 wheels, it will be categorized as a truck. Any other number of wheels will be reported as an
error. Use a switch statement to compute the decision.
5.6 Write a Java class called Vehicle. The Vehicle class will have instance attributes for color, make,
model, speed, number of occupants, and maximum number of occupants. The Vehicle class will also
have a static variable called vehicleCount that can be used to track the number of vehicles in the
application. The constructor for Vehicle should expect values for make, model, maximum number of
occupants, and color, and it should set the vehicle speed to zero, the number of occupants to 1, and
increment the count of vehicles each time the constructor is called. Each of the instance and static variables
should have an accessor (get) method that will return the appropriate value, and all except the
vehicleCount variable should also have a mutator (set) method so that the value can be modified.
You should also give the Vehicle class an instance method called changeSpeed. The
changeSpeed method should expect a floating-point value for the new speed, and it should return a
floating-point value representing the difference between the new speed and the previous speed of the
vehicle. Include a public static void main(String[] args) method that creates a few
vehicles, sets some speeds, and reads some variable values, so that you can test your code by launching
the class from the command line.
5.7 Write a Skateboard class that inherits from Vehicle. Override the changeSpeed method for the
Skateboard class, so that instances of the Skateboard class can never exceed 10 mph. If a larger
value is supplied, the method will simply set the speed of the Skateboard to 10.
5.8 Write a Bus class that inherits from Vehicle. An instance of the Bus class must always have a
named driver. In the constructor for a Bus, make sure that your code expects and stores the name of the
driver. Also, the Bus class should have accessor and mutator methods for returning and changing the
name of the driver.
5.9 To the class Vehicle, add a refuel method that expects two parameters, fuelQuantity and
milesSinceLastFueling. Also add instance variables to the Vehicle class for totalMileage
and totalFuelConsumed. Further, add an accessor method called fuelEconomy that will return
the total miles per gallon of the vehicle.
What will you do to make the refuel method work properly when invoked on an instance of
Skateboard? Write a test class called ManyVehicles that creates a variety of different
Vehicles, exercises all the methods you have created, and checks for proper execution. Try to set the
speed of a Skateboard to 60, for example, or to refuel a Skateboard. Check that the fuel economy
calculations are being performed correctly.
5.10 Write a class that extends Exception and is called TooManyOccupantsException. Have the
Vehicle class mutator for number of occupants throw such an exception if the numberOfOccupants
would exceed the maximum number of occupants for the vehicle. What will you need to change in your
ManyVehicles test class?
5.11 Change your ManyVehicles class so that it reads from a text file called Vehicles.txt the specifications
for the Vehicles to create. Use a BufferedReader or a Scanner to read the file. Using a
Scanner is probably easier in this case. Here is a sample Vehicles.txt file. The first word in a
line is the color, the second word in a line is the make, the third word is the model, and the fourth word
is the maximum number of occupants:
red Ford F-150 3
silver BMW 328i 4
blue GM bus 32
gold Chrysler PTCruiser 4
orange WorldIndustries ProBoard 1
5.12 Write a Java program that iterates through the integers from 1 to 20, computing the square of each
number and writing the information to a file called squares.txt. Use a PrintWriter to write the
file of the first 20 integers and their squares. Arrange for two columns with a line of column headings at
the top. You will find this easy to do using the println() method of the PrintWriter.

SUMMARY

Java is a modern object-oriented programming language. This chapter discussed how to compile and run
Java programs. We discussed the “primitive” data types in Java, as well as the frequently used “reference” types
including String and Array types. We explained the use of control structures for selective code execution
and iteration. These statements included the if-else, for, while, do-while, and switch statements.
Java takes advantage of the OO concept of classes, and the attendant principles of inheritance, encapsulation,
and polymorphism. An instance of a class is called an object, and objects have state and behavior. Classes define
both instance and static variables, which manifest the state of an object. Classes also define both instance and
static methods, which endow objects with their characteristic behaviors. Java also provides the concept of an
interface, which makes it possible to enforce similar behavior across different classes.
Error handling in Java is accomplished using Exception objects. When an error occurs, a program can
throw an Exception, which can describe the problem. Exceptions can be caught within the application
when the code generating the Exception is enclosed in a try block. Following the try block can be multiple
catch blocks and a finally block. Catch blocks can specify which subclasses of Exception they
will handle. Code in a finally block will always be executed, whether an error occurs in the try block or not.
If the application does not catch an Exception, the Exception will propagate up to the JVM, which will
handle the Exception by reporting it and terminating the program.
Input and output in Java occurs using streams. A stream is a sequence of data elements. The many types of
streams available in Java can be classified into Input/OutputStreams, which handle raw binary data as
bytes, and Reader/Writer streams which handle character data, and automatically perform translations to and
from character encodings. For efficiency, good programming practice is to wrap a base stream object in a
buffered stream to provide efficient buffering of I/O.
The Scanner class in Java is a handy class for reading text from the keyboard, a file, or other input stream.
The PrintWriter class is another convenience class that facilitates the common task of writing formatted
text to a file.

PRINTWRITER

The PrintWriter is another very convenient I/O class; it makes writing text to a file as easy as writing
text to the display. To create a PrintWriter that is associated with a file, you simply pass the name of the
file to the constructor. Then you can write to the file simply using the print() and println() methods you
have learned to use for writing to the display.
A PrintWriter can be used with any output stream, but a very common use is to make it very easy to
write formatted text to a file. Here is a simple program that reads lines of text typed at the keyboard, and writes
the same text into a file using a PrintWriter. Using the println() method, this program adds a line
number at the front of each line as it writes the line to the file.
import java.io.*; //PrintWriter is here
import java.util.*; //Scanner is here
public class PrintToFile{
public static void main( String[] args) {
PrintWriter myWriter;
Scanner sc;
String lineOfData;
String fileName;
int lineNumber;
try {
System.out.print("Enter file name: " );
sc = new Scanner( System.in );
fileName = sc.nextLine();
myWriter = new PrintWriter( fileName );
System.out.println( "Now enter lines of text." );
System.out.println( "When you are done, " +
"type only Cntrl/z (EOF) on the line." );
lineNumber = 1;
while( sc.hasNextLine() ) {
lineOfData = sc.nextLine();
myWriter.println( lineNumber + ". " + lineOfData );
lineNumber++;
}
myWriter.close();
}
catch( IOException e ) {

System.err.println( "I/O error: " + e.getMessage() );
}
}
}

SCANNER

Often we need to read information from the user of the program. We might prompt the user, for example,
to ask them what kind of car they drive. We can ask the question of the user by displaying the question using
System.out.println(). We have shown many examples of displaying information on the screen.
Java provides a class called Scanner that makes it easy to read information from the keyboard into the
program. To create a scanner object for reading from the keyboard, we simply pass the standard input “stream”
to the constructor for a new Scanner. For example, here is a snippet of code to create a new Scanner for
reading from the keyboard, and then to use the Scanner to read a floating-point number:
...
Scanner scanner = new Scanner(System.in);
// Obtain input
System.out.print("Enter balance: ");
double balance = scanner.nextDouble();
...
The Scanner class has many methods, and you should consult the Java API documentation to see what
they are, and what choices you have.
You can also use a Scanner to read from a file. To associate a Scanner with a file of text, just pass
a FileReader object to the Scanner constructor:
sc = new Scanner(new FileReader( myFile.txt ) );
To read lines of text, you can use the nextLine() method of Scanner to transfer a line of text
into a String variable. You can also use the hasNextLine() method to test to see whether there is
something to read. Here’s a snippet of code to loop, reading text for processing into a String called
lineOfData.

String lineOfData;
Scanner sc = new Scanner( myFile.txt );
while( sc.hasNextLine() ) {
lineOfData = sc.nextLine();
...
}//while
When the program reaches the EOF, the hasNextLine() method will return false, and the program will
exit the while loop.

INPUT AND OUTPUT

Java programs read and write data by means of streams. A stream is a series of data elements that flows
from some input device to the program, or from the program to some output device. The general approach to
input and output (I/O) from a Java program is to:
Open the stream
While there is data to read or write
read and process data, or write data
}
Close the stream
The stream classes for I/O are grouped together in a Java package called java.io. A package is just a
collection of related classes. One can create packages of one’s own classes, but we will not be describing that
in this brief introduction to the language. The reason to mention the package name here is that a programmer
must import a package in order to take advantage of the classes within it. In order to use the stream classes
we will soon discuss, your program must have a statement at the very beginning, even before the class
statement, that says,
import java.io.*;
The asterisk means to import all the classes in the package. If the programmer wants only one of the
classes, the programmer can substitute the class name for the asterisk. Usually one simply types the line as we
have shown it.
The stream classes in Java are divided into two great categories: Reader/Writer and InputStream/
OutputStream. If the class is in the Reader/Writer category, it is a stream for reading and writing character
data—letters, numbers, and symbols. If the class is in the InputStream/OutputStream category, it
is a stream for reading and writing bytes—raw data, 8 bits at a time.
Students are sometimes confused thinking about the difference between character data and bytes. Are not
bytes used to encode characters? Yes they are. In fact, we could get along with just the InputStream/
OutputStream classes, and let programs be responsible for making sense of the data by converting the data to
characters when that was appropriate.
However, often data sources consist of character data, and it is very convenient to have I/O classes for
that common situation. If the information exists in the form of characters, a Reader/Writer will interpret
the information correctly and return a set of characters to the program. This saves the programmer having to
write a tedious conversion that would otherwise be necessary frequently.
If the information exists in some other form than characters, such as binary numbers in integer or floatingpoint
format, as in an image file, then it will not make sense to interpret the bit patterns as characters. In that
case, the programmer should use the InputStream/OutputStream classes, which will simply transfer the
bytes. Then the program will be responsible for interpreting the bytes correctly.
One other situation calls for the use of InputStream/OutputStream classes, too. That is when one
does not care what the data represent. This would be the case, for example, when the task is to copy a file. The
program doing the copying does not need to know what the content of the file means; it just needs to copy
each byte to a new file. In that case, using the InputStream/OutputStream classes instead of the
Reader/Writer classes makes sense, even if the file to be copied consists of characters, because the
InputStream/OutputStream classes will be more efficient—the step of translating bit patterns to characters
will be skipped.

There are 50 classes in java.io, and we will describe only a few here. To read a file of character data,
one would use a BufferedReader “wrapped around” a FileReader. The Java I/O design is very flexible,
and this is a good example of that. A FileReader reads characters from a file, and by wrapping the
FileReader with a BufferedReader, the I/O will be accomplished more efficiently by reading a group
of characters at once. The BufferedReader also provides a method called readLine(), which allows the
program to read a whole line at a time from a file into a String variable. Without the BufferedReader, a
FileReader only has methods to read characters.
Here is a little program to read a file of character data and display it on the screen:
import java.io.*;
/**
* A program that opens a character based file,
* specified on the command line,
* and shows its contents on standard output.
*
* @author Carl Reynolds
*/
public class ShowFile {
public static void main( String args[] ) {
BufferedReader in = null;
String line;
// Make sure the number of arguments is correct
if ( args.length != 1) {
System.err.println( "Usage: ShowFile sourceFile" );
System.exit(1);
}
// Attempt to open the file for reading
try {
in = new BufferedReader( new FileReader( args[0] ) );
}
catch ( FileNotFoundException e ) {
System.err.println( "ShowFile: " + e.getMessage() );
System.exit( 1 );
}
// Read and display
try {
while ( (line = in.readLine() ) != null ) {
System.out.println( line );
}
}
catch ( IOException e ) {
System.err.println( "ShowFile: " + e.getMessage() );
System.exit( 1 );
}
finally {
// Close the file
try{
in.close();
}
catch( Exception e ) {}
}
}//main
} //ShowFile
This program checks the command line arguments in the array of Strings called args to make sure that the
user provided a parameter for the file name. If the user provided exactly one argument, the program assumes this
argument is the name of a file, and it attempts to open the file using a BufferedReader inside a try block.
If all goes well, the program enters a while loop calling the readLine() method of the
BufferedReader to read a line of the file at a time into the String variable line, and then display the
text using the println() method. The loop will terminate when readLine() returns a null value; that is
the signal that the BufferedReader has encountered the end-of-file (EOF).
The program uses the finally block to close the file. Since the close() method can itself
throw an IOException, the call to close() within the finally block must also be surrounded by
a try block. If an error occurs here, however, this program simply ignores it; the catch block is empty
of any code.
Our second example reads a file for the simple purpose of copying the bits in the file to a new file. For this
purpose we use a BufferedInputStream wrapped around a FileInputStream. The program copies
the bits literally, one byte at a time. This approach is highly efficient because there is no overhead of translating
the bit patterns into characters.
import java.io.*;
/**
* Copy files from the command line.
* @author Paul Tymann
* @author Carl Reynolds
*/
public class FileCopy {
public static void main( String args[] ) {
BufferedInputStream in = null;
BufferedOutputStream out = null;
int data;
// Check command line arguments
if ( args.length != 2 ) {
System.out.println(
"Usage: FileCopy sourceFile destFile");
System.exit(1);
}
try {
// Open the input file.
in = new BufferedInputStream(
new FileInputStream( args[0]) );
// Open the output file.
// If the output file exists, it will be overwritten.
out = new BufferedOutputStream(
new FileOutputStream( args[1] ) );
}
catch ( FileNotFoundException e ) {
System.err.println("FileCopy: " + e.getMessage() );
System.exit( 1 );
}
// Now copy the files one byte at a time
try {
while ( (data = in.read() ) != -1) {
out.write( data );
}
}

catch ( IOException e ) {
System.err.println( "FileCopy: " + e.getMessage() );
System.exit( 1 );
}
finally {
// Close the files.
try {
in.close();
out.close();
}
catch( Exception e ) {}
}
}//main
} //FileCopy
When the program opens the BufferedOutputStream, the new FileOutputStream opens an
existing file for overwriting, or, if the output file does not exist, it creates a new output file for writing. There is a
second parameter in the constructor for the FileOutputStream which would allow a program to append to
an existing file, but we have not used that here.
With the read() method of the BufferedInputStream, either a byte of data is returned, or, if the
program encounters the EOF, a binary -1 is returned. As long as the read() continues to return bytes, the
program calls write() to copy the data. Though you see individual bytes being read and written, the transfer
is much more efficient than you might think, because the InputStream and OutputStream are buffered.

ERROR HANDLING

Java uses Exceptions to represent error conditions.
Exception is actually a class in Java, and when a program creates an Exception, it creates a new
object, which is an instance of the Exception class. An Exception object can have information about what
went wrong, usually including an error message, and a “stack trace” showing which method created the error.
Having created an Exception object when something goes wrong, the program “throws” the Exception
using the key word throw. The JVM will print an error message and stop execution when a program throws
an Exception, unless the programmer has provided code to “catch” the exception and handle the error
condition in the program. This approach to handling program errors is called “exception handling” for obvious
reasons, and it’s a relatively modern idea.
One advantage of handling errors this way is that code to handle error conditions will be segregated into
code blocks separate from the main logic of the program. This makes it much easier to follow the intent of the
programmer, both in the main logic and in the error handling code.
Java provides many subclasses of Exception so that different problems result in different classes
of Exception objects being thrown. Some examples include FileNotFoundException,
NullPointerException, and NumberFormatException.
Java recognizes two types of Exceptions, checked and unchecked. The names come from what the Java
compiler does with them. The compiler “checks for” appropriate handling of checked Exceptions, but does
not check for handling of unchecked Exceptions.
An unchecked Exception represents an error that is probably too serious for an application to correct.
An example is the NullPointerException, which occurs when the program tries to access a variable
which should contain a reference to an object, but which contains null instead. The compiler assumes that such
an exception should cause the program to terminate with an error condition, so it does not check to see that the
program has code to handle that error condition itself.
A checked exception such as FileNotFoundException represents an error condition from which
the program potentially could recover. In the case of FileNotFoundException, for example, the
program could prompt the operator for a new file name and try again. If the compiler recognizes that a
method could encounter a checked exception, the compiler will require that the method either provide a
handler for that exception or declare with its own throws declaration that it can itself generate the checked
Exception.
The way to add exception handling to a Java program is to enclose program statements which might generate
an Exception within a try block. A try block begins with the key word try and an open curly brace.
At the end of the code being included in the try block is a close curly brace. Immediately following the try block
will be one or more catch blocks. A catch block contains the code to handle the error.
Let’s go back to our Automobile class and its accelerate() method. Instead of simply setting the
speed of the Automobile to its maximum value when the argument to the accelerate() method is too
large, we can have the Automobile class generate a special subclass of Exception appropriate to this
application. Here is the code for our new ExcessiveSpeedException class:


public class ExcessiveSpeedException extends Exception {
ExcessiveSpeedException( Automobile a ) {
super( "New speed exceeds maximum speed of "
+ a.toString() );
}
}
Our ExcessiveSpeedException inherits from Exception. The ExcessiveSpeedException
constructor expects an Automobile object as an argument. To take advantage of the message attribute inherited
from the superior class, it incorporates the toString() description of the Automobile into the message
that it passes to the constructor of the superior Exception class.
Now we can rewrite the accelerate() method of Automobile as follows:
public void accelerate ( double newSpeed )
throws ExcessiveSpeedException {
if( newSpeed > 70. )
throw new ExcessiveSpeedException( this );
speed = newSpeed;
}
The reference to this means that the particular instance of Automobile that generates the
ExcessiveSpeedException will be passed to the ExcessiveSpeedException constructor. Notice
that the method header for accelerate() now includes a declaration that the method can throw an
ExcessiveSpeedException. If you forget to include the declaration, the compiler will require such a
declaration when it sees that some statement within the method throws an ExcessiveSpeedException.
Finally, notice that we no longer require an else clause after the if statement. Once a method throws an
exception, execution stops, except for whatever code is ready to catch the Exception. Therefore, we no
longer need else to insure two non-overlapping paths of execution in response to the test in the if statement.
We can rewrite the AutomobileFactory class to handle the possible occurrence of an
ExcessiveSpeedException.
.
.
.
try {
family.accelerate( 120. );
sports.accelerate( 120. );
}
catch( ExcessiveSpeedException ex) {
System.out.println( ex.getMessage() );
}
System.out.println( family + " " + family.getSpeed() );
System.out.println( sports + " " + sports.getSpeed() );
}
In this case, the catch block simply reports the error, and the program continues on. With other errors, the
catch block might try to correct the problem, ask the user for a decision, or simply terminate the program by
calling System.exit().
The output from this version of AutomobileFactory looks like this:
3 Automobiles
2006 Kia Rio
2002 VW Passat
2005 Ford Mustang
New speed exceeds maximum speed of 2002 VW Passat
2002 VW Passat 0.0
2005 Ford Mustang 0.0

When AutomobileFactory tries to accelerate the VW to too great a speed, the Automobile class
throws an ExcessiveSpeedException which stops execution of accelerate() and transfers control
to the catch block. The catch block reports the problem by printing the message attribute of the Exception
object. When the catch block completes, the program continues, but the speeds of both Automobiles remain
0.0, because the path of execution never set the speed of either one.
There can be more than one catch block; in fact, you can have several. Each one can specify a particular
class of Exception to handle. That is important to segregating code for handling different kinds of problems.
If a method throws a FileNotFoundException, it may be easy to fix by asking the operator to enter the
file name again. On the other hand, if a read of the file fails and the method throws an IOException, it may
be difficult for the program to recover. In the first case the catch block may “soldier on,” and in the second case
the catch block may simply report the error and then call System.exit().
When more than one catch block follows a try block, the catch blocks should be ordered such that lowerlevel
Exception classes occur before higher-level, more general classes of Exceptions. When a method
throws an exception, the try block searches down the list of catch blocks until it finds a match between the
Exception class that was thrown and the Exception class declared in the catch block. The first acceptable
match will be invoked to handle the error. If the first catch block specifies objects of class Exception, the
most general class, the first catch block will handle all Exceptions, regardless of whatever other catch
blocks there may be. So, if a program wants to attempt to recover from a FileNotFoundException and
terminate on any other failure, the catch block for the FileNotFoundException should come before the
catch block for the class Exception.
There’s one more option. After the try block and all the catch blocks, a programmer can add a finally block.
A finally block contains code that will always be executed, whether an error occurs or not. A finally block is
a good place to put general “clean-up” code, like the statement to close a data base.
Here is the syntax for the try/catch/finally construction:
try {
.
. //main line logic goes here
.
}
catch( SpecificException ex ) {
.
. //handle SpecificException
.
}
catch( LessSpecificException ex ) {
.
. //handle LessSpecificException
.
}
catch( Exception ex ) {
.
. //handle everything else that might happen
.
}
finally {
.
. //tidy up — this code will always be executed
.
}
//If code is successful, or exception is caught and
// handled, execution will continue here.

Java’s error-handling mechanism is one of its great strengths. Exception handling with try/
catch/finally is very robust and leads to very supportable code. Since one can easily add application-specific
exception classes to support one’s own work, this approach is also very extendable.

INTERFACES

In Java, we can also specify an interface to enforce a common set of behaviors among different classes.
For example, think about the problem of sorting a group of Automobile objects. How should Automobiles
be ordered? By year? Alphabetically by make? By horsepower? This problem arises frequently when we’re
working with objects, so the Java language specifies an interface that any new class can implement in order
to facilitate sorting instances of the new class.
An interface consists of one or more method signatures, but it does not contain any code implementing any
of the methods. (An interface can include constants as well as method signatures, but we will focus on the methods.)
A method signature is like the first line of a method; the signature specifies what the method will return,
the name of the method, and what arguments the method expects when it is called.
For example, Java provides the interface Comparable, and the Comparable interface specifies a single
method called compareTo(). The compareTo() method expects an object as an argument (the object with
which to compare the first instance) and it returns an int. The value of the returned int will be 0 if the two
objects being compared are equal, -1 if the first object is “smaller” (should be ordered first), and +1 if the first
object is “larger” (should be ordered second).
We can implement the interface Comparable in our Automobile class by adding this code to our class
Automobile:
class Automobile implements Comparable<Automobile> {
.
.
public int compareTo( Automobile car )
{
return this.toString().compareTo( car.toString() );
}
The new first line of our Automobile class now declares that the class Automobile will implement
the interface Comparable. The <Automobile> syntax says that we will only be comparing an Automobile
object with another Automobile. If, by some error of programming, our program tries to compare an
Automobile object with a Thermostat object, the JVM will generate an error.
The new compareTo() method implements the Comparable interface for the class Automobile.
We’ve taken a shortcut here which takes advantage of the toString() method we already have for
Automobile. The phrase this.toString() will return a String object which represents this instance
of an Automobile. The key word this always references the particular instance itself. The String
returned will be of this form:
2002 VW Passat
The year will be followed by the make and the model of the Automobile. Likewise, the phrase
car.toString() will return a String representing the other Automobile, such as this:
2006 Kia Rio
The String class has a compareTo() method that orders Strings in “ASCIIbetical” order, which is
like alphabetical order, except that it follows the ASCII encoding values of characters. In ASCII the letters are
coded in alphabetical order, but all uppercase letters come before any of the lower-case letters, and digits and
symbols are included as well as letters. For our purposes of ordering Automobiles, we thought that the
toString() representation of Automobiles sorted in ASCIIbetical order would be fine. Older
cars will be ordered first, and among cars of the same year, cars will be sorted ASCIIbetically by make and
model.
The interface idea is similar to the idea of a class, in that an interface creates a new data type. When
the class Automobile implements the interface Comparable, instances of Automobile can also be
treated as instances of Comparable. Just as good design of a class hierarchy can reduce programming and
improve reliability, good interface design can also.
For instance, the sort() method of the Java Collections class will sort lists of Comparable
objects. Our Automobile class implements Comparable, Java’s String class implements Comparable,
Java’s Date class implements Comparable, etc. One sort() method will work for any group of objects
whose class implements Comparable. That alone is a great example of code reuse.
It’s easy to design and use your own interfaces, too. However, in this brief chapter we will not be discussing
that topic

POLYMORPHISM

The word polymorphism means “many forms.” When a subclass overrides a method of a superior class, the
behavior of the method will depend upon which type of object is being used in the program, an instance of the
superior class or an instance of the subclass. This characteristic of OO programming is called polymorphism,
and it is a powerful feature of the OO approach.
We will add some lines to our AutomobileFactory class to set the speed of a family car to 120 and
set the speed of a sports car to 120. Looking back at the accelerate() method for the class Automobile,
you will see that the maximum speed for an instance of the Automobile class is 70. Compare that with the
accelerate() method for the SportsCar class; the top speed for a SportsCar is 150.
When we call the same accelerate() method for an instance of Automobile and an instance of
SportsCar, the results are different. The Automobile speeds up to 70, and the SportsCar speeds up to
120. To show this, add code to the AutomobileFactory class:
/**
* Class AutomobileFactory
* @author Carl Reynolds
*/
class AutomobileFactory {
.
.
.
family = new Automobile(
"VW", "Passat", 2002, 170 );
sports = new SportsCar(
"Ford", "Mustang", 2005, 300 );
.
.
.
//same method call to instances of 2 different classes
family.accelerate(120. );
sports.accelerate(120. );
//polymorphism will cause the effects to be different
System.out.println( family + " " + family.getSpeed() );
System.out.println( sports + " " + sports.getSpeed() );
}
This will be the new output:
3 Automobiles
2006 Kia Rio
2002 VW Passat
2005 Ford Mustang
2002 VW Passat 70.0
2005 Ford Mustang 120.0
Polymorphism allows us to write programs in a more general way. We can reference the superior class as
we write programs, and if the object being used by the program happens to belong to a subclass of the superior
class, the methods in the subclass which override the corresponding methods in the superior class will insure that
methods appropriate to the particular instance will be called. This is another way in which OO programming
reduces the amount of code that must be written and tested, and also promotes reuse of existing code in new
applications.

Inheritance

OO programming makes it easy to add functionality to software without rewriting the code one has already
written and tested. Suppose we want to add distinctions between types of Automobiles. A Ferrari can go
much faster than a Kia, so the accelerate() method should be different, and perhaps other behaviors
should also be different for such different Automobiles.
We can add a new class called SportsCar that will inherit from Automobile, and we can give the
SportsCar class a different accelerate() method. Here is the Java class for SportsCar:
/**
* Class SportsCar
* Inherits from class Automobile
* @author Carl Reynolds
*/
class SportsCar extends Automobile {
private double maxSpeed = 150.;
//constructor
SportsCar( String mk, String mdl, int yr, int power )
{
super( mk, mdl, yr, power );
}
//override of inherited accelerate() method
public void accelerate( double newSpeed )
{
if( newSpeed > maxSpeed ) speed = maxSpeed;
else speed = newSpeed;
}
}
The SportsCar class extends the class Automobile; that means SportsCar inherits from
Automobile. Any instance of a SportsCar will also be an Automobile, and except where there are
differences between the code for SportsCar and the code for Automobile, an instance of a SportsCar
will have exactly the same state variables and behavior as any instance of the class Automobile.
The SportsCar class must also have a constructor; it’s called SportsCar. The constructor for
SportsCar simply uses the constructor for Automobile, the superclass, by using the super key word to
pass the same values for make, model, year, and power to the constructor for the Automobile class.
The only difference between instances of SportsCar and instances of Automobile will be the
behavior provided by the accelerate() method. In the case of an Automobile, the maximum speed will
be 70, but in the case of a SportsCar, the maximum speed will be 150. We say that the subclass SportsCar
overrides the accelerate() method inherited from the superclass Automobile.
Everything else that is true about an Automobile object will be true about a SportsCar object.
All will have instance variables to store make, model, year, horsepower and speed. Creating either a new
Automobile or a new SportsCar will increment the count of Automobiles maintained by the
Automobile class.
We didn’t have to change any of our existing code to enhance our work to treat sports cars differently from
other automobiles!

INSTANCE AND STATIC VARIABLES AND METHODS

One twist of complexity is that some state information and some behaviors belong to the class, while others
belong to the instances of a class. For instance, we would maintain the speed of each Automobile as part of
the state of each individual car (part of the state of each instance). On the other hand, we would maintain a
count of the total number of Automobiles as part of the state of the class Automobile. It seems natural
that speed should be associated with a particular car, but we need a central place to keep track of the total
number of Automobiles.
Perhaps we’re stretching the analogy a little bit, but
imagine a Ford on the road. It has a speed we can
measure, but after the Ford exits the factory, there is no easy way for the Ford to be kept apprised of the total
number of Automobiles that have been built. If we want to know how many Automobiles have been
built, we must go back to the factory and get the count. The factory is the class.

Variables like speed, which represent the state of an instance of a class, are called instance variables.
Variables like count, which are maintained by the class itself, are called static variables. The word static
means many things in computer science, and this use of the word static may be confusing. Other languages label
the same idea with a different name; for example, Visual Basic calls variables of this kind “shared” variables,
because they’re shared by all instances of a class. That term may be more helpful as you learn, so when you see
“static,” think to yourself “shared,” or “class.”
Similarly, methods can be instance methods or static methods. If two different instances of a class both
call the instance method accelerate(), it will be as if there were two different copies of that method, and
each instance had its own. (In reality, there will not be two copies of the code, but each instance will get its own
“stack” for local variables, which will keep the execution of the two calls separate, as if the code existed in two
places.) On the other hand, if two different instances of a class call the static method getAutomobileCount(),
the two instances will be using exactly the same code, because there is only one copy, and that is shared.
Variables and methods will always be instance variables and methods, unless you specifically label them
static. If you label a variable or method static, the variable or method will exist only at the level of the
class, and will be shared among the instances.
Below is our example Automobile class. Notice that there is no main method in the Automobile
class. This class cannot be executed directly. If we were to add a public main method, the class could be executed,
and whatever the main method were coded to accomplish would be done. However, this Automobile
class is intended to be a “factory” to create Automobile objects for use by other programs and classes,
rather than to be a program to be run by itself. You can think of the Automobile class as creating a new data
type—Automobile.
Notice also that in the class Automobile there is a method named Automobile; the name of the
method is the same as the name of the class. The method named Automobile is the constructor for the class.
Whenever another program needs an instance of an Automobile, the other program will use the new keyword
to request a new Automobile. We can tell from the Automobile constructor that the constructor
expects four parameters whenever a new Automobile is requested; these are the make, the model, the year,
and the horsepower. The first two parameters are String values, and the last two are ints.
When another program asks for an instance of an Automobile, the constructor will create an
Automobile object and return to the other program a reference to the new Automobile. A reference is an
address. The other program can then use the reference to the new Automobile object to manipulate it.
/**Class Automobile
* Illustrating instance and static varibles
* and methods
* @author Carl Reynolds
*/
class Automobile {
//static variable
private static int count; //count of automobiles
//instance variables
private String make;
private String model;
private int year;
private int hp;
private double speed;
//Constructor
Automobile( String mk, String mdl, int yr, int power ) {
make = mk; //assign constructor parameters
model = mdl; // to private instance variables
year = yr;
hp = power;
count++; //add to count of Automobiles created
}

//static method
static int getCount() {
return count;
}
//instance methods to set and get speed
public void accelerate( double newSpeed ) {
if( newSpeed > 70. ) speed = 70.;
else speed = newSpeed;
}
public double getSpeed() { return speed; };
//returns a text representation of an Automobile
public String toString() {
return year + " " + make + " " + model;
}
}
Here is a class which uses the Automobile class:
/**
* Class AutomobileFactory
* @author Carl Reynolds
*/
class AutomobileFactory {
public static void main( String[] args ) {
Automobile economy, family, sports;
economy = new Automobile(
"Kia", "Rio", 2006, 110 );
family = new Automobile(
"VW", "Passat", 2002, 170 );
sports = new Automobile(
"Ford", "Mustang", 2005, 300 );
System.out.println(
Automobile.getCount() + " Automobiles" );
System.out.println( economy );
System.out.println( family );
System.out.println( sports );
}
}
The class AutomobileFactory can be executed directly, because it has a main method coded in
the standard way. The main method declares three variables to be of type Automobile (notice you can
declare several variables of the same type on one line, as we did here), and then it creates three Automobile
objects by using the new keyword to invoke the constructor for the Automobile class three different
times.
The first println statement calls the static method getCount() by specifying the class name
Automobile, followed by a dot (period), followed by the method name getCount(). The getCount()
method will return the number 3, because each time the constructor of the Automobile class generates a new
Automobile, it increments its static count variable.

Finally, the three println statements at the end print a text representation of each Automobile. Such
use of an object’s name, such as economy, inside println causes the JVM to use the toString() method
of the class. When that happens here, the result on the screen is this:
3 Automobiles
2006 Kia Rio
2002 VW Passat
2005 Ford Mustang

INHERITANCE

You may be thinking that one accelerate() method might not work for all instances of the class
Automobile. May be the acceleration behavior a Ferrari should be modeled differently from the acceleration
behavior of a Kia. If we want to model such differences, we can take advantage of the OO programming
paradigm called inheritance.
One class can inherit from another, in which case the new class (called the subclass or subordinant class
or child class) carries all the variables and methods of the higher-level class (called the superclass or superior
class or parent class). In addition, the child class can add state variables unique to the child class, and add
behavior methods unique to the child class. In addition, the child class can override methods of the parent class
in order to give the child class different behavior, even though the name of the method implementing the behavior
has the same name as the method of the parent class.
These sorts of considerations lead software developers to create a class hierarchy. The programmer defines
the more general state variables and behavior methods in higher-level classes. Then, when writing the subordinant
classes, the programmer uses the inherited state and behavior when it fits, and adds state variables, methods,
and overriding methods to subordinant classes in order to implement differences between the superior and
subordinant classes.
The beauty of this technique is that classes which are written and tested do not change. Existing software
functionality can be reused. When the programmer requires new features in a class, the programmer can inherit
from an existing, tested class, and write new software simply to meet the new requirements.
If one decides to implement the accelerate() method differently for different Automobiles, one
would write the parent class Automobile, and then have subordinant classes inherit from Automobile.
In our example, we might design several classes to inherit from Automobile, a class called EconomyCar,
a class called FamilyCar, and a class called SportsCar. Each of these subordinant classes would inherit
the accelerate() method from the Automobile class, and could override the inherited accelerate()
method to change the acceleration behavior of instances of the subordinant class. If a subordinant class does not
override the method of the superior class, instances of the subordinant class will respond to the method just as
instances of the superior class do. If my Ford “is” a FamilyCar, my Ford also “is” an Automobile, because
FamilyCar inherits from Automobile.

OBJECT STATE AND BEHAVIOR

Grady Booch, a well-known writer on the topic of OO programming, has defined an object as
something “that has state, behavior, and identity.” In other words, an object has characteristics (which may
change over time), an object can perform certain prespecified actions, and an object provides us a way to
refer to it. The state of an object is provided by variables. As the values of variables change, the state of the object
changes. At any point in time, the values of the instance’s variables provide its state. For example, the speed
of my Ford varies over time. At any particular moment, the state of my Ford includes the speed at which it is
currently moving.
The behavior of objects is provided by methods. A method is a programming procedure. In the case of my
Ford, the accelerate() method allows my Ford to change speed. In the world around us, we observe that
different members of the same class behave similarly; it’s easy to distinguish a dog from a cat by the way the
individual animals move. Likewise, we expect different instances of the same Java class to behave similarly, so
methods are defined by procedures in the class, not in the individual instances. The class Automobile will
have the definition of the accelerate() method, and any particular instance of Automobile will behave
similarly by changing speed using the same method.

CLASSES AND OBJECTS

People new to OO programming often have difficulty distinguishing what are called classes from what are
called instances. A class is a specification, a blueprint, or maybe even a concept, like vehicle; an instance is a
specific example of a class. From the class Automobile, one can build or identify particular cars. My Ford
with vehicle ID 1FABP64T1JH100161 is said to be an instance of the class Automobile.
Often the word object is used as a synonym for the word instance. One also says that my Ford is an object
of the class Automobile. This can be confusing, especially at first, because Java, like some other OO
languages, also recognizes a class called Object (capital O). In fact, every class in Java inherits from the class
Object (we will discuss inheritance soon); the class Object is the root of the Java class hierarchy. Though
the use of the word in two senses can be confusing, generally one should understand the word “object” to mean
“instance,” unless the word “Object” is capitalized.
We say that <an instance> “is” <a class>. Some writers say that an “is-a” relationship exists between
an instance and its class. For instance, my Ford is an Automobile.

OBJECT-ORIENTED PROGRAMMING

Java is an object-oriented language, which means that Java facilitates the writing of object-oriented
programs. Object orientation is more a matter of how one thinks about programming than it is a particular
programming technique. When one writes object-oriented code, one thinks of software “things” that are analogous
to things in the outside world.
For instance, if our job is to write software for the State Thruway Authority for automated toll collection,
we would think about the job differently depending upon whether we take the older “procedural” approach or
the newer object-oriented (OO) approach.

Using the procedural approach, we would break the job down into subtasks, or subroutines, write the
routines, and combine the routines with a main program into a sequence of activities to be performed. We might
have a carEntersThruway procedure, and a carExitsThruway procedure, and we might keep information
in a file about the cars using the Thruway.
Using the OO approach, we would think about the “things” in our problem domain, and create analogous
software classes. For instance, we would probably have a Vehicle class, and we might have a
ThruwayInterchange class, and a VehicleOwner class. We would give Vehicles characteristics that
are important to our application, such as licenseNumber, state, make, model, and color. Since we
need to track where vehicles enter and leave the Thruway, we might add Vehicle properties
enteredAtInterchange and exitedAtInterchange. Likewise, the properties of a VehicleOwner
might include firstName, lastName, streetAddress, city, state, and zipCode.
The logic of an OO program gets coded as “methods” of the objects. Instead of having an isolated
or application-wide carEntersThruway procedure, as we might using the procedural approach, we can
have similar code in a method of the Vehicle class. The logic may be the same, but in the OO approach we
think of a Vehicle object having “behaviors” appropriate to the application. When a Vehicle enters
the Thruway, we will call the Vehicle’s enterThruway method, and the Vehicle object will deal
appropriately with that event.
The data one operates on and the logic one encodes may be the same for the procedural approach and
the object-oriented approach, but the object-oriented approach organizes the work differently. When an objectoriented
program is complete, a set of classes is the result. These classes, if well designed, can be reused
and extended more easily so that future programming projects have a head start.
Putting the code inside classes also allows functionality to be encapsulated, which leads to more effective
testing and more reliable use later on. The software classes exist as their own entities, with known properties
(attributes), and well-defined methods. Using inheritance, the OO approach also offers a standard way to add
functionality without changing at all the code that has already been written. There is less temptation to modify
the classes that have already been defined, implemented and tested. The result is usually more stable and
reliable code.
Object orientation is an advance in how programmers think about their work. The OO approach leads to
software classes which more closely model the real world, and therefore make the application more natural
to think about. In addition, building classes usually leads to code which is more easily reused. Both effects lead
to better programming productivity.

BASIC CONTROL STRUCTURES

All programming languages provide ways to alter the sequence of instructions that actually get
executed when a program runs. This ability to select which logic to apply, or to choose an appropriate
number of times to cycle through a section of code, is what makes programs flexible enough to be
useful in the real world. Imagine a program to compute the average grades for students in a class,
but imagine that the program requires all classes to have exactly the same number of students, and
has no way to properly handle a missing grade! Such a rigid program would not be worth the trouble
to write.
if
The most common control structure for selecting a block of code to execute is the if statement. The if
statement can be used in its simple form, or in its extended if-else form. Here is an example of a simple
if statement:
if(grade > 0) {
sumOfGrades = sumOfGrades + grade;
numberOfGrades++;
}
This statement says, if the variable grade is greater than 0, then add the grade value to the variable
sumOfGrades, and increment the variable numberOfGrades by 1. Otherwise, do nothing. Either both
statements following the if statement will be executed, or neither will be, because they are both within the
curly brackets which follow the if. The curly brackets mark a code block.
If the tested condition is true, then the code block of the if statement will be executed. If the condition
is false, the code block will be skipped.
Here is the syntax of the simple if statement:
if( <conditional expression> ) <statement>
The conditional expression must evaluate to either true or false. If the conditional expression is true,
the following statement will be executed, but not otherwise. The <statement> can also be a compound
statement, which is another way of saying that <statement> can be a code block enclosed in curly braces.
A compound statement or code block is enclosed in curly braces, and each statement inside must be terminated
with a semicolon.
Here is an example of an if-else statement:
if( windSpeed > 20 ) {
hoistSmallSail();
}
else {
hoistLargeSail();
}
The if-else statement allows the program to select one of two mutually exclusive paths of execution. In
this case, if the wind is strong, the program calls a method to hoist a small sail. Otherwise, the program calls a
method to hoist a large sail. By the way, you can tell that hoistSmallSail() and hoistLargeSail()
are methods because a pair of parentheses follows the name. A method is a named block of code, and we will
talk about methods when we discuss classes and objects in more detail later.
Here is the syntax of the if-else statement:
if( <conditional expression> ) <statement_one>
else <statement_two>
If the conditional expression is true, statement_one will be executed. If the conditional statement is
false, statement_two will be executed. As before, statement_one and statement_two can be
compound statements, i.e., code blocks framed in curly braces.
for
Programs frequently must iterate or loop through a block of code repeatedly. Java has several control structures
for this purpose, and one of the most commonly used control structures of this type is the for loop.
Suppose we want to compute the average grade in a class of students. We have the scores in a file
called Students, and each line in the file contains a single score. Each score is the grade of one of the students
(e.g., 89.5). We could write code such as this to read the scores from the file and compute the total of
all the scores:
double total = 0.0;
BufferedReader in = new BufferedReader(
new FileReader( "Students" ) );
for ( int i = 1; i <= numberOfStudents; i++ ) {
String score = in.readLine();
total = total + Double.parseDouble( score );
The first line declares a thing called a BufferedReader, which is “wrapped around” a FileReader
that opens the file called Students. We will discuss these sorts of input/output statements further in the
section on Input and Output. This statement declares the variable in to be a BufferedReader associated with
the file Students.
Notice that programming statements in Java can continue to a second, third, or more lines. The Java
compiler will continue to interpret the lines as one statement until it encounters the semicolon, which marks the
end of the statement.
The for statement begins with parentheses enclosing three expressions, which are separated by semicolons.
The first expression defines initial conditions in the for loop. In this case, the expression declares an
int called i, and sets the value of i to 1.
The second expression in the for statement establishes a condition which will evaluate to either true or
false. When the condition is true, the code block of the for statement will be executed. In this case, as long as
the value of i is less than or equal to the number of students, the loop will execute.
The third expression in the for statement specifies what to change each time the loop is executed. This
expression is sometimes called the “increment expression,” because it is usually employed to change the value
of the variable being tested in the second expression. That is the case here, because the third expression says to
increment the value of the variable i each time the loop executes.
The body or code block of the for statement follows the three expressions within parentheses. In this case,
the readLine() method of the BufferedReader reads the next line of the file into a String variable
called score. Since the BufferedReader reads character strings, we must convert the characters into an
internal floating-point number before we can do our math. The last line says use the parseDouble() method
of the Double class to interpret the character string in score (e.g., 89.5) as a double (a floating-point
number which can include a fractional part). The Double class is one of Java’s “wrapper classes,” which we
discussed in the section on data types.
In summary, this for loop will begin executing with the value of i set to 1. After each execution of the
loop, the value of i will be incremented. The loop will continue to execute as long as the value of i is no greater
than the number of students. When i becomes greater than the number of students, the conditional test in the
second expression of the for statement will fail (will be false), and the program will “drop out” of the loop and
continue at the next statement following the for loop body.
Here is the syntax of the for statement:
for( <initial>; <test condition>; <increment> ) <body>
The conditional expression must evaluate to either true or false. If the conditional expression is true, the
body of the for loop will be executed, but not otherwise. The <body> is usually a compound statement, which
is a code block enclosed in curly braces. Each statement within the body must be terminated with a semicolon.
while
Another structure to control looping (iteration) is the while statement. Suppose we don’t know how many
student scores are in the file of student scores. We can use a while statement to read the file until there are no
more scores in the file to be read:
double total = 0.0;
BufferedReader in = new BufferedReader(
new FileReader( "Students" ) );
String score = in.readLine();
while( score != null ) {
total = total + Double.parseDouble( score );
score = in.readLine();
 We use the same BufferedReader as before to read the file Students. After reading the first line in
the file, the while statement checks to see if the variable score has a value of null. The variable score will
be null only if there was nothing in the file to read. As long as score is not null, the body of the while statement
will execute—it will “parse,” or interpret, as a fractional number, whatever the BufferedReader just
read, and then it will read the next line in the file.
The while statement syntax is very simple:
while( <loop condition> ) <statement>
Again, the statement can be a code block enclosed in curly braces. As long as the test condition remains
true, the body of the while statement continues to execute. This is a very appropriate control structure when
we do not know in advance how many times a code block must execute.
do-while
A variation of the while statement is the do-while. In the case of the do-while statement, the body
of the loop executes before the code checks the loop condition. When a program must execute a block of code
at least once, the do-while may be the best choice for controlling a loop. Here is code to use the do-while
statement instead of the while statement for reading the file Students:
BufferedReader in = new BufferedReader(
new FileReader( "Students" ) );
String score;
do {
score = in.readLine();
total = total + Double.parseDouble( score );
} while( score != null )
At first glance, it looks like this version saves code. However, in this particular case, this code exposes us
to danger. If the file should ever be empty, the first call to parseDouble will cause the program to fail with
a run-time exception, because Double.parseDouble cannot parse a null value. In this application, we
would do better to use the while instead of the do-while.
This is the syntax of the do-while loop:
do <loop body>
while( <loop condition> );
The loop body can be, and usually is, a code block framed by curly braces. As long as the loop condition
remains true, the loop body will execute again and again. The do-while structure is particularly appropriate
when you require the loop body to execute at least once every time the program runs.
switch
The last control structure we will discuss here is the switch statement. Like the if statement, the
switch statement allows your program to select certain statements to execute under certain conditions. The
switch statement is more complex, and one can always use a series of if statements instead of a switch
statement, but switch is very appropriate and readable for some programming problems.
Suppose we have a group of students and want to assign them to different dorms depending upon whether
they are freshmen, sophomores, juniors, or seniors. Let’s assume that the variable yearInSchool is coded
as an int, and is set to 1 for freshmen, 2 for sophomores, 3 for juniors, and 4 for seniors. We could then use
this code to decide to which dorm each student should be assigned:

switch( yearInSchool ) {
case 1: System.out.println( "Oberlies Hall" );
break;
case 2: System.out.println( "Kiriazides Hall" );
break;
case 3: System.out.println( "Glisson Dorm" );
break;
case 4: System.out.println( "Valk Hall" );
break;
default: System.out.println( "illegal year" );
}
If a student is a freshman, the student will be assigned to Oberlies Hall; if the student is a sophomore, the
student will be assigned to Kiriazides Hall; etc.
Notice the break statements. The break statement says to exit the switch statement. If the break
statement is missing, the execution of the switch statement will “fall through” to the next case. Sometimes
you will want that to happen, but certainly not always. Forgetting to insert the break statement appropriately
is a common programming error.
Here’s an example using the switch statement to allow “falling through” from one condition to the next
in a helpful way:
switch( dayOfChristmas ) {
case 12: System.out.println( "Twelve drummers drumming" );
case 11: System.out.println( "Eleven pipers piping" );
case 10: System.out.println( "Ten lords a-leaping" );
case 9: System.out.println( "Nine ladies dancing" );
case 8: System.out.println( "Eight maids a-milking" );
case 7: System.out.println( "Seven swans a-swimming" );
case 6: System.out.println( "Six geese a-laying" );
case 5: System.out.println( "Five golden rings" );
case 4: System.out.println( "Four calling birds" );
case 3: System.out.println( "Three French hens" );
case 2: System.out.println( "Two turtle doves" );
case 1: System.out.println( "And a partridge ... tree" );
break;
default: System.out.println( "?Day = " + dayOfChristmas );
}
Notice that in this example, the case statements proceed from highest to lowest, instead of the other way
around. The cases can be ordered in any way that makes sense, even nonsequentially. The switch statement
executes by taking the value of the integral expression inside the parentheses (assume that dayOfChristmas
is an int). The switch statement then compares the value of the integral expression to each case value.
When it finds a match, the code for that case begins to execute.
In this example, the switch statement helps us write the lyrics for the song The Twelve Days of Christmas.
For instance, if the dayOfChristmas equals 3, execution will begin at case 3 and continue until it encounters
the break at the end of case 1. The one break statement is necessary to avoid executing the default
error message. The result will be the lyrics for the third day of Christmas:
Three French hens
Two turtle doves
And a partridge in a pear tree

Here is the syntax for the switch statement:
switch( <integral expression> ) {
case value_one: <statement_one>
case value_two: <statement_two>
case value_three: <statement_three>
. . .
case value_n: <statement_n>
default: <statement_default>
}
The integral expression must evaluate to an integer value. This usually means that the integral expression
is an int or a char value. In particular, the expression cannot be a String (although that option would be
nice to have sometimes).
The statements can be compound statements, and in a “switch” from other syntax, compound statements
within a switch case need not be framed in curly brackets. However, if you like curly brackets, the Java
compiler will accept curly brackets around the compound statements.
The default case is optional, but we believe a default case should always be included, if only to
provide error checking. If your program expects the days of Christmas to vary between 1 and 12, it’s good
practice to put in a default statement which will let you know if the value of dayOfChristmas ever turns
up as some value other than 1 through 12. Especially with more complex programs, such default code could
save you many hours of debugging. Without the default statement, if none of the cases match the integral
expression, the JVM simply skips over all the switch code. Having the default case will catch the
anomalous condition and show you where the problem is.
Here is a complete program to print the words to the 12 verses of The Twelve Days of Christmas. The program
uses a while loop to iterate through the 12 verses. Then it uses an if-else statement to decide whether this
is the first verse or one of the later verses; that is necessary because the line about a partridge in a pear tree has
the word “And” in it for the 2nd through 12th verses, but not for the 1st verse. The \n at the end of the lines
having to do with a “partridge in a pear tree” is an example of an escape sequence. An escape sequence begins
with a backslash, and the following character has special meaning for the Java compiler. The \n means to insert
a linefeed, so that there will be a blank line between verses. There are other escape sequences for tabbing and
other functions, too.
Finally, this program illustrates how to add comments to a program written in Java. Any typing that follows
// on a line is treated as a comment; that is, the typing is ignored by the Java compiler. Also, any typing
between the characters /* and */ is also a comment, and such comments can extend over multiple lines. If
such a multiline comment begins with /**, it is a javadoc (Java documentation) comment, and will be included
by the javadoc processor in the automatically generated documentation of the program. Javadoc
comments can include special tags, such as @author, which the javadoc processor recognizes when it
generates the HTML format of the documentation.
We will not be describing the javadoc processor in any more detail in this chapter, but you can read
about javadoc comments here: http://java.sun.com/j2se/javadoc/. In our opinion, the javadoc processor is
one of the magnificent contributions Java has made to programming practice. The javadoc processor uses
comments within the programs themselves to generate attractive and complete documentation of every
class. Wonderful!
As a matter of programming style, I like to put a comment following closing curly braces that tells me
which block of code is being terminated. Particularly when many code blocks are nested within one another,
such comments help me keep track of my curly brackets. This style is a personal preference, not a standard.
Adopt it only if you wish.
/**
* A program to print the words to the Twelve Days of Christmas
* @author Carl Reynolds
*/
public class DaysOfChristmas {
public static void main(String args[]) {
int dayOfChristmas = 1; //start with the 1st day of Christmas
while( dayOfChristmas <= 12 ) {
if( dayOfChristmas == 1 )
{
System.out.println( "A partridge in a pear tree \n" );
}//if
else
{
switch( dayOfChristmas )
{
case 12: System.out.println( "Twelve drummers drumming" );
case 11: System.out.println( "Eleven pipers piping" );
case 10: System.out.println( "Ten lords a-leaping" );
case 9: System.out.println( "Nine ladies dancing" );
case 8: System.out.println( "Eight maids a-milking" );
case 7: System.out.println( "Seven swans a-swimming" );
case 6: System.out.println( "Six geese a-laying" );
case 5: System.out.println( "Five golden rings" );
case 4: System.out.println( "Four calling birds" );
case 3: System.out.println( "Three French hens" );
case 2: System.out.println( "Two turtle doves" );
System.out.println(
"And a partridge in a pear tree \n" );
break;
default: System.out.println( "?Day = " + dayOfChristmas );
}//switch
}//else
dayOfChristmas++;
}//while
System.out.println("The End" );
}//main
}//class

JAVA IDENTIFIERS

Every programming language has its rules for how to name elements of a program. In Java, names must
always begin with a letter. Letters in Java include all lowercase and uppercase letters, as well as the underscore
character “_” and the currency symbol “$”.
After the first letter, any number of letters and/or digits may follow. A Java identifier may be of any length,
and it is good programming practice to use names long enough to be self-descriptive. More experienced
programmers generally use longer variable names, because longer names usually make programs much easier
to read and maintain.
Java is a “case-sensitive” language. That means that Java recognizes uppercase and lowercase letters as
different. The identifier university is different from University, and both are different from
UNIVERSITY.
While one is not required to do so, standard programming practice is to begin all class names with an
uppercase letter, and to begin all other names with a lowercase letter. Also, when an identifier consists of more
than one word, the usual practice is to use what’s called “camel case” capitalization (it’s “humpy”). Here are
some example variable names:
highWindWarning
wonLostRecord
mothersMaidenName

JAVA OPERATORS

Operators are symbols in a language that stand for built-in functions. Java has a great many operators and,
since this chapter will only serve to introduce the Java language, we will not discuss them all. Here are the
operators we will discuss:
By assignment, we mean taking the value on the right side of the equal sign (sometimes called RS) and giving
that value to the variable on the left side of the equal sign (sometimes called LS). If the value of k is 5, after the
following statement is executed, the value of c will also be 5. Likewise, the value of k will remain 5 after execution:
c = k;
The arithmetic operators perform their expected functions. For example, if the value of a is 3, and the value
of b is 5, after the following statement executes the value of x will be 15:
x = a * b;
In contrast to some other languages, Java has no operator for exponentiation. If a programmer wants to raise
a number to some power, the program must perform the exponentiation either by repeatedly multiplying, or by
using the pow() method of the Math class which is part of the built-in Java library.
The ++ and -- operators are convenience operators that many programmers like because they save some
typing. The following two statements have the same effect:
m = m + 1;
m++;
In either case, the value of m will increase by 1. The -- operator works similarly, except that the value of
the variable will decrease by 1.
The rest of the operators in our list are logical operators. We use logical operators to test the truth of conditions
important to our programs. For example, if our program were going to find all the houses in a neighborhood
whose assessed values were greater than $200,000, our program might have a statement like this in it:
if ( assessedValue > 200000 ) {
We will discuss the use of if statements in the section on Java control structures, so for now simply
observe that the “>” operator allows one to test the truth of the condition that assessed value is greater than
$200,000. If the value of the variable assessedValue at the time the statement executes is greater that
200000, the logical operator “>” will return a value of true. Otherwise, it will return false.
We will discuss the other logical operators in the section on Java control structures. Remember, too, that
we have not discussed all Java operators. Java also has operators for testing and shifting bit values, conditional
statement execution, modulo arithmetic, and some other functions.

Thursday, May 5, 2011

How To Sniff VOIP Session Using Cain

According to wikipedia:


Voice over Internet Protocol (Voice over IP, VoIP) is one of a family of internet technologies, communication protocols, and transmission technologies for delivery of voice communications and multimedia sessions over Internet Protocol (IP) networks, such as the Internet. Other terms frequently encountered and often used synonymously with VoIP are IP telephony, Internet telephony, voice over broadband (VoBB), broadband telephony, and broadband phone.

Cain is an excellent software which can be used for sniffing a VOIP, There are couple of methods to sniff a VOIP session but in this tutorial I will explain you how you can use a Man in the Middle Attack with Cain and Abel to sniff a VOIP conversation.

Sniff VOIP Session With Cain

So here is how you can capture a VOIP session on your network:

Step 1 - First of all download Cain  and install it.

Step 2 - Once cain is successfully installed go ahead and launch it, Now launch the sniffer by clicking on a small green button just below the file option

Step 3 - Next click on the blue "+" at the top, choose "All hosts in my subnet" and click ok



Step 4 - This will show you all the active hosts on your network.



Step 5 - Next goto ARP tab at the bottom and press the blue "+" sign, select the hosts on which you want to you want to perform a man in the middle attack and click ok


Step 6 - Now just click on the little yellow "Microtoxic" button at the top to launch the ARP Poisoning attack which is the real name for Man in the middle attack..



Step 7 -  Next click VOIP tab at the bottom and if cain has captured a VOIP session, you will get similar results.


I hope you have enjoyed reading the post, I will write also write an article on protecting your VOIP sessions in the upcoming posts.