• No results found

Java Notes

N/A
N/A
Protected

Academic year: 2021

Share "Java Notes"

Copied!
203
0
0

Loading.... (view fulltext now)

Full text

(1)

Chapter 1

Introduction to java

Java is language for the development of Enterprise applications, and it was developed at Sun Microsystems as a platform-independent language primarily aimed at controlling appliances such as video game consoles VCRs, bread toasters . “Sun” , later modified the language to take advantage of World Wide Web. Java is an object-oriented language, and very similar to C++.

Java Features

1. PlatformIndependent

The concept of Write-once-run-anywhere is one of the important key feature of java language that makes java as the most powerful language.

2. Simple

Programs are easy to write and debug because java does not use the pointers explicitly. It is much harder to write the java programs that can crash the system.

3. ObjectOriented

java is a fully Object Oriented language because, object is at the outer most level of data structure in java. No stand alone methods, constants, and variables are there in java. Everything in java is object even the primitive data types can also be converted into objects.

4. Robust

Java has the strong memory allocation and automatic garbage collection mechanism. It provides the powerful exception handling and type checking mechanism as compare to other programming languages. Compiler checks the program whether there any error and interpreter checks any run time error and makes the system secure from crash. All of the above features makes the java language robust.

5. Distributed

Internet programmers can call functions on HTTP , FTP protocols and can get access to the files from any remote machine rather than writing codes on their local system.

6. Portable

The feature Write-once-run-anywhere makes the java language portable provided that the system must have interpreter for the JVM.

7. Secure

Java does not use memory pointers explicitly. All the programs in java are run under an area known as the sand box. Security manager determines the accessibility options of a class like reading and writing a file to the local disk. Java uses the public key encryption system to allow the java applications to

(2)

transmit over the internet in the secure encrypted form. The bytecode Verifier checks the classes after loading.

(3)

8. Performance

Java uses native code usage, and lightweight process called threads. In the beginning interpretation of bytecode resulted in slow performance but the advanced versions of JVM uses just in time compilation technique that improves the performance.

9. Multithreaded

Multithreading programming is a very interesting concept in Java. 10. Interpreted

One of the advantage of Java as an interpreted language is its error debugging quality. Due to this any error occurring in the program gets traced.

11. Architecture Neutral

Java was designed to support applications on network. The Java compiler generates byte code

instructions, to be easily interpreted on any machine and to be easily translated into native

machine code on the fly. What is Java Virtual Machine?

Languages like C and Pascal converts the source code into machine code for one specific type of machine and the machine language vary from system to system . But Java compiler produce code for a virtual machine . JVM converts the byte code into machine code for the computer one wants to run.

The JVM is a part of JRE that is required by every operating system.

Each operating system and CPU architecture requires a JRE. JRE consists of a set of base classes i.e. Java API as well as a JVM. JVM is java interpreter as it converts the byte code into machine code for the computer one wants to run.

JRE consists of a number of classes based on JavaAPI and JVM, and without JRE, it is impossible to run Java.

How to write First Java program public class FirstProgram

{

public static void main(String arr[] ) {

System.out.println(" Hello Java World"); }

(4)

Save the file with same name as the public class just adding the extension “.java” e.g. FirstProgram.java.

Now compile as:

c:\ javac FirstProgram.java

This creates a class file in bytecode form as FirstProgam.class How to execute this code:

c:\ java MyFirstProgram OUTPUT :: Hello Java World

Different Editions of Java Technology

a) Java SE - Java SE or Java Standard Edition provides tools and API's that you can use to create desktop applications, applets, server applications. These programs developed using Java SE can be run on almost every popular operating system.

b) JEE - Java Enterprise Edition helps in web application service, component model and enterprise class service oriented architecture(SOA).

c) JME - Java Micro Edition or JME is an accumulation of Java APIs that are used for the development of software for devices like mobile phones, PDAs, TV set-top boxes, game programming.

Demonstartion Programs

Example 1 : Demo of a Simple java program

public class FirstProg {

public static void main(String args[]) {

System.out.println( “welcome to the java SE 6”); }

}

Example 2 : Demo of if statement through a java program

public class DemoIf {

public static void main(String args[]) {

int a = 10, b = 15, m;

(5)

System.out.println( “max number = “+m); }

}

Example 3 : Demo of while.. loop through a java program

public class DemoWhile {

public static void main(String args[]) { int n = 257, s =0, d; while (n !=0) { d = n % 10; s = s +d ; n = n / 10; }

System.out.println( “sum of digits = “+s); }

}

Example 4 : Demo of for.. loop

public class DemoFor {

public static void main(String args[]) { int n = 30, i; for (i = 1; i <=n; i++) if ( n % i == 0 ) System.out.println( “ “+ i ); } }

(6)

Structure of Arrays

Array is the most widely used data structure in java. It can contain multiple values of the same type. Moreover, arrays are always of fixed length i.e. the length of an array cannot be increased or decreased. The Array class implicitly extends java.lang.Object so an array is an instance of Object. Suppose an array contains "n" integers. The first element of this array will be indexed with the "0" value and the last integer will be referenced by "n-1" indexed value.

Presume an array that contains 12 elements as shown in the figure. Each element is holding a distinct value. Here the first element is refrenced by a[0] i.e. the first index value.

The figure below shows the structure of an Array more precisely.

Array Declaration

To represent the variable as an Array, we use [] notation. These two brackets are used to hold the array of a variable.

int[] array_name; //declares an array of integers

String[] names;

int[][] matrix; //this is an array of arrays

It is essential to assign memory to an array when we declare it. Memory is assigned to set the size of the declared array. for example:

int[] array_name = new int[5];

Here is an example that creates an array that has 5 elements. public class Array

{

public static void main(String[] args) {

int[] a = new int[5]; }

(7)

Array Initialization

After declaring an array variable, memory is allocated to it. The "new" operator is used for the allocation of memory to the array object. The correct way to use the "new" operator is

String names[];

names = new String[10];

Here, the new operator is followed by the type of variable and the number of elements to be allocated. In this example [] operator has been used to place the number of elements to be allocated.

Lets see a simple example of an array,

public class Sum

{

public static void main(Stri ng[] args)

{

int[] x = new int [101]; for (int i = 0; i<x.length; i ++ ) x[i] = i; int sum = 0; for(int i = 0; i<x.length; i+ +) sum += x[i]; System.out.println(sum); } }

To know the length of the Array, we use field length, as shown. Example 5 : Demo of 1 D array - Linear search

public class DemoLsearch {

public static void main(String args[]) { int a[] ={ 10,20,30,15,25}, i, n; int x = 15, flag = 0; n = a.length; for ( i = 0 ; i < n ; i ++) if ( a[ i ] == x) { flag = 1; break; } if ( flag != 0 )

System.out.println( “item found at = “+ ( i+1)); }

(8)

Example 6 : Demo of 1 D array - Sorting of n integers

public class DemoSort {

public static void main( String args[] ) { int a[ ] ={ 10,08,30,15,27,17,12}, i, j, n,temp; n = a.length; for ( i = 0 ; i < n-1 ; i ++) for (j= i+1; j < n; j++) if ( a[ i ] >a[ j ]) { temp = a[ i ]; a[ i ] = a[ j ]; a[ j ]= temp; }

for ( i=0; i < n; i++)

System.out.println( “ “+ a[ i ]); }

}

Example 7 : Demo of user defined iterative functions

public class DemoFunction {

public static void main(String args[]) {

int n = 5, i, fm; fm = fact (m);

System.out.println(“result = “ + fm); }

static int fact( int n) { int fn = 1, i; for (i = 2; i <=n; i++) fn = fn * i; return fn; } }

(9)

Example 8 : Demo of Recursive functions

public class DemoRecfun {

public static void main(String args[]) {

int n = 5, i, fm; fm = fact (m);

System.out.println(“result = “ + fm); }

static int fact( int n) { if ( n < 0) return 1; else return n * fact ( n – 1); } }

(10)

Chapter 2

Object Oriented Features of

Java

OOP stands for Object Oriented Programming. There are four main pillars of an Object Oriented Programming Language :

Inheritance: Inheritance provide the facility to derive one class by another using simple syntax. You can say that it is a process of creating new class and use the behavior of the existing class by extending them for reuse the existing code and adding the additional features as you need.

Encapsulation: Encapsulation is the ability to bundle the property and method of the object and also operate them. It is the mechanism of combining the information and providing the abstraction as well.

Polymorphism: Polymorphism is the way that provide the different functionality by the functions having the same name based on the signatures of the methods. There are two type of polymorphism first is run-time polymorphism and second is compile-time polymorphism.

Dynamic binding: It is the way that provide the maximum functionality to a program for a specific type at runtime. There are two type of binding first is dynamic binding and second is static binding.

Class: A class provide a feature to defines the properties and behavior (variables and methods) as an ADT , that can be used by all its objects. It is a blue print for the creation of objects.

Object: Class itself does nothing but the real functionality is achieved through their objects. Object is an instance of the class. It takes the properties (members) and uses the behavior (methods) defined in the class.

The Encapsulation, Inheritance and Polymorphism are main pillars of OOPs. These have been described below :

Encapsulation:

Encapsulation is the process of binding together the methods and data variables as a single entity. It keeps both the data and functionality code safe from the outside world. It hides the data within the class and makes it available only through the methods. Java provides different accessibility scopes (public, protected, private ,default) to hide the data from outside.

Here we provide a example in which we create a class "Check" which has a variable "amount" to store the current amount. Now to manipulate this variable

(11)

we create a methods and to set the value of amount we create setAmount() method and to get the value of amount we create getAmount() method

Here is the code for "Mainclass" class : class Check

{

private int amount=0; public int getAmount() {

return amount; }

public void setAmount(int amt) {

amount=amt; }

}

public class Mainclass{

public static void main(String[] args) {

int amt=0;

Check obj = new Check(); obj.setAmount(200);

amt = obj.getAmount();

System.out.println("Your current amount is :"+amt); }

}

Here the data variable "amount" and methods setAmount() and getAmount() are enclosed together with in a single entity called the "Check" class. These two methods are used to manipulate this variable i.e. set and get the current value of amount.

Example 9 : Demo of object oriented programming class DemoCalc { int a , b; public DemoCalc() { a = 5; b = 10;

(12)

} public int sum () { int x; x = a + b; return x; } }

public class TestDemoCalc {

public static void main(String args[]) {

DemoCalc m = new DemoCalc(); int z; z = m.sum(); System.out.println(“result = “ + z); } } Constructor

Constructor is the method whoose name is same as that of the class. But there are many difference between the method (function) and the Constructor. It has no return type.

It is used for initialization purpose. A class can have any number of constructors. It is then called constructor overloading.

Example 10 : Demo of Constructor Overloading class DemoOver { int a , b; /* default constructor */ public DemoOver() { a = 5; b = 10; }

/* constructor with parameter */ public DemoOver( int k1, ink k2) {

a = k1; b = k2; }

(13)

public int sum () { int x; x = a + b; return x; } }

public class TestDemoOver {

public static void main(String args[]) {

DemoOver m1 = new DemoOver();

DemoOver m2 = new DemoOver(20,25); int z1, z2;

z1 = m1.sum(); z2 = m2.sum();

System.out.println(“result1 = “ + z1 + “result2 “+z2); }

}

this key word : It is used to resolve the ambiguity between a formal parameter and a datamember.

Example 11 : Demo of keyword this

class Demothis {

int a , b;

/* constructor with parameter */ public Demothis( int a, ink b) {

this.a = a; this.b = b; }

public int sum () { int x; x = a + b; return x; } }

public class TestDemothis {

public static void main(String args[]) {

(14)

Demothis m1 = new Demothis(20,25); int z1; z1 = m1.sum(); System.out.println(“result = “ + z1 ); } }

Instance variables: They are the datamembers in a class and get a copy of memory for each object instance. With one object instance if they are modified , the other instances are not effected.

Example 12 : Demo of instance variable class DemoInvar { int a,b; public DemoInvar( ) { a=5; b=7; }

public void update () {

a++; b++; }

public void disp() {

System.out.println ( “a= “+a + “b=”+b); }

}

public class TestDemoInvar {

public static void main(String args[]) {

DemoInvar m1 = new DemoInvar(); DemoInvar m2 = new DemoInvar (); m1.update();

m1.disp(); m2.disp();

} }

(15)

Static variables: They are the data members in a class defined with a keyword static. Such members are also called class members , . and get a single copy of memory per JVM, for all object instances. With one object instance if they are modified , the other instances are also effected as they are shared .

Example 13 : Demo of class variable class DemoClvar { static int a ; int b; public DemoClvar( ) { a = 5; b = 7; }

public void update( ) {

a ++; b++; }

public void disp( ) {

System.out.println ( “a= “+a + “b=”+b); }

}

public class TestDemoClvar {

public static void main(String args[]) {

DemoClvar m1 = new DemoClvar(); DemoClvar m2 = new DemoClvar (); m1.update( );

m1.disp( ); m2.disp( );

} }

Class methods : Such methods belong the class but not to the objects. They are called with class name.

Example 14 : Demo of class method

(16)

class DemoClmd {

public static wishcode01 () {

System.out.println( “ Happy New Year”); }

public static wishcode02 () {

System.out.println(“Happy returns"); }

}

public class TestDemoClmd {

public static void main(String args[]) {

DemoClmd.wishcode01( ); DemoClmd.wishcode02( ); } }

(17)

Example 15 : Demo of class method

class DemoMathop

{

static float multiply(float x, float y) {

return x*y; }

static float divide(float x, float y) {

return x/y; } }

public class TestDemoMathop {

public static void main(String args[]) { float a = DemoMathop.multiply(2.0,5,0); float x = DemoMathop.divide(a,2.0); System.out.println("x=" + x); } }

Example 16 : Demo of method invocation by other methods of the same class ( Nested methods) class DemoNest { int a,b; public DemoNest( ) { a=15; b=7; }

public int large() {

int m;

m= ( a>b)? a : b; return m; }

(18)

{

int x = large(); /* method call */ System.out.println ( “max= “+ x); }

}

public class TestDemoNest {

public static void main(String args[]) {

DemoNest m1 = new DemoNest(); m1.disp();

} }

System.out.println() ::

The "java.lang" package is built into every program. A package is a libaries of classes.

The java.lang package has a System Class, which includes a static nested class called "out" and this out class, has a method by name println(). Why method main has " public , static" access specifiers :: It is called from outside.

The main() is a class method

It is invoked by the interpretor with its class name.

Chapter 3

(19)

Strings are handled as objects in java. Java support two classes to handle strings

1 String 2 StringBuffer

String objects hold text which can't be changed. A String class object is immutable because the time taken by JVM to reallocate memory and add data is more than creating a new object. A StringBuffer on the

otherhand, is mutable. It can change and grow in size The default constructor allocates 16 char size to a StringBuffer

String Methods

Let s1, s2 are the source and destination strings. Then some methods are s2 = s1.toLowerCase() s2 = s1.replace('x', 'y') s2 = s1.trim() s1.equals(s2) , s1.isEmpty() s1.equalsIgnoreCase(s2) S1.length s1.charAt(n) s1.subString(n) , s1.subString(m,n) s1.indexOf("x") s1.toString() s1.compareTo(s2) s2 = s1.concat(s3)

(20)

StringBuffer methods s1.charAt(n) s1.append(s2), s1.replace(m,n,s2) s1.setCharAt(n,'x') s1.insert(n,s2)

s1.setLength(n) , s1.length(), s1.reverse()

The following programs demonstrate String handling in java. Example 17 : Demo of methods in String class

public class TestStread {

public static void main( String args[]) {

String s1 = "hello";

String s2 = new String(); s2 = "from" String s3 = new string("Java"); String s4 = s1 + s2 + s3;

String s5 = s4.concat(" world "); String s6 = "";

System.out.println(s5);

System.out.println(s5.toUpperCase());

system.out.println("is empty? " + s6.isEmpty()); }

}

Example 18 : Demo of methods in String class public class TestSsort

{

public static void main( String args[]) {

String s[] = { "arun", "rao" , "sridhar", "jones"}; int i,j,n;

String temp = null; n = s.length;

for ( i=0; i< n-1; i++) for (j=i+1; j<n ; j++)

(21)

if ( s[i].compareTo(s[j]) > 0 ) {

temp = s[i]; s[i] = s[j]; s[j] = temp;

}

for ( i =0; i< n; i++)

System.out.println(s[i]); }

}

Example 19 : Demo of methods in String buffer class public class TestBuff

{

public static void main( String args[]) {

StringBuffer s1 = new StringBuffer("hello"); StringBuffer s2 = new StringBuffer();

s2.insert(0," from");

s2.append(" java"); s1.append(s2); System.out.println(s1); s1.replace(6,10,"to"); System.out.println(s1); s1.delete(6,8); System.out.println(s1);

System.out.println("alloted len" + s1.capacity()); s1.setLength(100);

system.out.println("new capacity"+ s1.length()); }

}

Example 20 : Demo of methods in StringBuffers public class TestSbuff

{

public static void main( String args[]) {

StringBuffer sb= new StringBuffer("Java is tough"); System.out.println(sb);

int n = sb.length(); int p;

for ( i=0; i< n; i++) {

(22)

p = i + 1;

System.out.print("char at pos" +p+"=" + sb.charAt(i)); }

String a = new String(sb.toString()); p = a.indexOf("tough"); sb.insert(p,"Not "); System.out.println(sb); sb.append(" to learn"); System.out.println(sb); } } StringBuilder class ::

StringBuffer , can be used by multiple threads. It is recommended when synchronization is required. Its methods are synchronized. A StringBuilder has no synchronized methods. So it works faster and , When we are doing number of string operations in a single thread we gain tremendous performance than StringBuffer.

Example 21 :: Demo of StringBuilder public class TestApp

{

public static void main(String args[]) {

String s = concate("java"," ","is"," ","simple"); System.out.println(s);

}

static String concate(String... k) {

StringBuilder sd = new StringBuilder( ); int n = k.length; int i;

for ( i= 0; i< n ; i++) sd.append(k[i]); return sd.toString( ); } } StringTokenizer. Example 22:

(23)

import java.util.StringTokenizer; class STDemo {

static String in ="title=Java: The Complete Reference;" + "author=Naughton and Schildt;" +

"publisher=Osborne/McGraw-Hill;" + "copyright=1999";

public static void main(String args[]) {

StringTokenizer st = new StringTokenizer(in, "=;"); while(st.hasMoreTokens()) {

String key = st.nextToken(); String val = st.nextToken();

System.out.println(key + "\\t" + val); }

} }

Wrappers

Java provide wrapper classes in order to use primitive data types as objects, Every primitive type has a class defined

primitive wrapper int Integer float Float char Character

There are methods defined to return the values of an object

Example 23 : Demo of wrapper class public class TestWrp1

(24)

public static void main( String args[]) {

Integer i = new Integer(25);

Character c = new Character('H'); int J = i.intValue(); char k = c.charValue(); System.out.println(j + " " +i); System.out.println(k+ " " + c); } }

Let a,b are primitive types, m,n are objects , and S is string object Conversion of primitive types to primitive objects

Integer m = new Integer(a); Float n = new Float(b);

Conversion of primitive objects to primitive types int a = m.intValue();

float b = n.floatValue();

Conversion of primitive types to string objects String s = Integer.toString(a);

String s = Float.toString(b);

Conversion of string objects to primitive types int a = Integer.parseInt(s);

float b = Float.parseFloat(s); Example 24 : Demo of wrapper class public class Adder

{

public static void main( String args[]) { int a, b, m; a= Integer.parseInt(args[0]); b= Integer.parseInt(args[1]); m = a+b; System.out.println("result " + m); } }

Autoboxing, unboxing of primitive types Example 25 : Demo of autoboxing, unboxing public class TestBoxUnbox

(25)

{

public static void main( String args[]) {

Integer ib1,ib2,ib3;

ib1 = 25; // autoboxing - encapsulating a value

int i1 = ib1; // unboxing - extracting the value System.out.println(ib1 + " " +i1);

ib2 = 35;

ib2 = ib2 + 1; // unbox and rebox System.out.println("value" + ib2) ;

ib3 = Abox.getval(55); // Autobox

System.out.println(" value returned" + ib3); }

}

class Abox {

static int getval( Integer ib) {

return ib; // unbox the return vaule }

}

for - each loop ::

for (type varaible : collection) statement;

Example 26 : Demo of for each public class DemoApp {

public static void main( String args[]) {

for ( String s: args) System.out.println(s); }

}

Example 27 : Demo of for-each public class DemoApp

(26)

{

enum Country { india, china, japan, canada}; public static void main( String args[])

{

for ( Country c: Country.values()) System.out.println("it Is" + c); }

}

(27)

Example 28 : Demo of variable numer of parameters public class DemoApp

{

static void mthvar(int... i) { int n = i.length; System.out.println("number of para"+ n); System.out.println("contents are"); for ( int k : i) System.out.println("it Is" + k); }

public static void main( String args[]) { mthvar(); mthvar(25,35); mthvar(10,20,30,40); } }

Example 29 : Demo of for-each public class DemoApp {

public static void main( String args[]) { int a[] = { 10,20,30,40,50}; int max = 0; for ( int k: a) if ( k > max) max = k; System.out.println("maximum" + max); } }

Chapter 4

(28)

Inheritance & Polymorphism in

java

Inheritance allows a class (subclass) to acquire the properties and behavior of another class (superclass). In java, a class can inherit only one class (superclass) at a time but a class can have any number of subclasses. It helps to reuse, customize and enhance the existing code. So it helps to write a code accurately and reduce the development time. Java uses extends keyword to extend a class.

Here is the code of the example : class A

{

public void fun1(int x) { System.out.println("in A is :" + x); } } class B extends A {

public void fun2(int x,int y) {

fun1(6); // prints "int in A"

System.out.println("in B is :" + x " and "+y); }

}

public class Testinherit {

public static void main(String[] args) {

B obj= new B(); obj.fun2(2); }

}

In the above example, class B extends class A and so acquires properties and behavior of class A. So we can call method of A in class B.

Thus inheritance is aechanism used to create new class by extending the definition of another class. This process of extending one class to create new class is called subclassing.

(29)

Single inheritance Multiple Inheritance Multilevel Inheritance Hirarchial Inheritance Hybrid Inheritance /* Demo of inheritance */ class DemoCalc { int a,b; public DemoCalc() { a = 5; b = 10; }

public int sum () { int x; x = a + b; return x; } }

public class TestDemoCalc {

public static void main(String args[]) {

DemoCalc m = new DemoCalc(); int z;

z = m.sum();

System.out.println(“result = “ + z); }

}

Example 30 : Demo of inheritance

class ChDemoCalc extends DemoCalc {

public int diff() { int x; x = a-b; return x; } }

public class TestChDemoCalc {

public static void main(String args[]) {

(30)

ChDemoCalc m = new ChDemoCalc(); int z1,z2;

z1 = m.sum(); z2 = m.diff();

System.out.println( “sum=“+ z1 + "diff=" +z2 ); }

}

Constructor under inheritance

When a child class object is instantiated the constructor of the base class is called first , then followed by the derived class constructor.

Example 31 : Demo of constructor under inheritance class A

{ A( )

{

System.out.println("In constructor of A"); } } class B extends A { B( ) { System.out.println("In constructor of B"); } }

public class TestApp {

public static void main(String args[]) { B b1 = new B(); } } output :: In construtor of A In construtor of B

Example 32 : constructor with param under inheritance - 1 class A

{ A( )

{

(31)

} } class B extends A { B(String s ) {

System.out.println("In string constructor of B"); System.out.println(s);

} }

public class TestConInhe {

public static void main(String args[]) {

B b1 = new B("Java is simple"); }

}

output :: In construtor of A

In string construtor of B

(32)

Example 33 : constructor with param under inheritance - 2 class A

{ A( )

{

System.out.println("In constructor of A"); }

A(String s ) {

System.out.println("In string constructor of A"); System.out.println("In A" + s); } } class B extends A { B(String s ) { super(s);

System.out.println("In string constructor of B"); System.out.println("In B" + s);

} }

public class TestApp {

public static void main(String args[]) {

B b1 = new B("Java is simple"); }

}

output :: In string construtor of A In A java is simple

In string construtor of B In B java is simple

super( ) :: It can be used to call super class methods/constructor Multilevel inheritance::

(33)

class A

{ A( )

{

System.out.println("In constructor of A"); } } class B extends A { B( ) { System.out.println("In constructor of B"); } } class C extends B { C( ) { System.out.println("In constructor of C"); } }

public class TestApp {

public static void main(String args[]) { C c1 = new C(); } } output :: In construtor of A In construtor of B In contructor of C

Polymorphism

Polymorphism allows one interface to be used for a set of actions i.e. one name may refer to different functionality. Polymorphism allows a object to accept different requests of a client (it then properly interprets the request like choosing appropriate method) and responds according to the current state of the runtime system, all without bothering the user.

(34)

1. Compile-time polymorphism 2. Runtime Polymorphism

In compiletime Polymorphism, method to be invoked is determined at the compile time. Compile time polymorphism is supported through the method overloading concept in java.

Method overloading means having multiple methods with same name but with different signature (number, type and order of parameters).

Here is the code of the example : class A{

public void fun1(int x){

System.out.println("The value of class A is : " + x); }

public void fun1(int x,int y){

System.out.println("The value of class B is : " + x + " and " + y); }

}

public class polyone{

public static void main(String[] args){ A obj=new A();

// Here compiler decides that fun1(int) is to be called and "int" will be printed. obj.fun1(2);

// Here compiler decides that fun1(int,int)is to be called and "int and int" will be printed.

obj.fun1(2,3); }

}

In rumtime polymorphism, the method to be invoked is determined at the run time. The example of run time polymorphism is method overriding. When a subclass contains a method with the same name and signature as in the super class then it is called as method overriding.

class A{

public void fun1(int x){

System.out.println("int in Class A is : "+ x); }

}

class B extends A{ public void fun1(int x){

System.out.println("int in Class B is : "+ x); }

}

public class polytwo{

(35)

A obj;

obj= new A(); // line 1

obj.fun1(2); // line 2 (prints "int in Class A is : 2")

obj=new B(); // line 3

obj.fun1(5); // line 4 (prints ""int in Class B is : 5") }

}

Method Overriding ::

It is used when a subclass has to replace a method of its superclass. Whenever such a method is invoked, java looks for a method of that signature, in the class definition of the current object. If such a method is not found then it looks for a matching signature in the superclass.

Example 35 :: Demo of method overriding class Animal

{

public void breath( ) {

System.out.println(" Breathing..."); }

}

class Fish extends Animal {

public void breath( ) {

System.out.println("Bubbling..."); }

}

public class TestRide {

public static void main(String args[]) {

Fish f = new Fish(); f.breath();

} }

(36)

super keyword

The super is java keyword. As the name suggest super is used to access the members of the super class. It is used for two purposes in java.

The first use of keyword super is to access the hidden data variables of the super class hidden by the sub class.

e.g. Suppose class A is the super class that has two instance variables as int a and float b. class B is the subclass that also contains its own data members named a and b. then we can access the super class (class A) variables a and b inside the subclass class B just by calling the following command.

super.member;

Here member can either be an instance variable or a method. This form of super most useful to handle situations where the local members of a subclass hides the members of a super class having the same name. The following example clarify all the confusions.

class A{ int a; float b; void Show(){

System.out.println("b in super class: " + b); } } class B extends A { int a; float b; B( int p, float q) { a = p; super.b = q; } void Show() { super.Show();

System.out.println("b in super class: " + super.b);

System.out.println("a in sub class: " + a);

}

public static void main(String[] args) { B subobj = new B(1, 5);

(37)

subobj.Show(); }

}

Use of super to call super class constructor: The second use of the keyword super in java is to call super class constructor in the subclass. This functionality can be achieved just by using the following command.

super(param-list);

Here parameter list is the list of the parameter requires by the constructor in the super class. super must be the first statement executed inside a super class constructor. If we want to call the default constructor then we pass the empty parameter list.

Example 36 : method overriding - how to access original method class Animal

{

public void breath( ) {

System.out.println(" Breathing..."); }

}

class Fish extends Animal {

public void breath( ) {

System.out.println("Bubbling..."); }

public void newbreath( ) {

super.breath(); }

}

public class TestRide {

public static void main(String args[]) {

Fish f = new Fish(); f.newbreath(); f.breath();

(38)

}

output :: breathing... bubbling...

Dynamic method dispatch ( Run time polymorphism)

Any subclass object reference can be given to a super class variable. It is to suport runtime polymorphism. It lets us write code that works with many different types of objects, and decide on the actual object type at runtime.

Example 37 : Runtime polymorphism class A

{

public void disp( ) { System.out.println("printing A"); } } class B extends A {

public void disp( ) { System.out.println("printing B"); } } class C extends B {

public void disp( ) {

System.out.println("printing C"); }

}

public class TestApp {

public static void main(String args[]) {

A a1 = new A(); B b1 = new B(); C c1 = new C();

A oref;

oref = a1; oref.disp(); oref = b1; oref.disp();

(39)

} } output :: printing A printing B printing C

Abstract class

A class is abstract if one or more methods in it are defined by the abstract key word. A method is abstract when it has only declaration but no expansion in the base class.No objects can be instantiated from such a class. When writing classes , we run across cases where we can provide general code and it is upto the developer to customize it in a subclass. To make sure he customizes it, we make the method abstract. Such a class is also made abstract.

(40)

Example 38 : Demo of abstract class -- 1 abstract class A

{

abstract public void disp( ); }

class B extends A {

public void disp( ) {

system.out.println("java is simple"); }

}

public class TestApp {

public static void main(String args[]) { B b1 = new B( ); b1.disp( ); } }

Example 39 : Demo of abstract class -- 2 abstract class A

{

abstract String getData( ); public void disp( )

{ System.out.println( getData( ) ); } } class B extends A { String getData( ) {

String s = "java is simple"; return(s);

} }

public class TestApp {

public static void main(String args[]) {

(41)

B b1 = new B( ); b1.disp( );

} }

Note : constructors, private, static methods can NOT be abstract. Final modifier :: To stop overriding To stop Inheritance creating constants To stop overriding :: class Animal {

final void breath( ) {

System.out.println(" Breathing..."); }

}

class Fish extends Animal {

public void breath( ) ...???? ( not allowed ) {

System.out.println("Bubbling..."); }

}

To stop inheritance :: final class Animal {

public void breath( ) {

System.out.println(" Breathing..."); }

}

class Fish extends Animal ...????! ( no .. not allowed ) {

public void breath( ) {

System.out.println("Bubbling..."); }

}

(42)

final int a = 25;

a++; ...????! not allowed a = 50; ...????! not allowed

is-a relation :: standard inheritance refers to is-a relation class A { void disp( ) { System.out.println("from A"); } }

class B extends A // B is-a A { B( ) { disp( ); } }

public class TestApp {

public static void main(String args[]) {

B b1 = new B();

} }

has-a relation :: It is a state when one object holds other object instances. class A { void disp( ) { System.out.println("from A"); } } class B { A a1; // B has-a A

(43)

B( ) {

a1 = new A( );

a1.disp( ) ; //The disp of A is avilable to obj B }

}

public class TestApp {

public static void main(String args[]) {

B b1 = new B();

} }

java Object class ::

Every class in java is derived automatically from java.lang.Object class. All classes in java are subclasses

Every object thus inherits certain methods. some of them

boolean equals(ob) :: used to check whether an object ob equals to this one

protected void finalize() :: called by garbage collector

when it is about to dispose object

Class getClass() :: It gives the run time class of the object int hashCode() :: It gives a hashcode value of the object. Example 40 :: Demo of Object class

class A

{

public void disp( ) { System.out.println("printing A"); } } class B extends A {

public void disp( ) {

(44)

System.out.println("printing B"); }

}

class C extends B {

public void disp( ) {

System.out.println("printing C"); }

}

public class TestApp {

public static void main(String args[]) {

A a1 = new A(); B b1 = new B(); C c1 = new C();

A oref;

oref = a1; oref.disp();

System.out.println( "ref is " + oref.getClass() ); oref = b1; oref.disp();

System.out.println( "ref is " + oref.getClass() ); oref = c1; oref.disp();

System.out.println( "ref is " + oref.getClass() ); } } output :: printing A ref is class A printing B ref is class B printing C ref is class C

Garbage collection and memory management

Java has a built in process called garbage collector. It occurs

(45)

dispose of the memory that no longer has reference to it. However to make it happen we can set references to null

Example 41 :: Demo of garbage collection class A { void disp( ) { System.out.println("from A"); } }

public class TestApp {

public static void main(String args[]) {

int a[ ] = { 10,20,30 }; A b1 = new A(); int l ; b1.disp();

l = a.length;

System.out.println ( "l=" + l );

b1 = null; a = null; // making them null }

}

Example 42 :: Demo of garbage collection & finalize() method class Tester { public int k; Tester( int i ) { k = i; } } class A { int m1; Tester t; A( ) {

(46)

m1 = 5; t = new Tester(2500); } void disp( ) { System.out.println("from A"); }

protected void finalize() {

t = null; // inner object to null }

}

public class TestApp {

public static void main(String args[]) { A b1 = new A(); b1.disp(); b1 = null; } }

interfaces :

They provide templates of behaviour, that other classes can implement. They define the design and classes that implement the interface must

provide the implementation of the design.

In Abstract classes some methods may have definition, and leaving few undefined. In interfaces no method can be defined.

The data members in Abstract class can be variables or constants but they are only constants in an interface. A class can extend only one abstarct class. But a class may implement multiple interfaces, and thus provide an indirect way to multiple inheritance.

class Printer {

(47)

// set the params // print data ... } } interface Copier {

public void copyDocument( Document d); }

interface Fax {

public void transmitDocument(Document d); }

class MultiFunctionPrinter extends Printer implements Copier, Fax {

// the content ... }

Note : A method inside an interface can not be declared private or protected. They can carry public abstract modifiers only. The members must be public, static final making them constants.

interface Examp {

public static final int a = 3;

int b = 5; // effectively public static final public abstract void calc( );

void change( ); // effectively public and abstract }

Extending an interface :

Like classes interface can inherit from other interfaces. The sub interface acquires all the method definitions and constants of the super interfaces.

interface Newxerox extends Copier, Fax {

.... }

(48)

Marker Interface

In java language programming, interfaces with no methods are known as marker interfaces. Marker interfaces are Serializable, Clonable, SingleThreadModel, Event listener. Marker Interfaces are implemented by the classes or their super classes in order to add some functionality.

e.g. Suppose you want to persist (save) the state of an object then you have to implement the Serializable interface otherwise the compiler will throw an error. To make more clearly understand the concept of marker interface you should go through one more example.

Suppose the interface Clonable is neither implemented by a class named Myclass nor it's any super class, then a call to the method clone() on Myclass's object will give an error. This means, to add this functionality one should implement the Clonable interface. While the Clonable is an empty interface but it provides an important functionality.

Example 43 : Demo of Interfaces

import java.io.*;

interface StudentInter {

void getData( ) throws IOException; void showData();

int calcTot();

float calcPercent(); void menu();

}

class Student implements StudentInter {

int rno, m1,m2; string name;

public void getData( ) throws IOException {

DataInputStream d = new DataInputstream( System.in ); System.out.print( "Enter Rollno :" );

rno = Integer.parseInt( d.readLine( ) ); System.out.print( "Enter Name :" ); name = d.readLine( );

System.out.println( "Enter Sub 1 Mark :" ); m1 = Integer.parseInt( d.readLine( ) ); System.out.println("Enter Sub 2 Mark :" ); m2 = Integer.parseInt( d.readLine( ) );

(49)

}

public void showData( ) {

System.out.println ( "Rollno = " + rno); System.out.println ( "Name = " + name); System.out.println ( "mark1 = " + m1);

System.out.println ( "mark2 = " + m2); }

public int calcTot( ) {

return ( m1 + m2); }

public float calcPercent( ) {

int t = m1+ m2; return ( t / 2 ); }

public void menu( ) {

System.out.println ( "Enter 1 to get total"); System.out.println ( "Enter 2 to get percent"); }

}

public class TestStudent {

public static void main( String args[ ] ) {

Student s = new Student( ); s.getData();

s.showData(); int tot;

float per;

s.menu( ); // to display menu

DataInputStream d = new DataInputstream( System.in ); System.out.print( "Enter choice : " );

int n = Integer.parseInt( d.readLine( ) );

(50)

switch( n ) {

case 1: tot = s.calcTot();

System.out.println("total =" + tot); break;

case 2: per = s.calcPercent();

System.out.println("percent=" + per); break;

default: System.out.println( "incorrect choice" ); }

} }

Partially implementing an interface

Classes that partially implement an interface must be abstract as they are only expanding few methods.

Example 43 : interface A { void dispone(); void disptwo(); }

abstract class B implements A { void disptwo() { system.out.println("expanded from b); } } class C extends B { void dispone( ) { System.out.println("expanded from c"); } }

public class TestApp {

public static void main( string args[]) {

(51)

C k1 = new C(); k1.dispone(); k1.disptwo(); } } Inner classes ::

They are non static nested classes. They nest the definition of one class inside another.

They are usefull while handling events such as user closing a window etc.

Example 44 :Demo of inner classes class A

{

class B {

public void disp( ) { system.out.print("inside B .."); } } B b1; A( ) { b1 = new B( ); b1.disp( ); } }

public class TestApp {

public static void main(String args[]) {

A a1 = new A(); }

}

when we instantiate Object a1 of class A, it instantiates internal object b1 of class B.

(52)

ProcessBuilder class ::

An Operating system process can be created using this class, and it manage all the process attributes. It is not at all synchronized.

Example 45 :: Demo of ProcessBuilder class import java.io.*;

public class TestApp {

public static void main(String args) throws IOException { ProcessBuilder pb1; pb1 = new ProcessBuilder("notepad.exe","first.java"); pb1.start( ); } }

(53)

Chapter 5

Exception Handling

Exception is a runtime error , that may cause abnormal termination of the program during its execution. When an error occurs within a java method , the method creates an exception object and hands it off

( Throwing) to the runtime system. This exception object contain

information about exception, its type, state of the program when it occured. The runtime system searches for appropriate block of code to handle the exception.

If there is no appropriate handler, with in that block the serach

progresses up through the call stack, until an appropriate handler is found. If no such handler is found, the runtime system stops and the program

terminates.

public class Divide {

public static void main(String args[]) {

System.out.println("prog starts here.."); int a,b,c;

a = Integer.parseInt(args[0]); b = integer.parseInt(args[1]); c = a/b;

System.out.println("c="+ c);

System.out.println("program ends here.."); }

}

Running with 4 cases as below would give a picture : case 1 : java Divide 4 2

case 2 : java Divide 4 case 3 : java Divide a 2 case 4 : java Divide 4 0

To prevent interuption of the programs flow from exceptions such as the ones shown above, handlers are used to catch such exceptions and handle them appropriately through cleanup or message notification.

(54)

There are three types of Exceptions:

1. Checked Exceptions - These are the exceptions which occur during the compile time of the program. The compiler checks at the compile time that whether the program contains handlers for checked exceptions or not. These exceptions do not extend RuntimeException class and must be handled to avoid a compile-time error by the programmer. These exceptional conditions should be anticipated and recovered by an application. Furthermore Checked exceptions are required to be caught.

ClassNotFoundException NoSuchMethodException InterruptedException

Unchecked Exceptions - Unchecked exceptions are the exceptions which occur during the runtime of the program. Unchecked exceptions are internal to the application and extend the java.lang.RuntimeException that is inherited from java.lang.Exception class. These exceptions cannot be anticipated and recovered like programming bugs, such as logic errors or improper use of an API. These type of exceptions are also called Runtime exceptions that are usually caused by data errors, like arithmetic overflow,

divide by zero etc.

Here is the list of unchecked exceptions. ArrayIndexOutOfBoundsExc

eption

ArithmeticException NullPointerException

2.Error - An Error indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. Hence we conclude that Errors and runtime exceptions are together called as unchecked exceptions.

(55)

The exception classes can be explained as well seeing the hierarchy structure:

The java.lang package defines several classes and exceptions. Some of these classes are not checked while some other classes are checked.

EXCEPTIONS DESCRIPTION CHECKED UNCHECKED

ArithmeticException Arithmeticsuch as a divide by errors zero

- YES

ArrayIndexOutOfBoundsExc

eption Arrays index is not within array.length - YES ClassNotFoundException Related Class not found YES -IOException InputOuput field not found YES

-IllegalArgumentException Illegalwhen calling a argument

method - YES

InterruptedException One thread has been interrupted by another thread

YES

-NoSuchMethodException Nonexistent method YES -NullPointerException Invalid use of null reference - YES

NumberFormatException Invalid string for conversion to

(56)

As you have come to know that exceptions are Objects that means an object is thrown when you throw an exception. Moreover only those objects could be thrown whose classes are derived from Throwable.

It is interesting to note here that the objects of your own design could also be thrown provided that they should be the subclass of some member of the Throwable family. Also the throwable classes which are defined by you must extend Exception class.

Handling Exceptions in java

It is done using five key words try, catch, throw, throws, finally try

{

// statements that may throw exception } catch( Exceptiontype-1 e) { // statements to handle } catch( Exceptiontype-2 e) { // statements to handle } finally {

// clean up code or exit code(optional) }

The code in the finally block always gets executed regardless of what happens with in the try block. It is used to close files, data base connections , Sockets etc.

When exception occurs the method may instantiate an exception object and hand it to the run time system to deal with it.

The exception object carry the following 1. Type of exception - its class

2. Where it occured - stack trace

3. Context information - message and state

(57)

The arguement type in the catch clause is from throwable class or one of its subclasses. Once an exception is thrown , the block from where it is thown expires and control can not return back to the throw point.

Java uses a termination model of handling exception rather than resumption model.

Throwable class ::

It is the super class in the hierarchy, under java.lang.Object. An exception object is an instance of throwable class or any of its sub class. The Throwable class provides a set of methods apart from various

constructors

Throwable() :

Throwable(String message) :

getMessage() : retuns the message from the object or null printStackTrace() : print the stack trace

A stack Trace is a list of methods excecuted in sequence that lead to the exception.

Example 46 ::

public class Divide {

public static void main(String args[]) {

System.out.println("prog starts here.."); int a,b,c; try { a = Integer.parseInt(args[0]); b = integer.parseInt(args[1]); c = a/b; System.out.println("c="+ c); } catch ( NumberFormatException e) { system.out.println("Invalid argumets"); }

(58)

catch ( ArithmeticException e) {

system.out.println("Second Arg can not be zero"); }

catch ( ArayIndexOutOfBoundsException e) {

system.out.println("pass proper args"); }

System.out.println("program ends here.."); }

}

Order of Catch Blocks ::

The order of catch blocks are important when there are multiple catch blocks. The exception subclasss must come before any of its super class. Otherwise the subclass exception never gets executed.

Example 47 : incorrect ordering of Exception public class Divide

{

public static void main(String args[]) {

System.out.println("prog starts here.."); int a,b,c; try { a = Integer.parseInt(args[0]); b = integer.parseInt(args[1]); c = a/b; System.out.println("c="+ c); } catch ( Exception e) { System.out.println("It is " + e"); } catch ( ArithmeticException e) {

System.out.println("Second Arg can not be zero"); }

(59)

} }

Hence it is improtant to handle right exception in the right context. Nested try statements ::

Each time a try in entered , the context of the Exception is pushed on to the stack. If an inner try does not have a catch for an exception, the stack is unwound and catch belonging to next try is inspected for a match. Example 48 : Demo nested try

public class Divide {

public static void main(String args[]) {

System.out.println("prog starts here.."); int a,b,c; try { a = Integer.parseInt(args[0]); b = Integer.parseInt(args[1]); try { c = a/b; System.out.println("c="+ c); } catch ( ArithmeticException e) {

System.out.println("Sec.Arg cannot be zero"); } } catch ( NumberFotmatException e) { System.out.println("Invalid argumets"); } catch ( ArayIndexOutOfBoundsException e) {

(60)

System.out.println("pass proper args"); }

System.out.println("program ends here.."); }

}

Redirecting Exceptions using "throws" ::

When an exception can occur in a method, then it is supposed to be handled, or atleast explicitely warn the potential callers about its

possibility. This is done using a throws clause in the method declaration so that it can be passed to a different method in the call stack.

void Divide( ) throws Exception-A, Exception-B {

}

Example 49:: demo of throws public class Testthrows {

public static void main(String args[]) {

int i; int n=args.length; try { for( i=0;i<n;i++) dispnames(args[i]); } catch ( ClassNotFoundException e) {

System.out.println("not found " + e); }

}

static void dispnames(String s) throws ClassNotFoundException {

Class c = Class.forName(s);

System.out.println("class name " + c.getName()); }

}

References

Related documents

A 3-parameter cubic equation of state NEoS associated with the Mathias-Copeman alpha function, and with vdW classical mixing rules was used for the modelling calculations, and leads

The state of an HPB agent is defined by the tuple hB; D; Ii, where B is the agent’s current belief state (i.e., a probability distribution over the states S, defined below), D is

Complete social and political equality for the Palestinian Arab minority in Israel is only possible, even purely as an idea, if the notion of a Jewish state is understood simply as

Specific ablation of DP1 receptor in vascular endothelial cells, colonic epithelium, and myeloid cells augmented DSS/TNBS-induced colitis in mice through increasing

Critical Success Factors for Improving Project Management Efficiency and Reducing Project Completion Time A more efficient project management process will help to reduce

In the present study, we aimed to investigate physiological changes and metabolic signatures of the M. growth phases, blastospores and hyphae. Specifically, we hypothesized

The VX Cycle offers a broad range of scales for the cost-effective production of LNG/CCNG, and the Cycle can be integrated with existing CNG stations, pipeline compressor stations

Member, Pennsylvania Physical Therapy Association 2000-present Member, Virginia Physical Therapy Association 2006-2012 Member, Virginia Physical Therapy Association 2006-2012