Friday, May 14, 2010

Java Exceptions

Exceptions

* ArithmeticException -

public class ArithmeticException extends RuntimeException

- Thrown when an exceptional arithmetic condition has occurred. For example, an integer "divide by zero" throws an instance of this class.

- ArithmeticException()
Constructs an ArithmeticException with no detail message.

-ArithmeticException(String s)
Constructs an ArithmeticException with the specified detail message.

* RuntimeException

public class ClassCastException extends RuntimeException

- Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. For example, the following code generates a ClassCastException:

Object x = new Integer(0);

System.out.println((String)x);
- ClassCastException()
Constructs a ClassCastException with no detail message.
-ClassCastException(String s)
Constructs a ClassCastException with the specified detail message.
* IndexOutOfBoundsException
public class IndexOutOfBoundsException extends RuntimeException

- Thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range.

- Applications can subclass this class to indicate similar exceptions.
- IndexOutOfBoundsException()
Constructs an IndexOutOfBoundsException with no detail message.
- IndexOutOfBoundsException(String s)
Constructs an IndexOutOfBoundsException with the specified detail message.
* NullPointerException
public class NullPointerException extends RuntimeException
- Thrown when an application attempts to use null in a case where an object is required. These include:
o Calling the instance method of a null object.
o Accessing or modifying the field of a null object.
o Taking the length of null as if it were an array.
o Accessing or modifying the slots of null as if it were an array.
o Throwing null as if it were a Throwable value.
- Applications should throw instances of this class to indicate other illegal uses of the null object.
- NullPointerException()
Constructs a NullPointerException with no detail message.
- NullPointerException(String s)
Constructs a NullPointerException with the specified detail message.
* FileNotFoundException

public class IOException extends Exception
- Signals that an I/O exception of some sort has occurred. This class is the general class of exceptions produced by failed or interrupted I/O operations.
* ConcurrentModificationException
- This exception may be thrown by methods that have detected concurrent modification of a backing object when such modification is not permissible, e. g. two threads modifying a HashMap simultaneously.
* NullPointerException
- Actually a null reference exception.
* StringIndexOutOfBoundsException
- Can be handled more generically with IndexOutOfBoundsException.
* NumberFormatException
- Commonly thrown when a String is converted to internal binary numeric format.
* ArrayStoreException
- Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects.

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.

[] SUPER CLASS
- Any class above a specific class in the class hierarchy.

[] SUB CLASS
- Any class below a specific class in the class hierarchy.

[] Benefits of Inheritance in OOP
- 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 method
- 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 superclassby providing a new implementation for that method.

[] Final Methods and Classes
- 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 subclass it belongs to.

[] 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.

[] Interfaces

- 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 WITH THE JAVA CLASS

[] Object-Oriented programming or OOP

– Revolves around the concept of objects as the basic elements of your programs.
– These objects are characterized by their properties and behaviors.



[] 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.


[] Class and Objects

[] Class

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



[]Class Variables

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

● To create an object or an instance of a class, we use the new operator.
● 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.



Methods

– is a separate piece of code that can be called by a main program or any other method to perform some specific function.

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



[] Method Declaration


- Return the character at the specified index. An index ranges from 0 to lenght()-1. The first character of the sequence is at index 0, the next at index1, and so on, as for array indexing.

[] 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

Introduction to Java Programming

A.) HISTORY

Java is a programming language originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation) and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities. Java applications are typically compiled to bytecode (class file) that can run on any Java Virtual Machine (JVM) regardless of computer architecture. Java is general-purpose, concurrent, class-based, and object-oriented, and is specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere". Java is considered by many as one of the most influential programming languages of the 20th century, and is widely used from application software to web applications.


B.) JAVA TECHNOLOGY

a.) PROGRAMMING LANGUAGE

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 programs that control the behavior of a machine, to express algorithms precisely, or as a mode of human communication.

b.) DEVELOPMENT ENVIRONMENT

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


designed to maximize programmer productivity by providing tightly-knit components with similar user interfaces. This should mean that the programmer has much less mode switching to do than when using discrete development programs.



c.) 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



d.) DEPLOYMENT ENVIRONMENT

There are two main deployment environments: First, 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. The other main deployment environment is on your web browser. Most commercial browsers supply a Java technology interpreter and runtime environment.


C.) JAVA FEATURES

a.) JAVA VIRTUAL MACHINE

enables a set of computer software programs and data structures to use a virtual machine 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.


b.) GARBAGE COLLECTION

relies on the observation that a previously allocated memory location that is no longer referenced by any pointers is no longer accessible to the application and is therefore reclaimable. The role of a garbage collector is to identify and recycle these inaccessible allocated memory chunks. There are two families of garbage collecting techniques -- reference counting and tracing.

Garbage collection thread :

– 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



c.) CODE SECURITY

Code security is attained in Java through the implementationof its Java Runtime Environment (JRE).

JRE– runs code compiled for a JVM and performs class loading (throughthe class loader), code verification (through the bytecode verifier)and finally code execution

Class Loader– responsible for loading all classes needed for the Java program– adds security by separating the namespaces for the classes of thelocal file system from those that are imported from network sources– After loading all the classes, the memory layout of the executable isthen determined. This adds protection against unauthorized accessto restricted areas of the code since the memory layout isdetermined during runtime

Bytecode verifier– tests the format of the code fragments and checks the codefragments for illegal code that can violate access rights to objects


D.) PHASES OF JAVA PROGRAM

a.) WRITE

The easiest way to write a simple program is with a text editor. So, using the text editor of your choice, create a text file with the following text, and be sure to name the text file ExampleProgram.java. Java programs are case sensitive, so if you type the code in yourself, pay particular attention to the capitalization.

b.) COMPILE

A program has to be converted to a form the Java VM can understand so any computer with a Java VM can interpret and run the program. Compiling a Java program means taking the programmer-readable text in your program file (also called source code) and converting it to bytecodes, which are platform-independent instructions for the Java VM.


c.) RUN

Once your program successfully compiles into Java bytecodes, you can interpret and run applications on any Java VM, or interpret and run applets in any Web browser with a Java VM built in such as Netscape or Internet Explorer. Interpreting and running a Java program means invoking the Java VM byte code interpreter, which converts the Java byte codes to platform-dependent machine codes so your computer can understand and run the program.


C.) The Difference between Java Application and Java Applet

[] Java Application

Java applications have the majority of differences with the java applets. If we talk at the source code level, then we don't extend any class of the standard java library that means we are not restricted to use the already defined method or to override them for the execution of the program. Instead we make set of classes that contains the various parts of the program and attach the main method with these classes for the execution of the code written in these classes. The following program illustrate the structure of the java application.

[]Java applet

is an applet delivered to the users in the form of Java bytecode. Java applets can run in a Web browser using a Java Virtual Machine (JVM), or in Sun's AppletViewer, a stand-alone tool for testing applets. Java applets were introduced in the first version of the Java language in 1995. Java applets are usually written in the Java programming language but they can also be written in other languages that compile to Java bytecode such as Jython


D.) What makes Java an Object Oriented Programming Language

Java is considered as an object oriented programming language because it uses "objects" – data structures consisting of datafields and methods together with their interactions – to design applications and computer programs. Java includes features such as data abstraction, encapsulation, modularity, polymorphism, and inheritance.

Even though Java has the look and feel of C++, it is a wholly independent language which has been designed to be object-oriented from the ground up. In object-oriented programming (OOP), data is treated as objects to which methods are applied. Java's basic execution unit is the class. Advantages of OOP include: reusability of code, extensibility and dynamic applications.





Topicz that have been discuss in JAVA Programming1

Brief History of Java1

[] is a programming language originally developed by James Gosling at Sun MicrosystemsOracle Corporation) and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities. Java applications are typically compiledbytecode (class file) that can run on any Java Virtual Machine (JVM) regardless of computer architecture. Java is general-purpose, concurrent, class-based, and object-oriented, and is specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere". Java is considered by many as one of the most influential programming languages of the 20th century, and is widely used from application software to web applications.



Java Programming Structures

[]Control Stucture

Control structures are a dynamic part of Java and come in several types: sequences, subprograms, selection statements, and loops.


[]Selection Structure

Also known as branch, conditional or decision structures, selections allow the program to execute different operations depending on events or conditions. This entails the use of the switch-case statement and the classic If-Then-Else statement.

With its roots in classic mathematics, the if-then-else is used in Java to quantify simple decisions under certain conditions. If something occurs, do this; else, do something different. The simplest form the selection statement can take is just the if-then statement:

if (testVar){

//Commands to execute

}

[]Sequential Structure

A sequence in Java is basically a list of commands that computer executes in order from beginning to end. Most small daily activities are sequential, such as cooking a meal or brushing teeth. A computer, like a human, finds sequential operations to be the simplest and as such the sequence is the default structure for Java programs


[]Repetition Structure

The Repetition Structure simply means to repeat or to loop certain pieces of code. Every loop requires an evaluation or else it will result in an endless loop; at some point the condition must test false in order to exit the loop.