Java Programming 2

Java Exceptions

Friday, May 14, 2010

0 comments  

1.Arithmetic Exception -These Exception occurs, when you divide a number by zero causes an Arithmetic Exception
2.Class Cast Exception -These Exception occurs, when you try to assign a reference variable of a class to an incompatible reference variable of another class
3.Array Store Exception -These Exception occurs, when you assign an array which is not compatible with the data type of that array
4.Array Index Out Of Bounds Exception -These Exception occurs, when you assign an array which is not compatible with the data type of that array
5.Null Pointer Exception -These Exception occurs, when you try to implement an application without referencing the object and allocating to a memory
6.Number Format Exception -These Exception occurs, when you try to convert a string variable in an incorrect format to integer (numeric format) that is not compatible with each other
7.ClassNotFoundException -This Exception occurs when Java run-time system fail to find the specified class mentioned in the program.
8.Instantiation Exception -This Exception occurs when you create an object of an abstract class and interface
9.Illegal Access Exception -This Exception occurs when you create an object of an abstract class and interface
10.Not Such Method Exception -This Exception occurs when the method you call does not exist in class
11.Negative ArraySizeException -These are Exception, when you declare an array of negative size.
12. Try-catch-finally block
Key aspects about the syntax of the try-catch-finally construct:
– The block notation is mandatory.
– For each try block, there can be one or more catch blocks, but only one finally block.
– The catch blocks and finally blocks must always appear in conjunction with the try block, and in the above order.
– A try block must be followed by AT LEAST one catch block OR one finally block, or both.
– Each catch block defines an exception handle. The header of the catch block takes exactly one argument, which is the exception its block is willing to handle. The exception must be of the Throwable class or one of its subclasses.

Inheritance, Polymorphism, Interface

Thursday, April 22, 2010

0 comments  

Inheritance
In Java, all classes, including the classes that make up the Java API, are subclassed from the Object superclass.
Supper Class
It is any class above a specific class in the class hierarchy.
Subclass
Any class below a specific class in the class hierarchy.
Benefits of Inheritance
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.
Sample Code
public class Person {
:
:
public String getName(){
System.out.println("Parent: getName");
return name;
}
}
Final Methods and Classes
Final Classes–Classes that cannot be extended–To declare final classes, we write,public final ClassName{. . . }
Other examples of final classes are wrapper classes and Strings.
public final class Person { . . . }
Final Methods–Methods that cannot be overridden–
To declare final methods, we write,
public final [returnType] [methodName]([parameters]){. . .}
Static methods are automatically final.
ExampleCode:
public final String getName(){
return name;
}
Polimorphism
It is 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.
In Java, we can create a reference that is of type superclass to an object of its subclass.
ExampleCode:
public static main( String[] args ) {
Person ref;
Student studentObject = new Student();
Employee employeeObject = new Employee();
ref = studentObject; //Person reference points to a // Student object
}
Abstrac Classes
It is 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.
Abstract Methods
Are methods in the abstract classes that do not have implementation–To create an abstract method, just write the method declaration without the body and use the abstract keyword
Interface
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.

Working with the Java Class

Monday, April 19, 2010

0 comments  

Object-Oriented Programming
Object-oriented programming (OOP) 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.[citation needed] Many modern programming languages now support OOP.
Object-oriented programming has roots that can be traced to the 1960s. As hardware and software became increasingly complex, manageability often became a concern. Researchers studied ways to maintain software quality and developed object-oriented programming in part to address common problems by strongly emphasizing discrete, reusable units of programming logic.

Encapsulation
In programming, the process of combining elements to create a new entity. For example, a procedure is a type of encapsulation because it combines a series of computer instructions. Likewise, a complex data type, such as a record or class, relies on encapsulation. Object-oriented programming languages rely heavily on encapsulation to create high-level objects. Encapsulation is closely related to abstraction and information hiding.

Classes and Objects
Objects

In the "real" world, objects are the entities of which the world is comprised. Everything that happens in the world is related to the interactions between the objects in the world. Just as atoms, which are objects, combine to form molecules and larger objects, the interacting entities in the world can be thought of as interactions between and among both singular ("atomic") as well as compound ("composed") objects. The real world consists of many, many objects interacting in many ways. While each object may not be overly complex, their myriad of interactions creates the overall complexity of the natural world. It is this complexity that we wish to capture in our software systems.

Class Variables
Also known as static variables, these are any variables (properties) that are associated with a class, and not an object instance. There is always only one copy of a class variable, regardless of the number of object instances that are created from that class. Class variables do not use the prototype object to implement inheritance. You access a class variable directly through the class, and not through an object instance; you must define a class in a constructor function before you can define class variables.

Classes


Many objects differ from each other only in the value of the data that they hold. For example, both a red crayon and a blue crayon are crayons; they differ only in the value of the color attribute, one has a red color and the other a blue color. Our object-oriented system needs a way to capture the abstraction of a crayon, independent of the value of its color. That is, we want to express that a set of objects are abstractly equivalent, differing only in the values of their attributes and perhaps, thus differing in the behaviors that result from those values.

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.
Method Declaration
It provides a lot of information about the method to the compiler, the runtime system and to other classes and objects. Besides the name of the method, the method declaration carries information such as the return type of the method, the number and type of the arguments required by the method, and what other classes and objects can call the method.

Static Methods

A static method is a method which accepts arguments instead of using instance varuables.

The opposite of a static method is an instance method.

The default for a method is to be an instance method. Methods must be explicitly defined as static methods.

A static method is also referred to as a class method.



Parameter Passing
Pass-by-Value

When you use pass-by-value, the compiler copies the value of an argument in a calling function to a corresponding non-pointer or non-reference parameter in the called function definition. The parameter in the called function is initialized with the value of the passed argument. As long as the parameter has not been declared as constant, the value of the parameter can be changed, but the changes are only performed within the scope of the called function only; they have no effect on the value of the argument in the calling function.

In the following example, main passes func two values: 5 and 7. The function func receives copies of these values and accesses them by the identifiers a and b. The function func changes the value of a. When control passes back to main, the actual values of x and y are not changed.

/**
** This example illustrates calling a function by value
**/

#include

void func (int a, int b)
{
a += b;
printf("In func, a = %d b = %d\n", a, b);
}

int main(void)
{
int x = 5, y = 7;
func(x, y);
printf("In main, x = %d y = %d\n", x, y);
return 0;
}

The output of the program is:

In func, a = 12 b = 7
In main, x = 5 y = 7

Pass-by-Reference

Passing by by reference refers to a method of passing the address of an argument in the calling function to a corresponding parameter in the called function. C onlyIn C, the corresponding parameter in the called function must be declared as a pointer type. C++ only In C++, the corresponding parameter can be declared as any reference type, not just a pointer type.

In this way, the value of the argument in the calling function can be modified by the called function.

The following example shows how arguments are passed by reference. In C++, the reference parameters are initialized with the actual arguments when the function is called. In C, the pointer parameters are initialized with pointer values when the function is called.

C++ only
#include 

void swapnum(int &i, int &j) {
int temp = i;
i = j;
j = temp;
}

int main(void) {
int a = 10;
int b = 20;

swapnum(a, b);
printf("A is %d and B is %d\n", a, b);
return 0;
}
End of C++ only
C only
#include 

void swapnum(int *i, int *j) {
int temp = i;
i = j;
j = temp;
}

int main(void) {
int a = 10;
int b = 20;

swapnum(&a, &b);
printf("A is %d and B is %d\n", a, b);
return 0;
}

Introduction to Java Programming

Wednesday, April 14, 2010

0 comments  



History


Java is a high-level object-oriented programming language developed by the Sun Microsystems. Though it is associated with the World Wide Web but it is older than the origin of Web. It was only developed keeping in mind the consumer electronics and communication equipments. It came into existence as a part of web application, web services and a platform independent programming language in the 1990s.


Earlier, C++ was widely used to write object oriented programming languages, however, it was not a platform independent and needed to be recompiled for each different CPUs. A team of Sun Microsystems including Patrick Naughton, Mike Sheridan in the guidance of James Goslings decided to develop an advanced programming language for the betterment of consumer electronic devices. They wanted to make it new software based on the power of networks that can run on different application areas, such as computers and electronic devices. In the year 1991 they make platform independent software and named it Oak. But later due to some patent conflicts, it was renamed as Java and in 1995 the Java 1.0 was officially released to the world.
Java is influenced by C, C++, Smalltalk and borrowed some advanced features from some other languages. The company promoted this software product with a slogan named “Write Once Run Anywhere” that means it can develop and run on any device equipped with Java Virtual Machine (JVM). This language is applicable in all kinds of operating systems including Linux, Windows, Solaris, and HP-UX etc.





Java technology


Since 1995, Java has changed our world . . . and our expectations..
Today, with technology such a part of our daily lives, we take it for granted that we can be connected and access applications and content anywhere, anytime. Because of Java, we expect digital devices to be smarter, more functional, and way more entertaining.
In the early 90s, extending the power of network computing to the activities of everyday life was a radical vision. In 1991, a small group of Sun engineers called the "Green Team" believed that the next wave in computing was the union of digital consumer devices and computers. Led by James Gosling, the team worked around the clock and created the programming language that would revolutionize our world – Java.
The Green Team demonstrated their new language with an interactive, handheld home-entertainment controller that was originally targeted at the digital cable television industry. Unfortunately, the concept was much too advanced for the them at the time. But it was just right for the Internet, which was just starting to take off. In 1995, the team announced that the Netscape Navigator Internet browser would incorporate Java technology.
Today, Java not only permeates the Internet, but also is the invisible force behind many of the applications and devises that power our day-to-day lives. From mobile phones to handheld devises, games and navigation systems to e-business solutions, Java is everywhere!


Java features
The Java Virtual Machine●Java Virtual Machine (JVM)–an imaginary machine that is implemented by emulating software on a real machine–provides the hardware platform specifications to which you compile all Java technology code●Bytecode–a special machine language that can be understood by the Java Virtual Machine (JVM)–independent of any particular computer hardware, so any computer with a Java interpreter can execute the compiled Java program.
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
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
●Class Loader–responsible for loading all classes needed for the Java program–adds security by separating the namespaces for the classes of the local file system from those that are imported from network sources–After loading all the classes, the memory layout of the executable is then determined. This adds protection against unauthorized access to restricted areas of the code since the memory layout is determined during runtime
Bytecode verifier–tests the format of the code fragments and checks the code fragments for illegal code that can violate access rights to objects
Phases of java program

Phase Purpose Tasks
1
Planning
Prepare log sheets
Record estimates for time in each phase
Record planning time in the time recording log
2
Requirements
Study and understand the requirements in detail
Determine the exact formats for input and output, and any command line parameters.
Record requirements time in the time recording log
3
Design
Think about the algorithms you will use
Think about the program design
Record design time in the time recording log
4
Code
Implement the design
type in the code
Record coding time in the time recording log
5
Compile
Compile the program
Fix all defects found
Record compile time in the time recording log
6
Test
Develop test cases
Test the program
Debug defects
Fix all defects found
Record testing time in the time recording log
7
Performance
Count lines of code
Develop performance test cases
Execute and record performance
Record performance time in the time recording log
8
Postmortem
Complete the project plan summary form with actual time spent
Think about the experience, and write a brief report
Record postmortem time in the time recording log




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.
What makes a Java an Object Oriented Programming Language