Friday, May 14, 2010

Java Exceptions

An exception

– is an event that interrupts the normal processing flow of a program. This event is usually some error of some sort.
– This causes our program to terminate abnormally.

Java Exceptions:
1.) ArithmeticException
2.) CollectionException
3.) ArrayIndexOutOfBoundsException
4.) ClassNotFoundException
5.) IOException
6.) FileNotFoundException
7.) ArrayListException
8.) NumberFormatException
9.) FontFormatException
10.) NullPointerException

Thursday, April 22, 2010

Inheritance, Polymorphism, Interface

Inheritance

☺In Java, all classes, including the classes that make up the Java API, are subclassed from the Object superclass.
  • Superclass– Any class above a specific class in the class hierarchy.

  • Subclass– Any class below a specific class in the class hierarchy.

Benefits of Inheritance in OOP : Reusability - Once a behavior (method) is defined in a superclass, that behavior is automatically inherited by all subclasses. – Thus, you can encode a method only once and they can be used by all subclasses. – A subclass only needs to implement the differences between itself and the parent.

Overriding Methods - If for some reason a derived class needs to have a different implementation of a certain method from that of the superclass, overriding methods could prove to be very useful. A subclass can override a method defined in its superclass by providing a new implementation for that method.

To override, the getName method of the superclass Person, we write in the subclass Student,

public class Student extends Person{
:
:
public String getName(){
System.out.println("Student: getName");
return name;
}
:
}

Now, when we invoke the getName method of an object of the subclass Student, the overridden getName method would be called, and the output would be,

Student: getName

Final Classes
– Classes that cannot be extended

– To declare final classes, we write,

public final ClassName{
. . .
}

Example:
public final class Person {
. . .
}

Other examples of final classes are your wrapper classes and Strings.

Final Methods
– Methods that cannot be overridden
– To declare final methods, we write,

public final [returnType] [methodName]([parameters]){
. . .
}

Static methods are automatically final.

Polymorphism
– The ability of a reference variable to change behavior according to what object it is holding.
– This allows multiple objects of different subclasses to be treated as objects of a single superclass, while automatically selecting the proper methods to apply to a particular object based on the subclassit belongs to. To illustrate polymorphism, let us discuss an example.

☺Given the parent class Person and the subclass Student of the previous examples, we add another subclass of Person which is Employee.

Abstract class
– a class that cannot be instantiated.
– often appears at the top of an object-oriented programming class hierarchy, defining the broad types of actions possible with objects of all subclasses of the class.

An interface
– is a special kind of block containing method signatures (and possibly constants) only.
– defines the signatures of a set of methods, without the body.
– defines a standard and public way of specifying the behavior of classes.
– allows classes, regardless of their locations in the class hierarchy, to implement common behaviors.
– NOTE: interfaces exhibit polymorphism as well, since program may call an interface method, and the proper version of that method will be executed depending on the type of object passed to the interface method call.

Monday, April 19, 2010

Working w/ the Java Class

Object Oriented Programming - is a programming paradigm that uses "objects" – data structures consisting of datafields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction, encapsulation, modularity, polymorphism, and inheritance. It was not commonly used in mainstream software application development until the early 1990s.

Encapsulation - the method of hiding certain elements of the implementation of a certain class.
– By placing a boundary around the properties and methods of our objects, we can prevent our programs from having side effects wherein programs have their variables changed in unexpected ways.

Classes and Objects - can be thought of as a template, a prototype or a blueprint of an object
– is the fundamental structure in object-oriented programming

• Two types of class members:
– Fields (properties or attributes)
• specify the data types defined by the class
– Methods.
• specify the operations

Object - is composed of a set of data (properties) which are variables describing the essential characteristics of the object, and consists of a set of methods (behavior) that describes how an object behaves.
– An object is an instance of a class.

Classes provide the benefit of reusability.
• Software programmers can use a class over and over again
to create many objects.

Class Variable - a class variable is a variable defined in a class (i.e. a member variable) of which a single copy exists, regardless of how many objects of the class exist.

Classes consist of
– Instance variables
– Instance methods
– Class Variables (static member variables)
•variables that belong to the whole class.
•This means that they have the same value for all the objects in the same class.

•Class Instantiation - the process of creating objects from a class is called instantiation. So an object is always an instance of a class which represents the blueprint.
The object is constructed using the class and must be created before being used in a program.
Objects are manipulated through object references (also called reference values or simply references)

•The new operator
– allocates a memory for that object and returns a reference of that
memory location to you.
– When you create an object, you actually invoke the class'
constructor.
•The constructor
– is a method where you place all the initializations, it has the same
name as the class.

Method - A Java method is a set of Java statements which can be included inside a Java class.

Java methods are similar to functions or procedures in other programming languages.

•The following are characteristics of methods:
– It can return one or no values
– It may accept as many parameters it needs or no parameter at all.
Parameters are also called arguments.
– After the method has finished execution, it goes back to the method
that called it.

Every Java program must have one main() method.

Here is the main() method from a Java program which prints "Hello World":

public static void main (String[] args) {
// This Java program prints "Hello World!"
System.out.println{"Hello World!");
}

Method Declaration - a method declaration is the heading of a method containing the name of the method, its parameters, and its access level. The method heading in Java is organized as such:

[access keywords] [return type] [method name] ( [parameters separated by commas] )

for instance:

public String toString(); is public (accessible by any class), returns a String, is called toString, and takes no parameters.

Other features could be added to the method declaration for a more specialized method such as static (method could be called without an object of that class), native (implemented using the native code, usually what C has already done, i.e. square root, power etc.).

Static Methods - methods that can be invoked without instantiating a class (means without invoking the new keyword).
– Static methods belong to the class as a whole and not to a certain instance (or object) of a class.
– Static methods are distinguished from instance methods in a class definition by the keyword static.
• To call a static method, just type,
Classname.staticMethodName(params);

●Parameter Passing
Pass-by-Value
when a pass-by-value occurs, the method makes a copy of the value of the variable passed to the method. The method cannot accidentally modify the original argument even if it modifies the

parameters during calculations.
– all primitive data types when passed to a method are pass-by-value.

Pass-by-Reference – When a pass-by-reference occurs, the reference to an object is passed to the calling method. This means that, the method makes a copy of the reference of the variable passed to the method.
– However, unlike in pass-by-value, the method can modify the actual object that the reference is pointing to, since, although different references are used in the methods, the location of the data they are pointing to is the same.

Wednesday, April 14, 2010

1.)Topics in JAVA 1

Methods of getting input from keyboard:
1.)JOptionPane - use to get input from keyboard using a dialog box and found in javax.swing package.
ex:
To get input from keyboard:
num = JOptionPane.showInputDialog("Enter a number: ");
a = Integer.parseInt(num);

To output the result:
JOptionPane.showMessageDialog(null, "Num = " +a);

2.)BufferedReader - use to get output input from keyboard using the command prompt and found in java.io package.
ex:
BufferedReader dataIn = new BufferedReader ( new InputStreamReader ( System.in) );
System.out.print("Enter First test Score: ");
try{
x = dataIn.readLine();
}catch( IOException e){
System.out.println(“Error in getting input”);
}

2 Kinds of Control Structure:
1.)Decision Control Structure - Java statements that allows us to select and execute specific blocksof code while skipping other sections.
– if-statement
– if-else-statement
– If-else if-statement


2.)Repetition Control Structure - are Java statements that allows us to execute specific blocks of code a number of times.
– while-loop
– do-while loop
– for-loop

Java Arrays - an array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.

To declare an array write the data type, followed by a set of square brackets[], followed by the identifier name.

ex:
int []ages;
or
int ages[];

Applet - is a special type of java program that is executed via internet.
Applets Life Cycle:
1.) init()
•First method called when the applet is loaded
2.) start()
Next method called after init
Invoked everytime the applet’s HTML document and the applet itself is displayed
3.)stop()
Called when the web browser leaves the applet’s HTML document
Inform the applet that it should stop its execution
4.)destroy()
Called when the applet needs to be removed from the memory completely
The stop method is always called before this method is invoked

Event Handling
Event Listeners
ActionListener Method
MouseListener Methods
MouseMotionListener Methods
WindowListener Methods
Guidelines for Creating Applications Handling GUI Events

To read input data, by default we use the computer keyboard. However, some of the data we need maybe stored in some data file. For example, if you have a class record stored in a file and you want to retrieve it, or simply want to read a text file using your java program.


Reading from a file:

The FileInputStream class allows you to read data from a file.

The class has the following constructors:

o FileInputStream(File file)
Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system.

o FileInputStream(FileDescriptor fdObj)
Creates a FileInputStream by using the file descriptor fdObj, which represents an existing connection to an actual file in the file system.

o FileInputStream(String name)
Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system.


2.) Introduction to JAVA Programming

a.) History
James Gosling initiated the Java language project in June 1991 for use in one of his many set-top box projects. The language, initially called Oak after an oak tree that stood outside Gosling's office, also went by the name Green and ended up later renamed as Java, from a list of random words. Gosling aimed to implement a virtual machine and a language that had a familiar C/C++ style of notation.

b.) JAVA Technology
  • Programming Language - a programming language is an artificial language designed to express computations that can be performed by a machine, particularly a computer. Programming languages can be used to create <>that control the behavior of a machine, to express algorithms precisely, or as a mode of human communication.

  • Development Environment - in integrated development environment (IDE) also known as integrated design environment or integrated debugging environment is a software application that provides comprehensive facilities to computer programmers for software development.

  • Application Environment - java technology applications are typically general-purpose
    programs that run on any machine where the Java runtime
    environment (JRE) is installed.
There are two main deployment environments:
1. The JRE supplied by the Java 2 Software Development Kit (SDK) contains the complete set of class files for all the Java technology packages, which includes basic language classes, GUI component classes, and so on.
2. The other main deployment environment is on your web browser. Most commercial browsers supply a Java technology interpreter and runtime environment.
  • Deployment Environment - as a development environment, Java technology provides
    you with a large suite of tools:
- a compiler - an interpreter - a document generator - a class file packaging tool

c.) JAVA Features

  • Java Virtual Machine - a Java Virtual Machine (JVM) enables a set of computer software programs and data structures to use a model for the execution of other computer programs and scripts. The model used by a JVM accepts a form of computer intermediate language commonly referred to as Java bytecode. This language conceptually represents the instruction set of a stack-oriented, capability architecture. has claimed there are over 4.5 billion JVM-enabled devices.
  • Garbage Collection - responsible for freeing any memory that can be freed. This happens automatically during the lifetime of the Java program.
    –programmer is freed from the burden of having to deallocate that memory themselves.
  • Code Security - Code security is attained in Java through the implementation of its Java Runtime Environment (JRE).
    JRE – runs code compiled for a JVM and performs class loading (through the class loader), code verification (through the bytecode verifier)
    and finally code execution.
d.) Phases of Java Programming

e.) Difference between JAVA application and JAVA applets

In simple terms, an applet runs under the control of a browser, whereas an application runs stand-alone, with the support of a virtual machine. As such, an applet is subjected to more stringent security restrictions in terms of file and network access, whereas an application can have free reign over these resources.

Applets are great for creating dynamic and interactive web applications, but the true power of Java lies in writing full blown applications. With the limitation of disk and network access, it would be difficult to write commercial applications (though through the user of server based file systems, not impossible). However, a Java application has full network and local file system access, and its potential is limited only by the creativity of its developers.

f.) What makes JAVA an object oriented programming language?

Java is called an Object Oriented Programming Language because many of the object oriented programming concepts are implemented in Java.

Some concepts are:
1. Class
2. Object
3. Inheritance
4. Encapsulation
5. Polymorphism
6. Abstraction