MY mENU


Friday 10 February 2012

Android Architecture

Android Architecture: The following diagram shows the major components of the Android operating system. 



1. Linux Kernel:-   Linux version provides more security, memory management, process management, network stack, and driver model. The kernel is also part the OS that  acts as an abstraction layer between the hardware and the rest of the software stack.

2.Android Runtime:-
       -
Every Android application runs in its own process, with its own instance of the Dalvik virtual machine.
         - Dalvik has been written so that a device can run multiple VMs efficiently.The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint.
         -The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included "dx" tool.
       -
Android includes a set of core libraries that provides most of the functionality.

3. Libraries :- Android includes a set of C/C++ libraries used by various components of the Android system.

 Some of the core libraries are listed below:-

 Media Libraries - based on PacketVideo's OpenCORE; the libraries support playback and recording of many popular audio and video formats, as well as static image files, including MPEG4, H.264, MP3, AAC, AMR, JPG, and PNG.

Surface Manager - manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers from multiple applications.

LibWebCore - a modern web browser engine which powers both the Android browser and an embeddable web view.

3D libraries - an implementation based on OpenGL ES 1.0 APIs; the libraries use either hardware 3D acceleration (where available) or the included, highly optimized 3D software rasterizer.


FreeType - bitmap and vector font rendering.

SQLite -
a powerful and lightweight relational database engine available to all applications.

System C library - a BSD-derived implementation of the standard C system library (libc),tuned for embedded Linux-based devices

4.Application Framework :-

Android provides an open development platform, So Developers have full access to the same framework APIs used by the core applications. Developers are free to take advantage of the device hardware, access location information, run background services, set alarms, add notifications to the status bar, and much, much more.

Underlying all applications is a set of services and systems, including:

 - A rich and extensible set of Views that can be used to build an application, including lists, grids, text boxes, buttons, and even an embeddable web browser.
 - Content Providers that enable applications to access data from other applications (such as Contacts), or to share their own data
 - A Resource Manager, providing access to non-code resources such as localized strings, graphics, and layout files
 - A Notification Manager that enables all applications to display custom alerts in the status bar
 - An Activity Manager that manages the lifecycle of applications and provides a common navigation backstack.

5. Applications :-
    Android will ship with a set of core applications including an email client, SMS program, calendar, maps, browser, contacts, and others. All applications are written using the Java programming language.

Android Application Life Cycle

Android Application Lifecycle :- In Android, the applications are run as a separate Linux process. So the application lifecycle is closely related to the process lifecycle. The application process lifecycle is handled by the system depending on the current system memory state.


In case of low memory, the Android system kills some less important process. The process importance is decided depending on the state of the process components.

The process types depending on the importance are as follows :-

1. Foreground process:- A foreground process is the application process with which the user is currently interacting. The process is considered to be foreground if its Activity is at the top of the Activity stack or its Service is executing callback functions like onCreate(), onStart() or onDestroy() methods.
2. Visible Process:- A visible process is the process which has an Activity visible to the user (
3. Service Process:- Service process contains a Service for which startService method is called and the service is running.
4. Background Process:- The background process does not have any visible activities to the          user.
5. Empty Process:- Empty process is the one that does not have any active application components. These processes are kept on for caching purpose.

It is important that application developers understand lifecycle of the application process. Not using these correctly can result in the system killing the application’s process while it is doing important work.


Advantages of C

    Advantages Of C     
     1. C is a small , efficient ,powerful and flexible language
     2. C is close to computer H/W (architecture).
     3. C is standardized, making it more portable compare to other languages.
     4. It contains libraries.
     5. Many other languages borrow from Csyntax for ex: Java, java script, perl.
     6. UNIX was written in C.

   
Dis Advantages Of C:


     1. C is designed for professional users.

     2. C was not able to automatic checking compare other languages.
     3. C does not support modern concept like OOP’s and multithreading.




A sample of C Program
      
      #include <stdio.h>     // Preprocessor
        main ()                // main function
      {                      // opening the brackets
      Printf(“Hello”);
       }                      // close the brackets
.
    

C Introduction


Introduction of C
     C is programming language developed in the  at AT and Tee Bell Laboratories of USA  in 1972's. It was designed and developed by man named  Dennis Richte. C is so popular  because it reliable and  simple and easy to use, with the help of C language new languages are born known as C++, Java, C#  and many other languages.



History Of C
     Before using C we were using language which is known as B, now what is B: it was on Interpreter based and had performance drawbacks.So Dennis Ritchie developed language known as C in 1972’s. And it was famous as Mother Language of the computer system. It was based on compiler.Strong Point as compare to B : In C language Compiler (Translator) compiles the whole source code to Machine code where as interpreter read the source code line by line or step by step.
Features of C
1. C language is the structured programming language because it has some standards.
2. Code reusability means we can use the code from environment to other environment.
3. Built in type float, int etc expressions, operators.
4. Syntax for decision control.
5. It has some libraries which pre is defined.(preprocessors).
6. File organization (.c, .cpp etc)


Android Installation Steps

Downloading Android Starter package :
 download the Android Starter package. You can get the latest version of the SDK starter package from the Link - http://developer.android.com/sdk/index.html
-After downloading, unpack the Android SDK archive.
-Make a note of the name and location of the unpacked SDK directory on your system
-you will need to refer to the SDK directory later, when setting up the ADT plugin or when using the
SDK tools.
- On Windows, right-click on My Computer, and select Properties. Under the Advanced tab, hit the Environment Variables button, and in the dialog that comes up, double-click on Path (under System Variables). Add the full path to the tools/ directory to the path. 


2. Installing the ADT plug-in  
ADT has been created for Android to ease the development of applications using an integrated system for development, compiling and signing and transferring to an android device.  It helps us quickly integrate java code with Android API and create applications with it. ADT installation as described in the steps below.
1. Start Eclipse, then select Help > Install New Software.
2. In the Available Software dialog, click Add....
3. In the Add Site dialog that appears, enter a name for the remote
site (for example, "Android Plugin") in the "Name" field.
In the "Location" field, enter this URL: https://dl-ssl.google.com/android/eclipse/ .If you have trouble acquiring the plugin, you can try using "http" in the URL, instead of "https" (https is preferred for security reasons. Click OK. 
4. Back in the Available Software view, you should now see "Developer Tools" added to the list. Select the checkbox next to Developer Tools, which will automatically select the nested tools Android DDMS and Android Development Tools. Click Next.
5. In the resulting Install Details dialog, the Android DDMS and Android Development Tools features are listed. Click Next to read and accept the license agreement and install any dependencies, then click Finish.
6. Restart Eclipse.

3. Configuring the ADT Plugin 
              Once you've downloaded ADT the next step is to modify your ADT preferences in Eclipse to point to the Android SDK directory:
1. Select Window > Preferences... to open the Preferences panel
(Mac OS X: Eclipse > Preferences).
2. Select Android from the left panel.
3. For the SDK Location in the main panel, click Browse... and
locate your downloaded SDK directory.
4. Click Apply, then OK. Adding Android platform.
The last step is to use AVD manager to install various components
into you development environment.
5. Launching from Eclipse/ADT
If you are developing in Eclipse and have already installed the ADT Plugin, follow these steps to access the Android SDK and AVD Manager tool:
1. Open Eclipse
2. Select Window > Android SDK and AVD Manager.
3. Select Available Packages in the left panel. This will reveal all of the components that are currently available for download from the SDK repository.

4. Select the component(s) you'd like to install and click Install Selected.
5. Verify and accept the components you want and click Install Accepted. The components will now be installed into your existing Android SDK directories.
New platforms are automatically saved into the <sdk>/platforms/ directory of your SDK; new add-ons are saved in the <sdk>/add-ons/ directory; samples are saved in the <sdk>/samples/android-<level>/;
and new documentation is saved in the existing <sdk>/docs/ directory (old docs are replaced).

Google Map In Android Application


Android Google Maps Application
  • To integrate with Google maps application you need to apply for a free Google map API Key.
  • To get the Google Map API Key you need to sign up for the Android Maps API.
  • To sign up, you will need to provide the certificate's fingerprint (MD5).
  • If you have a certificate fingerprint (MD5) you can sign up here and get the API Key.
To get certificate fingerprint (MD5) follow the simple steps below:
  • You need to get the keystore file for getting the certificate fingerprint (MD5).
  • Your keystore file can be found at the following path
"C:\Documents and Settings\<username>\Local Settings\Application Data\Android"
(Or)
"C:\Documents and Settings\<username>\.android"
  • Keystore file name is "debug.keystore" file.
  • Copy the "debug.keystore" file to some other folder (ex: - "D:\Androidkeystore\") (its user friendly to use).
  • Open command Prompt and go to the Java installed directory. ("C:\Program Files\Java\<JDK_version_number>\bin")
  • Then type the below line (given in box) and press enter.
keytool.exe -list -alias androiddebugkey -keystore "D:\AndroidKeystore\debug.keystore" -storepass android -keypass android
Now you will get a certificate fingerprint (MD5). (see the below image).
getmd5certificate
Here the MD5 certificate fingerprint is"64:88:A2:FC:AA:9F:B1:B0:CA:E4:D0:24:A8:1E:77:FB"
Enter the MD5 certificate fingerprint in the textbox and get the API Key (see below image)
signupformapapikey
After clicking the Generate API Key Button , you will get Google Map API Key (red circled).
getxmlcodeformap
Now the sample xml layout code to use the Google map application in Android is as specified below
Coding:-
To use Google map in your application, you need to add <uses-library> element together with the <uses- permission> in AndroidManifest.xml file
Now your AndroidManifest.xml code looks like
<?xml version="1.0? encoding="utf-8??>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pack.sample.map"
android:versionCode="1?
android:versionName="1.0?>
<application android:icon="@drawable/icon" android:label="@string/app_name">
<uses-library android:name="com.google.android.maps" />
<activity android:name=".SampleMapApplication"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
To display map in your application, modify the main.xml file. It is located in <project-folder>/res/layout.
Use <com.google.android.maps.MapView> element to display map.
Now your main.xml code looks like
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.google.android.maps.MapView
android:id="@+id/mapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:enabled="true"
android:clickable="true"
android:apiKey="0U7-rnRk3Os0sPZnZF9iejONnHMsGRLxU0JbrBg"/>
</RelativeLayout>
Now edit your Java class file as specified below

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
Now run the application, you should be able to see the Google Map...





NullPointerException


NullPointerException occurs when below criteria happens

1) Throw when an application attempt to use a null in a case where an object is required

2) Calling the instance method of null object

3) Accessing or Modifying the field of null object

4) Taking the length of null as if it were an array

5) Accessing or modifying the slot of null as if it were an array

6) Throwing null as if it were a throwable value

Handle

Suppose String name = null

if i will do this

if (name.equals("srinivas")) --> it throw null pointer Exception

to avoid this you can use the above statement as below

if("srinivas".equals(name))

ClassNotFoundException


Thrown when an application tries to load in a class through its string name using :

- The forName method in class Class.

- The findSystemClass method in class ClassLoader .

- The loadClass method in class ClassLoader.

- but no definition for the class with the specified name could be found.
e.g Class.forName("java.lang.String");

Create own exception


Steps :

1. Write our own Exception Class as extending Exception Class as SuperClass.

2. Write default constructor in our own Exception Class.

3. Write a parameterized constructor with a String as a parameter and from that call the SuperClass parameterized constructor by passing the same String.

4. Whenever needed create Object to our own Exception Class and throw it using throw statement.


example program looks like:

public class Demo{
public float add(int i,int j)throws DivisionException{
if(j==0)
throw new DivisionException("Denominator is zero");
return i/j;
}
public static void main(String[] args) {
Demo d=new Demo();
try{
System.out.println( d.add(101,-2));
}
catch(DivisionException a){

a.printStackTrace();
//System.out.print("Error messege is "+a.getMessage());
// System.out.println(a.toString());

}
}
}
Exception class is :

class DivisionException extends Exception {
public DivisionException() {
}
DivisionException(String msg){
super(msg);
}
}

Collection Framework


Collections Framework is a unified architecture for representing and manipulating Collections. It is a Class hierarchy to handle group of objects.

Collections Frameworks contain the following :

Interfaces : These are abstract data types that represent Collections. Interfaces allow Collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy.

Implementations
 : These are the concrete implementations of the Collection Interfaces. In essence, they are Reusable Data Structures.

Algorithms : These are the methods that perform useful computations, such as searching and sorting, on objects that implement Collection Interfaces. The algorithms are said to bepolymorphic: that is, the same method can be used on many different implementations of the appropriate Collection Interface. In essence, algorithms are reusable functionality.

Vector Vs ArrayList


Vector is synchronized and ArrayList is not. Any method that touches the Vector's contents is thread safe. And ArrayList is not thread safe. However using synchronization will incur a performance hit. So if we don't need a thread-safe collection, we have to use ArrayList.

Data growth
Internally the ArrayList and Vector manage their contents using an Array. You need to keep this fact in mind while using either in your programs. When you insert an element into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent. So if you don't use them properly, you may end up with performance hit.

Traversal
ArrayList implements Iterator Interface for traversing While Vector implements Enumerator Interface for traverse.




               ArrayList

Vector
1. No method is synchronized in the ArrayList class

1. All methods in Vector are synchronized.
2. ArrayList object is not thread safe.

2.  Vector is thread safe.
3. Relatively performance is high

3. Relatively performance is low
4. Introduced in 1.2 version and it is non legacy4. Introduced in 1.0 version and it is legacy

List


List : An Ordered Collection (called a sequence). Lists can contain duplicate elements.

- We have precise control over on List, where in the List each element is inserted and can access elements by their integer index (position).

There are 3 flavours of List implementation Classes :

1. Array List
2. Linked List
3. Vector


- In addition to the operations inherited from Collection, the List interface includes operations for the following:

Positional access : manipulates elements based on their numerical position in the List

Search : searches for a specified object in the list and returns its numerical position

Iteration : extends Iterator semantics to take advantage of the List's sequential nature

Range-view : performs arbitrary range operations on the List.


ArrayList:


ArrayList is a Collection which can be used to represent a group of objects as a single entity.
  • it is a implemented class for  List interface
  • Introduced in 1.2 version
  • The underlying data structure is resizable or growable array.
  • Insertion order is preserved
  • Duplicates are allowed
  • Heterogeneous objects are allowed
  • null insertion is possible
  • This  class implements RandomAccess , Serializable , Cloneable interfaces
  • Best choice  for retrieval purpose and worst if our frequent operation is insertion or deletion in the middle
Linked List:

LinkedList is a Collection implemented class which can be used for representing a group of objects as a single entity.
  • LinkedList is the implemetation class for List interface
  • Introduced in 1.2 version
  • Underlying data Structure is   DoubleLinkedList
  • Allows duplicates
  • Insertion order is preserved
  • Allows heterogeneous objects
  • null insertion is possible
  • LinkedList class implements Seriallizable and Cloneable interface but not RandomAccess interface
  • Best choice  if frequent operation is insertion or deletion an objects in middle  but worst choice if frequent operation is retrieval.
Vector class:
     Vector is a legacy collection class which can be used to represent a group of objects.
  • Introduced in 1.0 version. it is legacy class
  • The underlying data structure is resizable or growable array.
  • Insertion order is preserved
  • Duplicates are allowed
  • Heterogeneous objects are allowed
  • It is a implemented class for  List interface
  • null insertion is possible
  •  Vector class implements RandomAccess ,Serializable,Cloneable interfaces
  • Best Choice if frequent operation is retrieval and worst choice if frequent operation is insertion or deletion in the middle.
  • All methods present in Vector class are synchronized hence Vector class object is thread safe.

List Vs Vector


List is an interface, while Vector is a concrete implementation ClassList fixes several minor API deficiencies in Vector. Commonly used Vector operations, such as elementAt and setElementAt, have been given much shorter names.

- We can observe the set method, which replaces the Vector method setElementAtreverses the order of the arguments so that they match the corresponding array operation.

Example : Consider the following assignment statement.

gift[5] = "golden rings";

The Vector equivalent is:

gift.setElementAt("golden rings", 5);

The List equivalent is:

gift.set(5, "golden rings");

- The method add(int, E), which replaces insertElementAt(Object, int), also reverses the order of the arguments.

- The three range operations in Vector (indexOf, lastIndexOf, and setSize) have been replaced by a single range-view operation (subList), which is far more powerful and consistent.

Map Vs HashTable


Map is an Interfce, and a HashTable is an concrete implemented Class of Map interface.

Map provides Collection views instead of direct support for iteration via Enumeration objects. But HashTable can.

Map allows you to iterate elements, over keys, values, or key-value pairsHashtable does not provide the key-value pairs.

Map provides a safe way to remove entries in the midst of iteration, but Hashtable did not.

Collection Interface

The core Collection Interfaces encapsulates different types of Collections. These Interfaces allow Collections to be manipulated independently of the details of their representation.

Collection — The root of the Collection Hierarchy. A collection represents a group of objects known as its elements. The Collection Interface is the least common denominator that allcollections implement and is used to pass collections around and to manipulate them when maximum generality is desired.

- Some types of Collections allow duplicate elements, and others do not. Some are ordered and others are unordered.

- The Java platform doesn't provide any direct implementations of this Collecton Interface but provides implementations of more specific subinterfaces, such as Set and List.

- All the Collection Classes in java.util package have been divided into 4 groups

1. Sets
2. Lists
3. Queues
4. Maps



See the collection Interface Hirarchy:





Convert Collection into Array


By using toArray() method we can convertCollection into an Array.

toArray() : This method is provided as a bridge between Collections and older APIs that expect Arrays on input. The Array operations allow the contents of a Collection to be translated into an Array.

- The simple form with no arguments creates a new Array of Object. The more complex form allows the caller to provide an Array or to choose the runtime type of the output Array.

Examples :

- choose c is a Collection. The following snippet dumps the contents of c into a newly allocated Array of Object whose length is identical to the number of elements in c.

Object[] a = c.toArray();

- If c is known to contain only Strings, the following snippet dumps the contents of c into a newly allocated Array of String whose length is identical to the number of elements in c.

String[] a = c.toArray(new String[0]);

Matrix Multiplication Programme in java


class MatrixMultiply{
public static void main(String[] args)  {
int array[][] = {{5,6,7},{4,8,9}};
int array1[][] = {{6,4},{5,7},{1,1}};
int array2[][] = new int[3][3];
int x= array.length;
System.out.println("Matrix 1 : ");
     for(int i = 0; i < x; i++) {
for(int j = 0; j <= x; j++) {
System.out.print(" "+ array[i][j]);
}
System.out.println();
}
int y= array1.length;
System.out.println("Matrix 2 : ");
     for(int i = 0; i < y; i++) {
for(int j = 0; j < y-1; j++) {
System.out.print(" "+array1[i][j]);
}
System.out.println();
        }

     for(int i = 0; i < x; i++) {
for(int j = 0; j < y-1; j++) {
for(int k = 0; k < y; k++){

array2[i][j] += array[i][k]*array1[k][j];
}
}
        }
System.out.println("Multiply of both matrix : ");
for(int i = 0; i < x; i++) {
for(int j = 0; j < y-1; j++) {
System.out.print(" "+array2[i][j]);
}
System.out.println();
        }
    }
}

Format Strings in Java


The String Class has a method format(), that returns a String object rather than a PrintStream object.

Using String's static format() method allows you to create a formatted String that we can reuse, as opposed to a one-time print statement.

Example:
- instead of
System.out.printf("The value of the float variable is %f, while the value of the " + "integer variable is %d, and the string is %s", floatVar, intVar, stringVar);

- we can write
String fs;
fs = String.format("The value of the float variable is %f, while the value of the " + "integer variable is %d, and the string is %s", floatVar, intVar, stringVar);
System.out.println(fs);

Conversion of Strings into numbers and numbers into Strings


There are two ways to convert Strings into Number :

1. The Number subclasses that wrap primitive numeric types Byte, Integer, Double, Float, Long, and Short each provide a class method named valueOf() that converts a String to anObject of that type.

Example : ValueOfDemo , that gets two strings from the command line, converts them to numbers, and performs arithmetic operations on the values

public class ValueOfDemo {
public static void main(String[] args) {

//this program requires two arguments on the command line
if (args.length == 2) {
//convert strings to numbers
float a = (Float.valueOf(args[0]) ).floatValue();
float b = (Float.valueOf(args[1]) ).floatValue();

//do some arithmetic
System.out.println("a + b = " + (a + b) );
System.out.println("a - b = " + (a - b) );
System.out.println("a * b = " + (a * b) );
System.out.println("a / b = " + (a / b) );
System.out.println("a % b = " + (a % b) );
} else {
System.out.println("This program requires two command-line arguments.");
}
}
}

The following is the output from the program when you use 4.5 and 87.2 for the command-line arguments :

a + b = 91.7
a - b = -82.7
a * b = 392.4
a / b = 0.0516055
a % b = 4.5


2. Each of the Number subclasses that wrap primitive numeric types also provides a parseXXXX() method (for example, parseFloat()) that can be used to convert Strings to primitive numbers. Since a primitive type is returned instead of an object, the parseFloat() method is more direct than the valueOf() method.

Example :

-Above ValueOfDemo program, we could use :

float a = Float.parseFloat(args[0]);
float b = Float.parseFloat(args[1]);


we can use static methods of wrapper classes to convert strings into primitive numbers
ex:int i= Integer.parseInt("10");
sop(i)-->10
float i= Float.parseFloat("10.6");

Double.parseDouble(String argument);

Converting Numbers into Strings:



Sometimes we need to convert a Number to a String because you need to operate on the value in its String form.

There are several easy ways to convert a number to a String :

Example : int i;
String s1 = "" + i; //Concatenate "i" with an empty string;
or
String s2 = String.valueOf(i); //The valueOf class method.

- Each of the Number subclasses includes a class method, toString(), that will convert its primitive type to a String.

Example :
int i;
double d;
String s3 = Integer.toString(i);
String s4 = Double.toString(d);

Example : The ToStringDemo example uses the toString() method to convert a Number to a String. The program then uses some String methods to compute the number of digits before and after the decimal point :

public class ToStringDemo {

public static void main(String[] args) {
double d = 858.48;
String s = Double.toString(d);

int dot = s.indexOf('.');

System.out.println(dot + " digits before decimal point.");
System.out.println( (s.length() - dot - 1) +
" digits after decimal point.");
}
}

The output of this program is :

3 digits before decimal point.
2 digits after decimal point.

OOPs Concept


If any language follows OOPS (Object Oriented System) features then we can say that language as Object Oriented Language.

Features of OOPS :
- Everything we represent as Object.
- Encapsulation
- Abstraction
- Inheritance
- Polymorphism
- Message Passing

Object:

An Object is an instance of a Class. It exists physically.
An Object can't exist without a Class
objects are stored in heap. 

An Object is a Basic runtime entity. 

It has it's individual state and behavior.

Why Java Not fully Object Oriented


) Everything in Java is not considered as a Object, there are primitive data types available.
Ex : for no.s we are using the int which is not a object type. (only Integer is object type ).

2) All features of OOP language is not fully supported by Java.
Ex : Multiple Inheritance, Operator Overloading, etc.


But we can make it as a fully object oriented language through using wrapper classes

instead of int use Integer
- - - byte -Byte
char - Character
double - Double
float - Float ... etc


Packages in Java


Package is a namespace that contains a set of related classes and interfaces.

Basic Packages :

java.lang : Fundamental classes are presnt in this package.
java.io : classes for reading and writing (input and output) are presnt in this package.

For Example:

Library is a package with collection of maths and science and social books.

Creating Package:
                                 To create a Package, you choose a name for the Package (i.e., naming conventions) and put a Package statement with that name at the top of every source file that contains the types (classes, interfaces) that you want to include in the Package.

The package statement must be the first line in the source file. There can be only one package statement in each source file.

Example 
:

package Library;
Class Maths
{
----
----
}

To create a Package we execute this Class with javac command like as

javac - d . Maths.java

Try and Catch Blocks in Exception handling


Try() Block:

       The first step in constructing an Exception Handler is to enclose the code that might throw an Exception within a try block.

Try Block Syntax :

try {
code
}
catch and finally blocks . . .

- The labelled code in above example contains one or more legal lines of code that could throw an Exception. So enclose the Exception-throwing statements within a try block.

- We can put each line of code that might throw an Exception within its own try block and provide separate Exception Handlers (Catch Block) for each. Or, we can put all the code within a single try block and associate multiple handlers with it.

- If an Exception occurs within the try block, that Exception is handled by an Exception Handler associated with it. To associate an Exception Handler with a try block, you must put a catch block after it.

Catch() Block:

          We associate Exception Handlers with a try block by providing one or more catch blocks directly after the try block. No code can be between the end of the try block and the beginning of the first catch block.

When an exception is raised in the try block and it throws it to the catch clause and catch clause will handle it.

Syntax :

try {

} catch (ExceptionType name) {

} catch (ExceptionType name) {

}


- Each catch block is an Exception Handler and handles the type of Exception indicated by its argument. The argument type, ExceptionType, declares the type of Exception that the handler can handle and must be the name of a Class that inherits from the Throwable Class. The handler can refer to the Exception with name.

- The catch block contains code that is executed if and when the Exception Handler is invoked. The Runtime System invokes the Exception Handler when the handler is the first one in the call stack whose ExceptionType matches the type of the Exception thrown. The system considers it a match if the thrown object can legally be assigned to the Exception handler's argument.

Exception Handlers can do more than just print error messages or halt the program. They can do error recovery, prompt the user to make a decision, or propagate the error up to a higher-level handler using Chained Exceptions.


Finally Block():
    
           The Finally Block always executes when the try block exits. This ensures that the Finally Block is executed even if an Unexpected Exception occurs. But Finally is useful for more than just Exception Handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a Finally Block is always a good practice, even when no Exceptions are anticipated.

- The Runtime System always executes the statements within the Finally Block regardless of what happens within the try block. So it's the perfect place to perform cleanup. TheFinally Block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a Finally Block to insure that resource is always recovered.

Note : If the JVM exits while the try or catch code is being executed, then the Finally Block will not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the Finally Block will not execute even though the application as a whole continues.


Finally block is executed after try-catch block.

in this block we have to save any unsaved information before termination of

the program.

we can close any database connections exists.

Finally is also a block, where code gets executed. and it is possible to occurs Exception there. and if any Exception occurs in finally result is Same Termination of the Program.
Solution : Use try Catch blocks there to avoid termination.

Eg:



public class ExceptionTest {

public static void main(String args[])
{
try
{
System.out.println("Inside Try");
}catch(Exception e)
{
System.out.println("Inside catch");
}
finally
{
try
{
int i=10/0;
}catch(Exception e)
{
System.out.println(e);
}
}
}

}

exception may arise in finally block . To avoid automatic termination we can use try catch inside finally .....