Core java tutorial


Core java tutorial - contributed by Pradip Patil


Introduction to Core Java

Java is a popular 3rd generation Object Oriented programming language. It was invented in 1991 by James Gosling. Previously it was known as Oak. Java was developed by Sun Microsystems.

Java interview test (20 questions) new

Features of JAVA

Following are the attributes/features of the first application language of World Wide Web.

  • Simple
    According to development point of view, Java is simple to develop and consists of features of the languages like C and C++.

  • Object Oriented
    Everything written in java is in the form of Objects. So, Java is truly an Object Oriented language.
  • Distributed
    Java is made for creating application on the internet/web and it has the ability to share data and code by using remote object. That’s why it said to have distributed characteristic.
  • Platform independent
    An important feature of the java as compared to other programming language is that it is platform independent.
  • Multithreaded
    Multithreaded means ability to handle multiple tasks simultaneously. This means that we need not wait for the execution of one task before starting the second task.
  • Robust and Secure
    Java is strict towards compile time and run time checking for the data type. It incorporates concept of exception handling and it also provides security from the thread and viruses.
  • High performances
    Performance of the java language is very high due to use of the byte code as an intermediate code. Overall execution speed of the java program is very fast.
  • Dynamic
    Java is dynamic in nature and it is capable of linking to new classes, libraries, methods etc. It also supports a function written in the other language and fetches that function dynamically in a program.

JDK environment:

Java language comes with a number of classes, method variables, packages and development tools. This altogether is known as Java Development Kit (JDK).

Java Development Kit consists of following things.

  • Javac: It is the java compiler which translates source code to the byte code format for the understanding of interpreter.
  • Java: Means Java interpreter which runs the program by reading and interpreting the file in byte code format.
  • appletviewer: It enables us to run applet program (without using web browser).
  • javadoc: Java source code file documentation which is created in HTML.
  • Jdb: To find out the error in program we have to use Java debugger.

Object Oriented concepts with respect to Java

Java is an Object Oriented Language. This means that each and everything written in java is in the form of objects and classes.

Object: object is anything which can exist.

E.g.- book ,computer, student etc.

Object = properties + behavior

  • In java all the arrays and primitive type data are also available in the form of an object.
  • Static variables and methods are written inside the class.
  • An object oriented language possesses the following features.

    1. Classes and objects
    2. Abstraction
    3. Inheritance
    4. Polymorphism
    5. Encapsulation
    Java possesses all of them.

Difference between C++ and JAVA

C++

C++ is not purely object oriented language.

C++ supports multiple inheritance.

C++ supports pointer concept

There are three access specifiers in C++ viz. Public, Private, Protected.

C++ supports Operator overloading.

Constructor and destructor concept are available in C++

JAVA

Java is purely object oriented language

Multiple inheritance is not available but there are means to reach it.

Java doesn’t support pointer.

Four access specifiers are available in java viz. Public, Private, Protected & default.

Java doesn’t have this concept.

Java only has constructor concept. , Destructor concept is not available in java.

Java Programming Fundamentals:

Java being an object oriented language, two types of programs can be developed in it:

1. Stand-alone application
2. Web applets

Stand-alone application: program which is written in java to complete certain task on local computer is known as stand-alone program.

Web applets: applet is the small java program developed for the web application and applet is located on server. It gets downloaded to local system and before executing the code.

Structure of java program

To learn any language, the best way is to execute some basic programs. Here I am writing basic hello word program.

Program 1 :

Hello.java

class Hello
{
            public static void main(String args[])
           {
                System.out.println(“Hello java user”);
           }
}

From 1st program you can understand how to write the code.

Here I am explaining program line by line.

Class declaration

The 1st line :

class Hello

Declare the class named Hello. Class is a predefined keyword available in java.

Opening brace

Every class available in java starts with “{” and ends with “}” because java is object oriented language and each and everything written in it in inside the class.

Main method declaration

The line is

public static void main(String args[])

here we are defining the method main(). Every java program must include main() method.

Public : we are using public keyword for deciding the access i.e public is the access specifier that decides the scope.

Static :static keyword specifies that we are able to create only single copy of the method throughout the program. So only one main() method will be available in a whole Java program.

void: This keyword states that main method does not return any value.

main() : main() is the predefine method available in java and execution of program always starts from main() method.

String args[] : It is the parameter to the main method which contain array of the objects of type String with array name args.

Output line

Line is
          System.out.println(“Hello java user”);

println() method is the member of out object which is the static data member of a System class. println() method always puts the cursor to the next line.

Comments in Java:

Comment is the description of the features of the programming code. Java permits two types of comment.

1. single line comments.
2. multiline comments.

Single line comment

This comment is used for writing comment for single line by using double slash symbol “//”.

Eg. //this is the comment for one line

Multiline comment

This comment is used for more than one line by using opening “/*” symbol and ending “*/” symbol. Comment statements are enclosed within these symbols.

Eg./* this is the

Multi line comment */

Java program structure

General structure of Java program is as follows

Comment for documentation : this section is optional and contains name of the program using comment.

Package statement: It is the first statement used to declare the package name. It is an optional field.

Import statement : Used to load another class in your program. It is an optional statement.

Interface statement: It is same like class but contains group of method declaration. It is an optional statement.

Class definition : It may be possible that java contains more than one class definition . It is an optional field depending on user programming logic.

Main method class : Since execution of java program starts from main() method, main class contains object of the other classes and it is a compulsory field.

Data types in java

For storing data in memory some memory location is required which can hold that data. Depending on the size of memory, data is classified into different data types.

Integer data type: Number without fractional part or decimal point.

It is declared as

int a=120;

Following table shows list of data type

Data Type Size Range
Byte 1 byte -128 to +127
Short 2 byte -32768 to +32767
Int 4 byte -2147483648 to +2147483647
Long 8 bytes -9223372036854775808 to +9223372036854775807

Float Data type: used to represent a number with decimal point

E.g. float a=3.14;

Data Type Size Range
Float 4 byte -3.4e38 to -1.4e-45 for negative values and 1.4e-45 to 3.4e38 for positive values
Double 8 byte -1.8e308 to -4.9e-324 for negative value and 4.9e-324 to 1.8e308 for positive value

Character data type: for storing single character,we use this data type

Data Type Size Range
Char 2 byte 0 to 65535

String data type: it represents group of the characters

String s=”India”;

Boolean data type: Represents only 2 values true or false

boolean b=true;

variables

Name given to the storage location is known as variable and it must be declared before using it in a program.

Variables are separated by using commas. Every statement is terminated by a semicolon.

E.g. int a=10, b=5;

char b=’x’;

Operators:

Java is very rich in operators and maximum operators are distinguished in 4 types.

1. Arithmetic operator
2. Relational operator
3. Logical operator
4. Bitwise operator

1. Arithmatic operator: An operator which is used for the mathematical calculation is known as an arithmetic operator.

Operator symbol Name of operator
+ Addition
- Substations
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement


These are some operators we use in arithmetic operations. The operands used for arithmetic operation must be numeric type .

2. Relational operator: This operator specifies relationship between operands..

Operator symbol Name of operator
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

3. Logical operator: operator which uses Boolean value and provide desired output.

Operator symbol Name of operator
& Logical AND
| Logical OR
&& Short circuit AND
|| Short circuit OR
!= Not equal to
== Equal to

4. Bitwise operator: This type of operator is applicable for int, short, char, byte.

Operator symbol Name of operator
~ Bitwise unary NOT
& Bitwise AND
I Bitwise OR
>> Shift right
<< Shift left
>>> Shift right zero fill
>>>= Shift right zero fill assignment
<<= Shift left assignment

Keywords

Java reserves some predefined words for programming purpose, called as keywords. There are 50 such keywords …

abstract
assert***
boolean
break
byte
case
catch
char
class
continue
default
float
for
goto*
super
switch
synchronized
this
throw
throws
transient
try
while
Void
If
implements
import
instanceof
int
interface
long
native
new
package
private
protected
public
return
short
static
do
double
else
enum****
extends
final
finally
volatile

Naming convention

It provides rules which must be followed by java programmer at the time of providing a name to the package, class method.

  • Package-package contains classes and method and interface name of the package written in small letter format.
    Eg .java.util

    java.io etc
  • Class: It is the framework for creating object. Class consists of the properties and methods. Class name always start with capital word.

    E.g. String

    System etc.
  • Constant : Represent all fixed value like PI ,etc

    E.g. PI

    MAX_VALUE etc
  • All keywords : Must be written with small letter.

    E.g. public

    void etc

Decision making statement

Statements which are able to take decision depending on the condition are known as decision making statement.

Mainly there are two decision making statements available in java.

1. If statement
2. Switch statement

If statement is very powerful decision making statement .

Syntax:

If(condition)

If statement can be written in the different format:

a) Simple if
b) If _ _ else
c) Nested if_ _ else statement

a) Simple if statement

E.g.;
----------
if (a>b)

System.out.println(“a is greator”);

b) If_ _ else statement

E.g.

if(x==1)
     x=x+1;
else
     x=x-1;

c) Nesting of if_ _ else statement

E.g.
if(a>b)
{
        if(a>c)
        {
               System.out.println(“A is greater”);
         }
else
        -----------
        -----------
}

Switch statement :switch condition checks and compares the value with the given list of cases and executes the particular case.

E.g.
Int x=8
switch(x)
{
       case 10:
       case 9:
       case 8:
       ---------
       ------------------
       break;
case 7:
       ----------------
       ----------------
       break;
default:
       ---------------
       ---------------
}
      ----------------
      ---------------

Iterative statements

Statements which execute any condition repeatedly are known as iterative statements.

In java this type of iterative statements are called as looping statements. They consist of following:

1. for loop: For loop is the very important loop control structure

Syntax:

for(initialization ; condition ;increment/decrement)
eg. for(int i=0;i<5;i++)

System.out.println(i);

This loop executes and prints the value of ‘i ‘ five times. The initial value of variable ‘i’ is zero and it will be incremented up to 4. This means the loop will be executed 5 times.

2. while loop : among all the looping statements, this is the simplest looping statement in java .

Syntax:

while(condition)
{
        ------------------
}

E.g.int no,i=0;

while(no<10)
{
       i=i+no;
}

In while loop if condition is true then it executes all body of the loop and if it is false then it comes out of the loop.

3.do while loop:

This loop executes the condition and looping statements at least one time irrespective of condition being true or false. This looping structure first executes the block and then checks the condition.

Syntax:

do
{
     ----------;
}

While(condition);

E.g.int i=1;
do
{
       System.out.println(i);
       i++;
}While(i<10);

Type casting

Converting one data type into another data type is known as type casting.

Two types of castings are done in java viz.

1. Automatic type casting
2. Generic type casting

1. Automatic type casting: In this type of the casting lower type of the datatype automatically gets converted into the higher type and results always in higher type.

Syntax :

(typename)expression

E.g. i=(int) 10.5

Here, 10.5 converted to int type.

Z=(int )x+y

Here, result of x+y is converted into integer value.

2. Generic type cast: To retrieve elements from collection we have to use this type of type casting. It manipulates group of the data into single unit.

Syntax:

class classname<type >

E.g.

ArrayList<integer> a=new ArrayList<Integer>();

Arrays

Arrays represent group of variables of same data type. We can use arrays for storing multiple values of the same datatype . So rather than declaring a large number of variables we can do use arrays.

Syntax:

Datatype arrayname[size]
E.g. int a[10];

This creates array with name ‘a’ which is able to store 10 values of integer values.

Arrays are divided into the 2 types as follows

1. Single dimensional array
2. Multi dimensional array

Single dimensional array: it is also known as 1D array. It represents only one dimension - may be row or column. Arrays always starts with the index zero i.e. array[0].

Syntax :

Datatype arrayname [ ] =new datatype [ size ];

E.g. int a[]=new int [10];

Here we declared an array with datatype integer and array size 10 .

10 variables are as?

a[0] ,a[1] ,a[2],_ _ _ _ _ _ _a[9];

so from 0 to 9 means total 10 elements can be stored in Array.

We can declare array in following manner also.

int a[]-{10,20,30,40,50};

means a[0]=10;

a[1]=20;

a[2]=30;

a[3]=40;

a[4]=50;

Similarly we can create arrays for other data type.

Multi dimensional array:

Multi dimensional array consists of two or more than 2 dimensions like (2D,3D _ _ _ )

Two dimensional array: Two dimensional arrays are represented in the form of rows and column. We can represent this type of data in the form of table.

Syntax:

int a[][]=new int [3][3];

a[0][0]=10;

a[0][1]=20;

a[0][2]=30;

a[1][0]=40

a[1][1]=50;

a[1][2]=60;

a[2][0]=70;

a[2][1]=80;

a[2][2]=90;

Means this array is able to store 9 elements in following format:

10 20 30
40 50 60
70 80 90

This is also known as matrix.

Three dimensional array: If you want to handle group of the element belonging to other group, you need to use three dimensional array.

Syntax :

Datatype arrayname [ ][ ][ ]=new datatype [size][size][size];

E.g. int a[ ][ ][ ]=new int [2][3][4];

In this manner we can declare multi dimensional arrays.

String

Sequence of the characters is known as string. In java, string is both a datatype as well as a predefined class from the object class which is available in lang package.

In java we can also call class as data type but it is user defined data type.

Syntax

String stringname;

stringname =new String (“string”);

E.g. String a;

a=new String (”Hello”);

String array: we can also create array of the string.

Syntax:

String arrayname[] =new String [size ];

E.g. String a[]=new String[3];

Here we can store three string values.

String method: String class consists of a lot of methods. Few methods are as

Method Task
S=s1.toUpperCase() Convert s1 to uppercase
S=s1.toLowerCase() Convert s1 to lowercase
s.equals(s1) Check for equality of string
s.compairTo(s1) Compare 2 string
s.substring(x) Identify substring from main string

StringBuffer class: It is the class related to the string class. String creates string of fixed size while stringBuffered creates string of variable size. We can perform the insertion updating in string. There are some methods available for string manipulation.

Method Task
s.append(s1) Attached string s1 to string s
S.insert(n, s1) Insert s1 at position n in string s
s.setChartAt(n,’a’) Modify n character to a

Like this we can use methods and update the string.

Creating classes and objects

Java is an object oriented language and without class we cannot create objects. Properties and behaviors are written in the classes .

class provide the packing to the variables and methods and depending on that we can create an object.

How to define the class?

Class is the user define data type and syntax for defining the class are as follows

Class classname
{
  Variable declaration;
         Method decleration()
         {
              Method body;
          }
}

E.g.

class Demo
{
       int x=10;
       void display()
       {
             System.out.println(“value=”+x);
       }
}

In similar manner if you have more than one class or you want to use method of another class in your program then you have to create object of that class

E.g.

class Demo
{
          int x=10;
          void display()
          {
                  System.out.println(“value=”+x);
          }
}

class sample
{
           public static void main(String a[])
        {
            Demo d=new Demo();
           d.display();
        }
}

In above program we’ve created ‘d ‘ as an object of the class Demo in class Sample and using that object we are able to call the display() method of the class Demo. For initializing the object we have to use new keyword .

Access specifiers: In java there are 4 access specifiers available. These are as follows

  • Private: It means that the members of the class are not accessible anywhere except that class.
  • Protected: Members are accessible anywhere but within the same directory only.
  • Public: member can be accessed anywhere outside the class
  • Default: if any access specifier is not specified then by default access specifies is default; default member access only in same directory.

E.g.

Public String S=”Hello”;
public void display();
like this we can able to create member and method as public, private, protected.

Constructor

Special type of method available in java which enables object itself when it is created, it is known as constructor.

Constructor has following characteristics:

  • Constructor name and classname must be same and it must end with the pair of the round brackets (i.e. opening and closing)
  • Constructor doesn’t have any return type, not even void.
  • Constructor may or may not have parameter.
  • Constructor gets called automatically at the time of creation of the object.
  • Constructor gets called whenever you create object. This means it gets called after every creation of the object.

Mainly constructor is divided into two types:

1. Default constructor : It is used when you want to initialise object without value.

E.g.

class Demo
{
     int x,y;
     Demo()// Default constructor
     {
         x=0;
         y=0;
     }
}

class Sample
{
           Public static void main(String a[])
          {
               Demo d=new Demo(); //calling default constructor
         }
}

2. Parameterized constructor: At the time of object instantiation, constructor is invoked automatically by passing certain values.

E.g.

class Demo
{
         int x,y;
         Demo(int p, int q)// parameterized constructor
         {
              x=p;
              y=q;
          }
}

class Sample
{
          Public static void main(String a[])
         {
              Demo d=new Demo(10,20); //calling Parameterize constructor
         }
}

Garbage collection

In java, like c++ , destructor is not there but memory which is allotted dynamically must get released and technique used to do this is known as garbage collection. When no reference to an object exists then that type of object is considered as an object not required in the program and it gets destroyed by garbage collect. It executes automatically at the time of execution of the program.

Finalize() method

Sometime object needs to perform some task after it is destroyed. For example consider that some resources are held by some object and you want object must free the resources before it get destroyed and to handle such situation java provides option called as finalize method.

Garbage collection runs in timely manner and java runtime call finalize() method.

Syntax:

Protected void finalize()
{
       //code
}

Inheritances

Acquiring the properties and behavior of a class in other class is known as inheritance.

In inheritance, new class can acquire all the features of the class from where it is derived. For incorporating all the properties we have to use one keyword known as extends.

From given syntax if you want to use properties from class A in class B then you have to extends.

In java, inheritances are mainly divided in to the 3 types

1.Single inheritance
2. Multilevel inheritance
3.Hirachical inheritance


1. Single inheritance: In this type of inheritance one base class and one derived class is available.

E.g.

class A
{
         //body
}

class B extends A
{
      //body
}

class Demo
{
         public void display()
         {
               System.out.println("in Demo");
          }
}

class Demo1 extends Demo
{
         public void display1()
         {
               System.out.println("In demo1");
         }
}

class Sample
{
       public static void main(String arg[])
       {
            Demo1 d=new Demo1();
            d.display1();
            d.display();
       }
}

From above example you can see that we’ve just created object of the derived class and by using that we can call the method of the base class.

2. Multilevel Inheritance: In this type of inheritance, total three or more than three classes are available and each of them is related to its superior class.

class Demo
{
       int x;
       Demo(int x)
       {
           this.x=x;
        }

        public void display()
       {
           System.out.println("value of x="+x);
      }
}

class Demo1 extends Demo
{
         int y;
         Demo1(intx,int y)
         {
               super(x);
                this.y=y;
          }

          public void display1()
           {
               super.display();
                System.out.println("value of y="+y);
           }
}

class Demo2 extends Demo1
{
      int z;
      Demo2(intx,inty,int z)
      {
            super(x,y);
            this.z=z;
        }

       public void display2()
      {
            super.display1();
            System.out.println("value of z="+z);
        }
}

class Sample
{
            public static void main(String arg[])
           {
                 Demo2 d=new Demo2(10,20,30);
                  d.display2();

           }
}

In above program we have three classes named as Demo,Demo1 and Demo2. Demo2 extends Demo1 and Demo1 extends Demo.By using this, we can acquire multilevel inheritance but in given program three new concepts are there, these are as follows.

super() method: We use this method with the constructor and it is only used for passing parameter to the constructor of the base class and it must be the 1st statement in the constructor. Only then it will be able to call and pass value to the constructor of base class

In above program we’ve created constructor of Demo2 and passed values to the Demo1 and Demo by using super method.

super keywords: This keyword we have to use to call the variable or method of the base class .

In above program we’ve called the display method by using the super keyword.

this keyword: use of this keyword is to refer to the current object and when objects are redundant then we have to use this keyword. In above code we’ve written this keyword inside the constructor to distinguish the object.

3. Hierarchical Inheritances: In this type of inheritance one base class is available and two or more than two classes can extends the base class.

E.g. class Demo
{
      //body
}

class Demo1 extends Demo
{
       //body
}

class Demo2 extends Demo
{
     //body
}

In java we have one restriction - extends only one class at a time. So, it is not possible to achieve multiple inheritance but by using the concept of interface we can achieve it.

Interface

In java, interface is also like class. It also contains methods and variables with the difference that interface defines only abstract methods and final fields. This means that interface does not consist of the body, so, the responsibility goes to the class which wants to use the interface.

Syntax:

Interface interfacename
{
         //Variable decleration
         //method decleration
}

classclassname implements interfacename
{
         //method implementation
}

Using interface we can able to achieve multiple inheritances.

Multiple inheritance

Multiple inheritance means more than two base classes are there with only one derived class. To achieve this type of inheritance we have to use interface.

E.g.

interface Demo
{
         public void dis();
}

class Demo1
{
        public void display1()
       {
           System.out.println("In Demo1");
       }
}

class Demo2 extends Demo1 implements Demo
{
        public void dis()
       {
           System.out.println("In Demo");
        }
        
        public void display2()
        {
             System.out.println("In Demo2");
         }
}

class Sample
{
        public static void main(String arg[])
        {
            Demo2 d=new Demo2();
           d.dis();
           d.display1();
           d.display2();
         }
}

The above example shows us - how we can achieve multiple inheritance with the help of interface.

Polymorphism: Ability to exist in different forms is known as polymorphism. Variable or method having different forms is also known as polymorphism.

Method overloading: Method overloading means when object performs similar task with the use of different parameters.

E.g.

class Demo
{
          intx,y;
          Demo(inta,int b)
          {
                 x=a;
                 y=b;
           }
              Demo(int p)< BR>               {<BR>                X=y=p;
                }
}

class Sample
{
         public static void main(String arg[])
         {
             Demo d=new Demo(10,20);
             Demo d1=new Demo(30);
         }
}

Method overriding: When two or more parents and child classes contain method with same name and same signature it is called as method overriding.

E.g.

class Demo
{
           void dis()
           {
               System.out.println("In Demo");
            }
}

class Demo1
{
         void dis()
          {
                System.out.println("In Demo1");
          }
}

class Sample
{
          public static void main(String args[])
         {
             Demo1 d=new Demo1();
             d.dis();
          }
}

o/p :In Demo1

Nesting and Inner classes : Defining the class within another class is known as nested classes. Scope of this class is within the boundary of original class only.

Eg.

class Demo
{
        void display()
        {
                   System.out.println("In Demo");
                   Demo1 d1=new Demo1();
                  d1.dis();
         }
      class Demo1
       {
             void dis()
             {
                      System.out.println("In Demo1");
              }
        }
}

class Sample
{
           public static void main(String arg[])
          {
              Demo d=new Demo();
             d.display();
           }
}

Final

Final variable : we use final keyword in front of variable to fix the value of that variable .

E.g. finalint x=10;

Final method : If you want to prevent overriding of the method then you have to use the final keyword in front of the method which you don’t want to override.

Eg.

finalvoid dis(){}

Final class : if you want to prevent your class from being inherited, you need to write final keyword in front of the class.

final class Demo
{
          // class Body
}

Abstract Method

Method without a body is known as an abstract method and it always starts with keyword abstract. We use this type of method when we want it to perform different tasks based on the object called

Abstract class

Class which contains 0 or more abstract methods is known as abstract class

Syntax :abstract class Demo
{
         abstract void dis();
}

The above example explains - how to declare the abstract class and method & that by using inheritance concept you can override the abstract method.

Difference between interface and abstract class

Abstract class Interface
It used when some common features are needed to be shared by all objects. It is used when all features are needed to be shared differently to different object.
If abstract class is there then it is the task of the programmer to write other classes. If interface is written then it is up to third party how to implement.
All abstract methods must be implemented in all sub classes. All methods in interface must override all methods in implemented class.
It contains instance variables. Interface can not contain instance variable. It only has constants.

Packages

Package is the collection of the classes and interfaces.

In general terms we can also say that folder or directory is also a package.

  • Classes we use for reusability of the code
  • For creating group of related classes
  • Using package we can hide the classes and interface

Packages are divided into the two types

1. Built- in package
2. User defined package

Built-in package : Packages which are already available in java are known as built-in packages. It provides all the information about classes, interfaces and methods available. Java is very rich in package. By using classes, it is easy for programmer to develop own application using in-built facility of package.

For using package in application, we have a keyword known as “import” and after that you have to specify the package name.

Some of the predefined packages are as follows

java.util: this package stands for utility purpose. This package contains all classes related to date and time & interfaces like Stack ,linkListHashtableetci.e collection classes.

Java.awt : It is also known as GUI package i.e graphical user interface package used for GUI development.

Java.net : Stands for networking purpose i.e for client server communication in programming - it provides the classes.

Some of the other packages are java.lang, java.sql, java.applet etc

User defined package:

Package which is created by user of java is known as user defined package. It is also used in the same way like built- in package using keyword “import “.

Following is the procedure for creating package:

- Create directory or package and after creation start writing java program inside that package with starting keyword

- package packagename //for creating package

- packagepackagename.subpackage //creating package inside the package

- Write all classes and methods as simple as normal program and classes and method which you want to use from that program. Make them as public for accessibility .

- To use that package in your program, simply write
importpackagename.*; // * means all class or you have to mention class name

- Create object of the class and use it as like as simple classes.

E.g.

create package p1 and write code of class Demo

package p1;

public class Demo
{
        public void dis()
        {
               System.out.println(“inside the package”);
         }
}

import p1.*;

class Sample
{
           public static void main(String arg[])
           {
                  Demo d=new Demo();
                  d.dis();
            }
}

o/p : inside the package

Exception handling

Abnormal condition which occurs at the time of running the program is known as exception. Since exception occurs at the time of running the program so it is also known as run time exception.

Exception is also a predefined class available in java .

Exceptions are divided into the two types:

1. Checked exception
2. Unchecked exception

Checked exception : This type of exception is handled by using the code with the help of try catch blocks by the user. This type of exceptions are extended from java.lang.Exception class.

Unchecked exception : This type of exception is not handled by the user, it is handled by the JVM. These exceptions extend from java.lang.RuntimeException class.

Exception handling code Try catch block

Throwing exception and catching it is done by using the try and catch block respectively.

Syntax:

try
{
         exception creating code
}
catch
{
          statements for handling exception
}

E.g.

class Demo
{
       public static void main(String ar[])
       {< BR>             intx=10,y=0,z;
           try
           {
                    z=x/y;
            }
            catch(Exception e)
            {
                System.out.println(“Can not divide by zero”+e);
             }
       }
}

Multiple catch:

We can also write multiple catch statements in a single program by identifying the different types of exceptions.

Syntax :

try
{
         code
}
catch(Exception type e)
{
        Statement
}

catch( Exception e1)
{
         statement
}

From above syntax you can understand - how to write the multiple catch statements if you know the type of exception that may appear in your program.

Nested try

Nested try means - writing try inside the try block.

try
{
       code
       try
       {
            code
       }
       catch(Exceptiontype e)
       {
               statement
       }
}

catch (Exception type e1)
{
           statement
}

throw

When we want to throw user defined exception then we use the keyword “throw”.

Syntax:

throw new exceptionalsubclass;

eg.

classUserdefine extends Exception
{
         Userdefine()
          {
                System.out.println(“Error”);
          }
}

class Sample
{
           public static void main(String ar[])
           {< BR>                   inta=10,b=20;
                    if( a>b)
                    {
                          throw new Userdefine()
                    }
                    else
                    {
                              System.out.println(“A is less than B”);
                    }
            }
}

The above example explains - how we can create our user defined exception.

throws

throws is predefined keyword available in java and it is used when method create particular type of exception while in process.

If you want to use throws keyword with method then it is known as ducking.

E.g.

import java.io.*;
class Demo
{
           void dis()throws IOException
           {
                BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in));
                String x=br.readLine();
                System.out.println(x);
             }
}

class Sample
{
               public static void main(String ar[])throws IOException
                {
                       Demo d=new Demo();
                        d.dis(); 
                }
}

From above example you can understnd how we can use throws.

finally

Finally block is generally used after the try or try and catch block. Because it gives us guarantee that it must get executed and that’s why it is used for file closing and releasing of the resources purpose.

Syntax:

try
{
           code
}

finally
{
          code
}

Or

try
{
           code
}
catch(---)
{
            code
}
             finally
{
code
}

User defined exception

Class or exception which is defined by the user is known as user defined exception and for that keyword throw is used.

Syntax

classclassname extends Exception
{
         Constructor code
}

e.g.

classUserdefine extends Exception
{
            Userdefine()
           {
                    System.out.println(“Error”);
           }
}

class Sample
{
           public static void main(String ar[])
           {< BR>                  inta=10,b=20; 
                   if( a>b)
                   {
                            throw new Userdefine()
                  }
                  else
                  {
                        System.out.println(“A is less than B”);
                   }
         }
}

Here we’ve created exception with name Userdefine and we used the predefined class Exception to create user define exception and we used that exception by using keyword throw.



Write your comment - Share Knowledge and Experience

Discussion Board
Repeat question

Good evening sir... This is the best website for careers related and i also happy and helping us But sir meri problem hai ki when also I practice On-line test for java question then repeat every question after complete 10 question . Please solved this problem

Rashid 03-18-2013 08:18 AM

 


 
Interview questions
Latest MCQs
» General awareness - Banking » ASP.NET » PL/SQL » Mechanical Engineering
» IAS Prelims GS » Java » Programming Language » Electrical Engineering
» English » C++ » Software Engineering » Electronic Engineering
» Quantitative Aptitude » Oracle » English » Finance
Home | About us | Sitemap | Contact us | We are hiring