[Go to site: main page, start]

0% found this document useful (0 votes)
11 views67 pages

Java Basics: Constructors & Inheritance

The document covers fundamental concepts of Java programming, including constructors, inheritance, static members, method overloading, method overriding, abstract classes, and the final keyword. It explains how constructors create class instances, the types and benefits of inheritance, and the use of static members and methods. Additionally, it discusses method overloading and overriding, emphasizing their roles in achieving polymorphism and code reusability.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views67 pages

Java Basics: Constructors & Inheritance

The document covers fundamental concepts of Java programming, including constructors, inheritance, static members, method overloading, method overriding, abstract classes, and the final keyword. It explains how constructors create class instances, the types and benefits of inheritance, and the use of static members and methods. Additionally, it discusses method overloading and overriding, emphasizing their roles in achieving polymorphism and code reusability.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Unit I

[Link]

[Link]

[Link] members

[Link] OVERLOADING,METHOD OVERRIDING

[Link] CLASS

[Link] keyword

7. String classes

1. Constructors

Constructor is a block of code that allows you to create an object of class. This can also be called
creating an instance. Constructor looks like a method but it’s not, for example methods can have
any return type or no return type (considered as void) but constructors don’t have any return type
not even void.

public class StudentData


{
private int stuID;
private String stuName;
private int stuAge;
StudentData()
{
//Default constructor
stuID = 100;
stuName = "New Student";
stuAge = 18;
}
StudentData(int num1, String str, int num2)
{
//Parameterized constructor
stuID = num1;
stuName = str;
stuAge = num2;
}
//Getter and setter methods
public int getStuID() {
return stuID;
}
public void setStuID(int stuID) {
[Link] = stuID;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
[Link] = stuName;
}
public int getStuAge() {
return stuAge;
}
public void setStuAge(int stuAge) {
[Link] = stuAge;
}
}

class TestOverloading
{
public static void main(String args[])
{
//This object creation would call the default constructor
StudentData myobj = new StudentData();
[Link]("Student Name is: "+[Link]());
[Link]("Student Age is: "+[Link]());
[Link]("Student ID is: "+[Link]());

/*This object creation would call the parameterized


* constructor StudentData(int, String, int)*/
StudentData myobj2 = new StudentData(555, "Chaitanya", 25);
[Link]("Student Name is: "+[Link]());
[Link]("Student Age is: "+[Link]());
[Link]("Student ID is: "+[Link]());
}
}
Output:

Student Name is: New Student


Student Age is: 18
Student ID is: 100
Student Name is: Chaitanya
Student Age is: 25
Student ID is: 555

[Link]
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.

The idea behind inheritance in java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of parent
class, and you can add new methods and fields also.

Inheritance represents the IS-A relationship, also known as parent-child relationship.

use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

Syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}

The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.

The class which is inherited is called parent or super class and the new class is called child or
subclass.

1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. [Link]("Programmer salary is:"+[Link]);
9. [Link]("Bonus of Programmer is:"+[Link]);
10. }
11. }
Test it Now
Programmer salary is:40000.0
Bonus of programmer is:10000

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We

will learn about interfaces later.

1) Single Inheritance

Single inheritance is damn easy to understand. When a class extends another one class only then
we call it a single inheritance. The below flow diagram shows that class B extends only one
class which is A. Here A is a parent class of B and B would be a child class of A.

Single Inheritance example program in Java


Class A
{
public void methodA()
{
[Link]("Base class method");
}
}

Class B extends A
{
public void methodB()
{
[Link]("Child class method");
}
public static void main(String args[])
{
B obj = new B();
[Link](); //calling super class method
[Link](); //calling local method
}
}
2) Multiple Inheritance

“Multiple Inheritance” refers to the concept of one class extending (Or inherits) more than one
base class. The inheritance we learnt earlier had the concept of one base class or parent. The
problem with “multiple inheritance” is that the derived class will have to manage the dependency
on two base classes.

To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.

Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If
A and B classes have same method and you call it from child class object, there will be
ambiguity to call method of A or B class.

3) Multilevel Inheritance
Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a
derived class, thereby making this derived class the base class for the new class. As you can see
in below flow diagram C is subclass or child class of B and B is a child class of A. For more
details and example refer – Multilevel inheritance in Java.

Multilevel Inheritance example program in Java

Class X
{
public void methodX()
{
[Link]("Class X method");
}
}
Class Y extends X
{
public void methodY()
{
[Link]("class Y method");
}
}
Class Z extends Y
{
public void methodZ()
{
[Link]("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
[Link](); //calling grand parent class method
[Link](); //calling parent class method
[Link](); //calling local method
}
}
4) Hierarchical Inheritance

In such kind of inheritance one class is inherited by many sub classes. In below example class
B,C and D inherits the same class A. A is parent class (or base class) of B,C & D. Read More
at – Hierarchical Inheritance in java with example program.

Class A
{
public void methodA()
{
[Link]("method of Class A");
}
}
Class B extends A
{
public void methodB()
{
[Link]("method of Class B");
}
}
Class C extends A
{
public void methodC()
{
[Link]("method of Class C");
}
}
Class D extends A
{
public void methodD()
{
[Link]("method of Class D");
}
}
Class MyClass
{
public void methodB()
{
[Link]("method of Class B");
}
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
[Link]();
[Link]();
[Link]();
}
}
The above would run perfectly fine with no errors and the output would be –
method of Class A
method of Class A
method of Class A

5) Hybrid Inheritance

In simple terms you can say that Hybrid inheritance is a combination


of Single andMultiple inheritance. A typical flow diagram would look like below. A hybrid
inheritance can be achieved in the java in a same way as multiple inheritance can be!! Using
interfaces. yes you heard it right. By using interfaces you can have multiple as well as hybrid
inheritance in Java.

Read the full article here – hybrid inheritance in java with example program.
Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.

Consider a scenario where A, B and C are three classes. The C class inherits A and B classes.
If A and B classes have same method and you call it from child class object, there will be
ambiguity to call method of A or B class.

3..JAVA – STATIC CLASS, BLOCK, METHODS AND VARIABLES

In this tutorial we will discuss the use of static keyword in Java. It can be used along with
Class name, Variables, Methods and block.

1. static class
2. static block
3. static methods
4. static variables

Static Class

A Class can be made static only if it is a nested Class. The nested static class can be accessed
without having an object of outer class.

Example 1:

class Example1{
//Static class
static class X{
static String str="Inside Class X";
}
public static void main(String args[])
{
[Link]="Inside Class Example1";
[Link]("String stored in str is- "+ [Link]);
}
}
Output:

String stored in str is- Inside Class Example1


Static Block

Static block is mostly used for changing the default values of static [Link] block gets
executed when the class is loaded in the memory.
A class can have multiple Static blocks, which will execute in the same sequence in which they
have been written into the program.

Example 1: Single static block

class Example3{
static int num;
static String mystr;
static{
num = 97;
mystr = "Static keyword in Java";
}
public static void main(String args[])
{
[Link]("Value of num="+num);
[Link]("Value of mystr="+mystr);
}
}
Output:

Value of num=97
Value of mystr=Static Keyword in Java
Static Methods

Static Methods can access class variables without using object of the class. It can access non-
static methods and non-static variables by using objects. Static methods can be accessed directly
in static and non-static methods.
Example: Static method display()

class Example6{
static int i;
static String s;
//Static method
static void display()
{
//Its a Static method
Example6 obj1=new Example6();
[Link]("i:"+obj1.i);
[Link]("i:"+obj1.i);
}

void funcn()
{
//Static method called in non-static method
display();
}
public static void main(String args[]) //Its a Static Method
{
//Static method called in another static method
display();
}
}
Output:

i:0
i:0
Static Variables

 Static variables are also known as Class Variables.


 Such variables get default values based on the data type.

 Data stored in static variables is common for all the objects( or instances ) of that Class.
 Memory allocation for such variables only happens once when the class is loaded in the
memory.

 These variables can be accessed in any other class using class name.

 Unlike non-static variables, such variables can be accessed directly in static and non-
static methods.

Example 1: Static variables can be accessed without reference in Static method

class Example7{
static int var1;
static String var2;
//Its a Static Method
public static void main(String args[])
{
[Link]("Var1 is:"+Var1);
[Link]("Var2 is:"+Var2);
}
}
Output:

Var1 is:0
Var2 is:null
As you can see in the above example that both the variables are accessed in void main method
without any object(reference).

Example 2: Static variables are common for all instances

package [Link];
class Example8{
static int Var1=77; //Static integer variable
String Var2;//non-static string variable

public static void main(String args[])


{
Example8 ob1 = new Example8();
Example8 ob2 = new Example8();
ob1.Var1=88;
ob1.Var2="I'm Object1";
ob2.Var2="I'm Object2";
[Link]("ob1 integer:"+ob1.Var1);
[Link]("ob1 String:"+ob1.Var2);
[Link]("ob2 integer:"+ob2.Var1);
[Link]("ob2 STring:"+ob2.Var2);
}
}
Output:

ob1 integer:88
ob1 String:I'm Object1
ob2 integer:88
ob2 String:I'm Object2
In above example String variable is non-static and integer variable is Static. So you can see that
String variable value is different for both objects but integer variable value is common for both
the instances as all the objects share the same copy of a static variable.

[Link] OVERLOADING AND METHODOVERRIDING

Method Overloading is a feature that allows a class to have two or more methods having same
name, if their argument lists are different. In the last tutorial we discussed constructor
overloading that allows a class to have more than one constructors having different argument
lists.

Argument lists could differ in –


1. Number of parameters.
2. Data type of parameters.
3. Sequence of Data type of parameters.

Method overloading is also known as Static Polymorphism.


Points to Note:
1. Static Polymorphism is also known as compile time binding or early binding.
2. Static binding happens at compile time. Method overloading is an example of static binding
where binding of method call to its definition happens at Compile time.

public class OverloadDemo


{
public static void main(String args[])
{
[Link]("sum of two integers");
sum(10,20);
[Link]("sum of two double
numbers"); sum(10.5,20.4);
[Link]("sum of three integers");
sum(10,20);
}
public static void sum(int num1,int num2)
{
int ans;
ans=num1+num2;
[Link](ans);
}
public static void sum(double num1, double num2)
{
double ans;
ans=num1+num2;
[Link](ans);
}
public static void sum(int num1,int num2,int num3)
{
int ans;
ans=num1+num2+num3;
[Link](ans);
}
}
SAMPLE OUTPUT:
Sum of two integers
30
Sum of two double numbers
30.9
Sum of three integers
60

Method overriding

Declaring a method in subclass which is already present in parent class is known as method
overriding.
Advantage of method overriding

The main advantage of method overriding is that the class can give its own specific
implementation to a inherited method without even modifying the parent class(base class).

class superclass
{
int x;
superclass(int x)
{
this.x=x;
}
void display() // base class method
{
[Link](x);
}
}
class subclass extends superclass
{
int y;
subclass(int x , int y)
{
super(x); // calls super class constructor
this.y=y;
}
void display() // derived class method
{
[Link](y);
}
}
class overriding
{
public static void main(String args[])
{
subclass s1=new subclass(100,200);
[Link](); // calls sub class method
}
}

Output

C:\Program Files\Java\jdk1.6.0_13\bin>javac [Link]

C:\Program Files\Java\jdk1.6.0_13\bin>java overriding


200
Method Overriding in dynamic method dispatch
Dynamic method dispatch is a technique which enables us to assign the base class reference to a
child class object. As you can see in the below example that the base class reference is assigned
to child class object.

In java, base class reference can be assigned objects of sub class. When methods of sub class
object are called through base class’s reference, the mapping / binding or function calls to
respective function takes place after running the program, at least possible moment. This kind of
binding is known as “late binding” or “dynamic binding” or “runtime polymorphism”.

 4 .//Program for Method Overriding / dynamic method dispatch/runtime


polymorphism/super keyword/constructor/inheritance

class shape //base class


{
int a,b;
shape( int a1,int b1)
{
a=a1;
b=b1;
}

public void display()


{}
}
class rectangle extends shape // subclass
{

rectangle(int a1,int b1)


{
super(a1,b1); // calls base class constructor
}
public void display() //method of derived class

{
[Link](“area of rectangle”+a*b);
}
}
class triangle extends shape //sub class
{
triangle(int a1,int b1)
{
super(a1,b1);
}

public void display() // method of derived class


{
[Link](“area of triangle”+0.5f *a*b);

}
}
class DispatchDemo

{
public static void main (String args[])

shape ob1= new shape();

reactangle ob2 = new rectangle();


triangle ob3 = new triangle();

shape r; // base class reference

r=ob1; [Link]();

r=ob2; // base class reference holds derived class object

[Link](); //since it holds rectangle object,the rectangle class method is called

r=ob3; // base class reference holds derived class object

[Link](); //since it holds triangle object,the trianlge class method is called

[Link] CLASS
 Abstract class is a class that cannot be instantiated. (you are not allowed to
create object of Abstract class).
 A class that is declared using “abstract” keyword is known as abstract class.
 It may or may not include abstract methods which means in abstract class you can have
concrete methods (methods with body) as well along with abstract methods ( without an
implementation, without braces, and followed by a semicolon).
 An abstract class has no use until unless it is extended by some other class.

 If you declare an abstract method (discussed below) in a class then you must declare
the class abstract as well. you can’t have abstract method in a non-abstract class.
need for abstract classes:

can generalize the super class from which child classes can share its methods.
The subclass of an abstract class which can create an object is called as "concrete class".

abstract Method:
1. It is a method, which has no body (definition) in the base class. The body should be
implemented in the sub class only.
2. Any class with at least one abstract method should be declared as abstract.
3. If the sub class is not implementing an abstract method, its sub class has to implement it.
4. It must be overridden. An abstract class must be extended and in a same way abstract
method must be overriden. Abstract method must be in a abstract class.

abstract class shape //abstract class


{
int a,b;

abstract public void display() // abstract method


{}
}
class rectangle extends shape // subclass
{

rectangle(int a1,int b1)


{
a=a1;
b=b1;
}
public void display() //method of derived class

{
[Link](“area of rectangle”+a*b);
}
}
class triangle extends shape //sub class
{
triangle(int a1,int b1)
{
a=a1;
b=b1;
}

public void display() // method of derived class

{
[Link](“area of triangle”+0.5f *a*b);

}
}
class DispatchDemo

{
public static void main (String args[])

reactangle ob2 = new rectangle();


triangle ob3 = new triangle();

shape r; // reference foe abstract class is created


r=ob2; // base class reference holds derived class object

[Link](); //since it holds rectangle object,the rectangle class method is called

r=ob3; // base class reference holds derived class object

[Link](); //since it holds triangle object,the trianlge class method is called

6..FINAL KEYWORD
This modifier can be applied to variables, methods and classes.

final data members:


Data member with final modifier becomes a constant.

final Method:
1. It is a method whose definition is preceded by keyword “final”.
final returntype funname()
{
}
2. It can’t be redefined in the sub class. This means that, a sub class can’t override it.

final class:
1. It is a class whose definition is preceded by “final”.
2. The final class can’t be sub classed or derived. This means that we can’t create a sub
class from a final class.

/ no inheritance
final class A
{
}

class B extends A
{
}

The above code gives compile error. Because class A is a final class, which can’t be derived.

[Link] CLASS , STRING BUFFER ,STRING TOKENIZER

String is a group of characters. To manipulate strings java provides the flg. classes.
1. String 2. StingBuffer

String:

It is used to create String objects. String objects are “immutable”. This means that they can’t be
modified. Though String is a class. It can be used as a data type.
Eg.
String s = ”java”;

StringBuffer:

It is also used to create string objects. But these objects are mutable (changeable). This means
that they can be modified. It should be instantiated as follows.

Eg.
StringBuffer s = new StringBuffer(“java”);

Constructors of String class:

String():
Creates a String object. Which is empty.
Eg.
String s = new String();

String (String str):


Creates a string object with given string.
Eg.
String s1= new String(“java”);
String s2=new String(s1);

String(char[] ch):
Creates a string object with given character array.
Eg.
Char ch={‘v’,’i’,’s’,’i’,’o’,’n’};
String s= new String (ch);

String (char ch[], int startindex, int numchar):


Creates a string object with from start index to num of characters of given array.

Eg.
Char ch[]={‘v’,’i’,’s’,’i’,’o’,’n’};
String s= new String(ch,2,5);

Methods of String class:

charAt(int):
returns the character specified by the index.. Eg.
String s=”hello java”; Char ch=[Link](4);

concat(String str):
It concatenates the given string with invoking string object and the result is assigned to a new
string.
Eg.
String s1= “Hello”; String s2=”java”; String s3=[Link](s2);

copyValueOf(char ch[]):
copies the given character array into a string object.

Eg.
char ch[]= {‘j’,’a’,’v’,’a’};
String s=[Link](ch);

copyValueOf(char ch[], int startindex, int numchar):


Copies the given character array from start index to number of characters into a string object.

Eg.
char ch[]= {‘j’,’a’,’v’,’a’};
String s=[Link](ch,2,2);
endsWith(String str):
It returns true. If the invoking string object ends with given string.

Eg.
String s=”Welcome to java”; boolean b=[Link](“java”);

startsWith(String str):
It returns true. If the invoking string object starts with given string.

Eg.
String s=”Welcome to java”; boolean b=[Link](“java”);

equals(obj):
Returns true if the invoking string object and given object are equal.

Eg.
String s1= “java”; String s2=”j2se”; boolean b=[Link](s1);

equalsIgnoreCase(obj):
Returns true if the invoking string object and given object are equal. But it ignores case.

getBytes():
Returns the invoking string object as a byte array.

Eg.
String s=”java”;
byte b[]= [Link]();

getChars(int startindex, int endindex, char ch[], int startindex):


it returns the invoking string object from start index to endindex to array ch at specified index.

Eg.
String s=”welcome to java”; Char ch[]=new char[20]; [Link](2,5,ch,0);

toLowerCase():
converts String object to lower case. Eg.
String s=new String (“hello java”); [Link]();

toUpperCase():
converts String object to upper case. Eg.
String s=new String (“hello java”);
[Link]();

trim():
It removes spaces in the invoking string object.
Eg.
String s = “ hai “; s.o.p(trim(s));

valueOf():
It is used to convert given parameter to a string. Eg.
String s= “ “; Int x=250;
S=[Link](x);

replace():
It is used to replace a character of invoking object with another character and result in assigned
to other string object.
Eg.
String s=”J2SE”;
String s2=[Link](“s”,”e”);

substring():
It returns a string within another string from specified index. Eg.
String s=”java is good”; String s1=[Link](5);

substring(int, int):
It returns a string from specified starting index to ending index of string object.
Eg.
String s=”java is good”; String s1=[Link](5,10);

indexOf():
It returns the index of specified string within the invoking string object. Eg.
String s=”java is good”; Int x =[Link](“is”);

lastIndexOf():
It returns the position / index of last occurrence of specified string in the invoking string object.
Eg.
String s=”java is good and is very nice”;

int x =[Link](“is”);

split():
It splits the invoking string object based on the criteria given as parameter and the result is
assigned to other string object.

Eg.
String s="hello, good, java"; String x[]=new String[5]; x=[Link](",");
for(int i=0;i<[Link];i++) [Link](x[i]);

Output: hello good java

replaceFirst():
Replaces the first occurance of the string (parameter1) other string (parameter2) and result is
assigned to another string object.

Eg.
String s=new String (“java is as good as any other language”); String s1=[Link](“as”,
“very”);
StringBuffer:

This class is also used to manipulate strings. It objects are mutable. This means that they can be
modified. This class belongs to [Link] package.

Constructors of StringBuffer

StringBuffer():
It creates an empty string buffer object.
Eg.
StringBuffer s= new StringBuffer();

StringBuffer(int):
It creates a string buffer object with initial capacity is 16. Eg.
StringBuffer s= new StringBuffer(16);
StringBuffer(String str):
It creates String Buffer object to given string. Eg.
StringBuffer s=new StringBuffer(“java”);

Methods of StringBuffer class:

length():
It returns the length of string buffer object. Eg.
StringBuffer s=new StringBuffer(“Welcome to java”); int x = [Link]();

capacity():
It sreturns the capacity of string buffer object.

Eg.
StringBuffer(“Welcome”);
Int x=[Link]();

ensureCapacity(int):
It is used to set capacity of StringBuffer object.

Eg.
StringBuffer s=new StringBuffer(“helloworld”); [Link](20);

setLength(int):
to set length of StringBuffer object.

Eg.
StringBuffer s=new StringBuffer(“hello world”); [Link](20);

charAt(int):
returns a character at specified index.

Eg.
StringBuffer(“Vision computer education”); Char ch=[Link](3);

setCharAt(int, char):
Set given char. of specified index. Eg.
StringBuffer s=new StringBuffer(“hello world”); [Link](3,k);
getChars(int startindex, int endindex, char target[], int target-startindex):
It copies a substring of StringBuffer object from start index to end index into target array.
Eg.
Char ch[]=new char[20];
SB= new SB(“hello, very good java”); [Link](1,4,ch,0);

append(String str):
To append given string to the string buffer object.

Eg.
StringBuffer s=new StringBuffer(“Hello”); [Link](“java”);

delete(int startindex, int endindex):


Deletes character of string buffer object from start index to end index. Eg.
StringBuffer s=new StringBuffer(“hello java”); [Link](3,6);

deleteCharAt(int):
Deletes character at specified index. Eg.
SB s=new SB(“j2me”); [Link](2);

replace():
It is used to replace some text of string buffer object with given string.

Eg.
SB s=new SB(“Hello King java”); [Link](2,7,”vision”);

STRING TOKENIZER

The string tokenizer class allows an application to break a string into tokens. The tokenization
method is much simpler than the one used by the StreamTokenizer class.
The StringTokenizer methods do not distinguish among identifiers, numbers, and quoted
strings, nor do they recognize and skip comments.

The set of delimiters (the characters that separate tokens) may be specified either at creation
time or on a per-token basis.

An instance of StringTokenizer behaves in one of two ways, depending on whether it was


created with the returnDelims flag having the value true or false:

 If the flag is false, delimiter characters serve to separate tokens. A token is a maximal
sequence of consecutive characters that are not delimiters.
 If the flag is true, delimiter characters are themselves considered to be tokens. A token
is thus either one delimiter character, or a maximal sequence of consecutive characters
that are not delimiters.

A StringTokenizer object internally maintains a current position within the string to be


tokenized. Some operations advance this current position past the characters processed.
A token is returned by taking a substring of the string that was used to create
the StringTokenizer object.

import [Link];
public class App {
public static void main(String[] args) {
String str = "This is String , created by NANDHA";
StringTokenizer st = new StringTokenizer(str);
[Link]("---- Split by space ------");
while ([Link]()) {
[Link]([Link]());
}
[Link]("---- Split by comma ',' ------");
StringTokenizer st2 = new StringTokenizer(str, ",");
while ([Link]()) {
[Link]([Link]());
}
}
}
SAMPLE OUTPUT:
---- Split by space ------
This
is
String
,
created
by
NANDHA
---- Split by comma ',' ------
This is String
created by NANDHA
UNIT II
[Link]
[Link]
[Link] COLLECTION CLASSES AND INTERFACES
4. ASSERTION
5. JAVA I/O STREAMS
[Link]
[Link] Classes
[Link]

[Link]

A package is a container of classes and interfaces. A package represents a directory that


contains related group of classes and interfaces

Advantages of using a package

 Reusability: Reusability of code is one of the most important requirements in the


software industry. Reusability saves time, effort and also ensures consistency. A class once
developed can be reused by any number of programs wishing to incorporate the class in that
particular program.
 Easy to locate the files.

 In real life situation there may arise scenarios where we need to define files of the same
name. This may lead to “name-space collisions”. Packages are a way of avoiding “name-
space collisions”.

Types of package:
1) User defined package: The package we create is called user-defined package.
2) Built-in package: The already defined package like [Link].*, [Link].* etc are known as
built-in packages.

Defining a Package:
This statement should be used in the beginning of the program to include that program in that
particular package.
package <package name>;

User-Defined packages:
The users of the Java language can also create their own packages. They are called user-defined
packages. User-defined packages can also be imported into other classes and used exactly in the
same way as the Built-in packages.
Creating and Importing Packages:
package packagename; //to create a package
package [Link];//to create a sub package within a package.
e.g.: package pack;
 The first statement in the program must be package statement while creating a package.
 While creating a package except instance variables, declare all the members and the class
itself as public then only the public members are available outside the package to other
programs.
Program 1:
package college;
public class student
{
int regno;
String name;
public student(int r,String na)
{
regno=r;
name=na;
}
public void print()
{
[Link]("Regno: "+regno );
[Link]("Name: "+name );
}
}
package course;
public class engineering
{
int regno;
String branch;
String year;
public engineering(int r, String br, String yr)
{
regno=r;
branch=br;
year=yr;
}
public void print()
{
[Link]("Regno: "+regno);
[Link]("Branch: "+branch);
[Link]("Year: "+year);
}
}Compiling the above program:
The –d option tells the Java compiler to create a separate directory and place the .class file in
that directory (package). The (.) dot after –d indicates that the package should be created in the
current directory

Access Specifiers

 private: accessible only in the class


 no modifier: so-called “package” access — accessible only in the same package

 protected: accessible (inherited) by subclasses, and accessible by code in same package


 public: accessible anywhere the class is accessible, and inherited by subclasses

Notice that private protected is not syntactically legal.

[Link]
Def: It is a collection of final data members and abstract methods.
 It is nothing but a pure abstract class. It has only abstract methods.
 Interface looks like class but it is not a class.
 An interface can have methods and variables just like the class but the methods declared
in interface are by default abstract (only method signature, no body). Also, the variables
declared in an interface are public, static & final by default.

1) We can’t instantiate an interface in java.

2) Interface provides complete abstraction as none of its methods can have body. On the other
hand, abstract class provides partial abstraction as it can have abstract and concrete(methods
with body) methods both.

3) implements keyword is used by classes to implement an interface.

4) While providing implementation in class of any method of an interface, it needs to be


mentioned as public.

5) Class implementing any interface must implement all the methods, otherwise the class should
be declared as “abstract”.

6) Interface cannot be declared as private, protected or transient.

7) All the interface methods are by default abstract and public.

8) Variables declared in interface are public, static and final by default.

interface Try
{
int a=10;
public int a=10;
public static final int a=10;
final int a=10;
static int a=0;
}
All of the above statements are identical.

9) Interface variables must be initialized at the time of declaration otherwise compiler will
through an error.

interface Try
{
int x;//Compile-time error
}
Above code will throw a compile time error as the value of the variable x is not initialized at the
time of declaration.

10) Inside any implementation class, you cannot change the variables declared in interface
because by default, they are public, static and final. Here we are implementing the interface
“Try” which has a variable x. When we tried to set the value for variable x we got compilation
error as the variable x is public static final by default and final variables can not be re-initialized.

class Sample implements Try


{
public static void main(String args[])
{
x=20; //compile time error
}
}
11) Any interface can extend any interface but cannot implement it. Class implements interface
and interface extends interface.

12) A class can implement any number of interfaces.

13) If there are two or more same methods in two interfaces and a class implements both
interfaces, implementation of the method once is enough.

use of interfaces

As mentioned above they are used for abstraction. Since methods in interfaces do not have body,
they have to be implemented by the class before you can access them. The class that implements
interface must implement all the methods of that interface. Also, java programming language
does not support multiple inheritance, using interfaces we can achieve this as a class can
implement more than one interfaces, however it cannot extend more than one classes.
Syn:
interface Interfacename
{
data members ; // final data members methods() ; // abstract methods
}

class Classname implements Interfacename


{

data members ;
methods()
}

interface Area
{
float compute(float x, float y);
}
class Rectangle implements Area
{
public float compute(float x, float y)
{
return(x * y);
}
}
class Triangle implements Area
{
public float compute(float x,float y)
{
return(x * y/2);
}
}
class InterfaceArea
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Triangle tri = new Triangle();
Area area;
area = rect;
[Link]("Area Of Rectangle = "+
[Link](1,2)); area = tri;
[Link]("Area Of Triangle = "+
[Link](10,2)); }
}
SAMPLE OUTPUT:
Area Of Rectangle = 2.0
Area Of Triangle = 10.0
Interfaces
abstract Classes

abstract class can extend only one class or


1 interface can extend any number of interfaces at a time
one abstract class at a time

abstract class can extend from a class or


2 interface can extend only from an interface
from an abstract class

abstract class can have both abstract and


3 interface can have only abstract methods
concrete methods

4 A class can extend only one abstract class A class can implement any number of interfaces

In abstract class keyword ‘abstract’ is


In an interface keyword ‘abstract’ is optional to declare
5 mandatory to declare a method as an
a method as an abstractk
abstract

abstract class can have protected , public Interface can have only public abstract methods i.e. by
6
and public abstract methods default

abstract class can have static, final or static


interface can have only static final (constant) variable
7
final variable with any access specifier i.e. by default
[Link] INTERFACES AND COLLECTION CLASSES

Collections in java is a framework that provides an architecture to store and manipulate the group of objects.

All the operations that you perform on a data such as searching, sorting, insertion, manipulation, deletion etc. can be performed
by Java Collections.

Java Collection simply means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue,
Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).

What is Collection in java

Collection represents a single unit of objects i.e. a group.

What is framework in java

o provides readymade architecture.


o represents set of classes and interface.
o is optional.

What is Collection framework

Collection framework represents a unified architecture for storing and manipulating group of objects. It has:

1. Interfaces and its implementations i.e. classes


2. Algorithm
Methods of Collection interface

There are many methods declared in the Collection interface. They are as follows:

No. Method Description

1 public boolean add(Object is used to insert an element in this collection.


element)

2 public boolean is used to insert the specified collection elements in


addAll(Collection c) the invoking collection.

3 public boolean remove(Object is used to delete an element from this collection.


element)

4 public boolean is used to delete all the elements of specified


removeAll(Collection c) collection from the invoking collection.

5 public boolean is used to delete all the elements of invoking


retainAll(Collection c) collection except the specified collection.

6 public int size() return the total number of elements in the


collection.

7 public void clear() removes the total no of element from the collection.

8 public boolean contains(Object is used to search an element.


element)

9 public boolean is used to search the specified collection in this


containsAll(Collection c) collection.

10 public Iterator iterator() returns an iterator.

11 public Object[] toArray() converts collection into array.

12 public boolean isEmpty() checks if collection is empty.

13 public boolean equals(Object matches two collection.


element)

14 public int hashCode() returns the hashcode number for collection.

Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class and implements List interface.

The important points about Java ArrayList class are:

o Java ArrayList class can contain duplicate elements.


o Java ArrayList class maintains insertion order.
o Java ArrayList class is non synchronized.
o Java ArrayList allows random access because array works at the index basis.
o In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any element is removed
from the array list.

User-defined class objects in Java ArrayList

Let's see an example where we are storing Student class object in array list.

class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
[Link]=rollno;
[Link]=name;
[Link]=age;
}
. }
import [Link].*;
public class TestCollection3{
public static void main(String args[]){
//Creating user-defined class objects
Student s1=new Student(101,"Sonoo",23);
Student s2=new Student(102,"Ravi",21);
Student s2=new Student(103,"Hanumat",25);
//creating arraylist
ArrayList<Student> al=new ArrayList<Student>();
. [Link](s1);//adding Student class object
. [Link](s2);
. [Link](s3);
. //Getting Iterator
. Iterator itr=[Link]();
. //traversing elements of ArrayList object
. while([Link]()){
. Student st=(Student)[Link]();
. [Link]([Link]+" "+[Link]+" "+[Link]);
. }
. }
. }
Test it Now
101 Sonoo 23
102 Ravi 21
103 Hanumat 25

Java LinkedList class uses doubly linked list to store the elements. It provides a linked-list data structure. It inherits the
AbstractList class and implements List and Deque interfaces.

The important points about Java LinkedList are:

o Java LinkedList class can contain duplicate elements.


o Java LinkedList class maintains insertion order.
o Java LinkedList class is non synchronized.
o In Java LinkedList class, manipulation is fast because no shifting needs to be occurred.
o Java LinkedList class can be used as list, stack or queue.

ArrayList LinkedList

1) ArrayList internally uses dynamic LinkedList internally uses doubly


array to store the elements. linked list to store the elements.

2) Manipulation with ArrayList Manipulation with LinkedList


is slow because it internally uses array. is faster than ArrayList because it uses
If any element is removed from the doubly linked list so no bit shifting is
array, all the bits are shifted in memory. required in memory.

3) ArrayList class can act as a list only LinkedList class can act as a list and
because it implements List only. queue both because it implements List
and Deque interfaces.

4) ArrayList is better for storing and LinkedList is better for


accessing data. manipulating data.
import [Link].*;
class TestArrayLinked{
public static void main(String args[]){

List<String> al=new ArrayList<String>();//creating arraylist


[Link]("Ravi");//adding object in arraylist
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
.
. List<String> al2=new LinkedList<String>();//creating linkedlist
. [Link]("James");//adding object in linkedlist
. [Link]("Serena");
. [Link]("Swati");
. [Link]("Junaid");
.
. [Link]("arraylist: "+al);
. [Link]("linkedlist: "+al2);
. }
. }
Test it Now

Output:

arraylist: [Ravi,Vijay,Ravi,Ajay]
linkedlist: [James,Serena,Swati,Junaid]

Java ListIterator Interface

ListIterator Interface is used to traverse the element in backward and forward direction.

import [Link].*;
public class TestCollection8{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
[Link]("Amit");
[Link]("Vijay");
[Link]("Kumar");
[Link](1,"Sachin");
[Link]("element at 2nd position: "+[Link](2));
. ListIterator<String> itr=[Link]();
. [Link]("traversing elements in forward direction...");
while([Link]()){
. [Link]([Link]());
. }
. [Link]("traversing elements in backward direction...");
while([Link]()){
. [Link]([Link]());
. }
. }
. }
Test it Now

Output:

element at 2nd position: Vijay


traversing elements in forward direction...
Amit
Sachin
Vijay
Kumar
traversing elements in backward direction...
Kumar
Vijay
Sachin
Amit

Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and
implements Set interface.

The important points about Java HashSet class are:

o HashSet stores the elements by using a mechanism called hashing.


o HashSet contains unique elements only.

Difference between List and Set

List can contain duplicate elements whereas Set contains unique elements only.

Java LinkedHashSet class is a Hash table and Linked list implementation of the set interface. It inherits HashSet class and
implements Set interface.

The important points about Java LinkedHashSet class are:

o Contains unique elements only like HashSet.


o Provides all optional set operations, and permits null elements.

Maintains insertion order

Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements
NavigableSet interface. The objects of TreeSet class are stored in ascending order.
The important points about Java TreeSet class are:

o Contains unique elements only like HashSet.


o Access and retrieval times are quiet fast.
o Maintains ascending order.

[Link]

An assertion is a statement in the JavaTM programming language that enables you to test your assumptions about your program.
For example, if you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than
the speed of light.

Each assertion contains a boolean expression that you believe will be true when the assertion executes. If it is not true, the
system will throw an error. By verifying that the boolean expression is indeed true, the assertion confirms your assumptions
about the behavior of your program, increasing your confidence that the program is free of errors.

The assertion statement has two forms. The first, simpler form is:

assert Expression1 ;
where Expression1 is a boolean expression. When the system runs the assertion, it evaluates Expression1 and if it
is false throws an AssertionError with no detail message.

The second form of the assertion statement is:

assert Expression1 : Expression2 ;


where:

 Expression1 is a boolean expression.


 Expression2 is an expression that has a value. (It cannot be an invocation of a method that is declared void.)

Use this version of the assert statement to provide a detail message for the AssertionError. The system passes the value
of Expression2 to the appropriate AssertionError constructor, which uses the string representation of the value as the error's
detail message.

The purpose of the detail message is to capture and communicate the details of the assertion failure. The message should
allow you to diagnose and ultimately fix the error that led the assertion to fail

Where assertions cannot be used?


 Do not use assertions for argument checking in public methods.
 Do not use assertions to do any work that your application requires for correct operation.

Enabling and Disabling Assertions


By default, assertions are disabled at runtime. Two command-line switches allow you to selectively enable or disable
assertions.

To enable assertions at various granularities, use the -enableassertions, or -ea, switch. To disable assertions at various
granularities, use the -disableassertions, or -da, switch

PROGRAM FOR ASSERTION

class MarkAssertDemo
{
static float maximummarks=100;
static float changes(float mark)
{
maximummarks=maximummarks-mark;
[Link]("The maximummark is:" + maximummarks);
return maximummarks;
}
public static void main(String args[])
{
float g;
for(int i=0;i<5;i++)
{
g=changes(15);
assert maximummarks>=40.00:"marks is below 40.";
}
}
}
SAMPLE OUTPUT:
javac [Link]
java –ae MarkAssertDemo
The maximummark is:85.0
The maximummark is:70.0
The maximummark is:55.0
The maximummark is:40.0
The maximummark is:25.0
Exception in thread "main" [Link]: marks is below 40.
at [Link]([Link])

[Link] I/O STREAMS


Stream is an abstract demonstration of input or output device to write or read data.
Byte Streams:
It supports 8-bit input and output operations. There are two classes of byte stream
o InputStream
o OutputStream

InputStream:
The InputStream class is used for reading the data such as a byte and array of bytes from an input source. An input source can
be a file, a string, or memory that may contain the data. It is an abstract class that defines the programming interface for all
input streams that are inherited from it.
InputStream
- ByteArrayInputStream
- FileInputStream
- ObjectInputStream
- FilterInputStream
- PipedInputStream
- StringBufferInputStream
- FilterInputStream
o BufferedInputStream
o DataInputStream
o LineNumberInputStream
o PushbackInputStream

OutputStream:
The OutputStream class is a sibling to InputStream that is used for writing byte and array of bytes to an output source. Similar
to input sources, an output source can be anything such as a file, a string, or memory containing the data.
OutputStream
- ByteArrayOutputStream
- FileOutputStream
- ObjectOutputStream
- FilterInputStream
- PipedOutputStream
- StringBufferInputStream
- FilterOutputStream
o BufferedOutputStream
o DataOutputStream
o PrintStream
OutputStream is also inherited from the Object class. Each class of the OutputStream provided by the [Link] package is
intended for a different purpose.

PROGRAM TO COPY ONE FILE TO ANOTHER – BYTE STREAM

import [Link];
import [Link];
import [Link];
import [Link];

public class CopyExample


{
public static void main(String[] args)
{
FileInputStream instream = null;
FileOutputStream outstream = null;

try{
File infile =new File("C:\\[Link]");
File outfile =new File("C:\\[Link]");

instream = new FileInputStream(infile);


outstream = new FileOutputStream(outfile);

byte[] buffer = new byte[1024];

int length;
/*copying the contents from input stream to
* output stream using read and write methods
*/
while ((length = [Link](buffer)) > 0){
[Link](buffer, 0, length);
}

//Closing the input/output file streams


[Link]();
[Link]();

[Link]("File copied successfully!!");

}catch(IOException ioe){
[Link]();
}
}
}

CHARACTER STREAM PROGRAM


import [Link].*;
class FileDemo {
public static void main(String args[]) {
try {
FileReader fr=new FileReader("[Link]");
FileWriter fw=new FileWriter("[Link]");
int c=[Link]();
while(c!=-1) {
[Link](c);
}
} catch(IOException e) {
[Link](e);
} finally() {
[Link]();
[Link]();
}
}
}

[Link]
Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes
the object's data as well as information about the object's type and the types of data stored in the object.

After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information
and bytes that represent the object and its data can be used to recreate the object in memory.

Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and
deserialized on an entirely different platform.

Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and
deserializing an object.

The ObjectOutputStream class contains many write methods for writing various data types, but one method in particular
stands out −

public final void writeObject(Object x) throws IOException


The above method serializes an Object and sends it to the output stream. Similarly, the ObjectInputStream class contains the
following method for deserializing an object −

public final Object readObject() throws IOException, ClassNotFoundException


This method retrieves the next Object out of the stream and deserializes it. The return value is Object, so you will need to cast
it to its appropriate data type.

SERIALIZING AN OBJECT
The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program instantiates an Employee
object and serializes it to a file.
When the program is done executing, a file named [Link] is created. The program does not generate any output, but
study the code and try to determine what the program is doing.

Note − When serializing an object to a file, the standard convention in Java is to give the file a .ser extension.

Example
import [Link].*;
public class SerializeDemo {

public static void main(String [] args) {


Employee e = new Employee();
[Link] = "Reyan Ali";
[Link] = "Phokka Kuan, Ambehta Peer";
[Link] = 11122333;
[Link] = 101;

try {
FileOutputStream fileOut =
new FileOutputStream("/tmp/[Link]");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
[Link](e);
[Link]();
[Link]();
[Link]("Serialized data is saved in /tmp/[Link]");
}catch(IOException i) {
[Link]();
}
}
}

Deserializing an Object
The following DeserializeDemo program deserializes the Employee object created in the SerializeDemo program. Study the
program and try to determine its output −

Example
import [Link].*;
public class DeserializeDemo {

public static void main(String [] args) {


Employee e = null;
try {
FileInputStream fileIn = new FileInputStream("/tmp/[Link]");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) [Link]();
[Link]();
[Link]();
}catch(IOException i) {
[Link]();
return;
}catch(ClassNotFoundException c) {
[Link]("Employee class not found");
[Link]();
return;
}

[Link]("Deserialized Employee...");
[Link]("Name: " + [Link]);
[Link]("Address: " + [Link]);
[Link]("SSN: " + [Link]);
[Link]("Number: " + [Link]);
}
}

This will produce the following result −

Output
Deserialized Employee...
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101

[Link] CLASS

Each of Java's eight primitive data types has a class dedicated to it. These are known as wrapper classes because they "wrap"
the primitive data type into an object of that class. The wrapper classes are part of the [Link] package, which is imported by
default into all Java programs.
The wrapper classes in java servers two primary purposes.
 To provide a mechanism to ‘wrap’ primitive values in an object so that primitives can do activities reserved for the
objects like being added to ArrayList, Hashset, HashMap etc. collection.

 To provide an assortment of utility functions for primitives like converting primitive types to and from string objects,
converting to various bases like binary, octal or hexadecimal, or comparing various objects.
All the wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number.

Boxing and Unboxing

The object of the wrapper class contains or wraps its respective primitive data type. Converting primitive data types into
object is called boxing, and this is taken care by the compiler. Therefore, while using a wrapper class you just need to pass the
value of the primitive data type to the constructor of the Wrapper class.

And the Wrapper object will be converted back to a primitive data type, and this process is called unboxing.
The Number class is part of the [Link] package.

Following is an example of boxing and unboxing −

Example
public class Test {

public static void main(String args[]) {


Integer x = 5; // boxes int to an Integer object
x = x + 10; // unboxes the Integer to a int
[Link](x);
}
}

This will produce the following result −

Output
15
When x is assigned an integer value, the compiler boxes the integer because x is integer object. Later, x is unboxed so that
they can be added as an integer.

Primitive Wrapper Class Constructor Argument

boolean Boolean boolean or String

byte Byte byte or String

char Character char


int Integer int or String

float Float float, double or String

double Double double or String

long Long long or String

short Short short or String

Below is wrapper class hierarchy as per Java API

As explain in above table all wrapper classes (except Character) take String as argument constructor. Please note we might get
NumberFormatException if we try to assign invalid argument in the constructor. For example to create Integer object we can
have the following syntax.
Integer intObj = new Integer (25);

Integer intObj2 = new Integer ("25");

Here in we can provide any number as string argument but not the words etc. Below statement will throw run time exception
(NumberFormatException)
Integer intObj3 = new Integer ("Two");

The following discussion focuses on the Integer wrapperclass, but applies in a general sense to all eight wrapper classes.
The most common methods of the Integer wrapper class are summarized in below table. Similar methods for the other wrapper
classes are found in the Java API documentation.

Method Purpose

parseInt(s) returns a signed decimal integer value equivalent to string s

toString(i) returns a new String object representing the integer i

byteValue() returns the value of this Integer as a byte

doubleValue() returns the value of this Integer as a double


floatValue() returns the value of this Integer as a float

intValue() returns the value of this Integer as an int

shortValue() returns the value of this Integer as a short

longValue() returns the value of this Integer as a long

int compareTo(int i) Compares the numerical value of the invoking object with that of i. Returns 0 if
the values are equal. Returns a negative value if the invoking object has a lower
value. Returns a positive value if the invoking object has a greater value.

static int compare(int Compares the values of num1 and num2. Returns 0 if the values are equal.
num1, int num2) Returns a negative value if num1 is less than num2. Returns a positive value if
num1 is greater than num2.

boolean equals(Object Returns true if the invoking Integer object is equivalent to intObj. Otherwise, it
intObj) returns false.

Let’s see java program which explains few wrapper classes methods.
view plaincopy to clipboardprint?

1. package WrapperIntro;
2. public class WrapperDemo {
3. public static void main (String args[]){
4. Integer intObj1 = new Integer (25);
5. Integer intObj2 = new Integer ("25");
6. Integer intObj3= new Integer (35);
7. //compareTo demo
8. [Link]("Comparing using compareTo Obj1 and Obj2: " + [Link](intObj2));
9. [Link]("Comparing using compareTo Obj1 and Obj3: " + [Link](intObj3));
10. //Equals demo
11. [Link]("Comparing using equals Obj1 and Obj2: " + [Link](intObj2));
12. [Link]("Comparing using equals Obj1 and Obj3: " + [Link](intObj3));
13. Float f1 = new Float("2.25f");
14. Float f2 = new Float("20.43f");
15. Float f3 = new Float(2.25f);
16. [Link]("Comparing using compare f1 and f2: " +[Link](f1,f2));
17. [Link]("Comparing using compare f1 and f3: " +[Link](f1,f3));
18. //Addition of Integer with Float
19. Float f = [Link]() + f1;
20. [Link]("Addition of intObj1 and f1: "+ intObj1 +"+" +f1+"=" +f );
21. }
22.
23. }

Output:

valueOf (), toHexString(), toOctalString() and toBinaryString() Methods:


This is another approach to creating wrapper objects. We can convert from binary or octal or hexadecimal before assigning a
value to wrapper object using two argument constructor. Below program explains the method in details.
view plaincopy to clipboardprint?

1. package WrapperIntro;
2. public class ValueOfDemo {
3. public static void main(String[] args) {
4. Integer intWrapper = [Link]("12345");
5. //Converting from binary to decimal
6. Integer intWrapper2 = [Link]("11011", 2);
7. //Converting from hexadecimal to decimal
8. Integer intWrapper3 = [Link]("D", 16);
9. [Link]("Value of intWrapper Object: "+ intWrapper);
10. [Link]("Value of intWrapper2 Object: "+ intWrapper2);
11. [Link]("Value of intWrapper3 Object: "+ intWrapper3);
12. [Link]("Hex value of intWrapper: " + [Link](intWrapper));
13. [Link]("Binary Value of intWrapper2: "+ [Link](intWrapper2));
14. }
15. }
[Link]

the object cloning is a way to create exact copy of an object. For this purpose, clone() method of Object class is used to clone
an object.

The [Link] interface must be implemented by the class whose object clone we want to create. If we don't
implement Cloneable interface, clone() method generates CloneNotSupportedException.

The clone() method is defined in the Object class. Syntax of the clone() method is as follows:

protected Object clone() throws CloneNotSupportedException

Why use clone() method ?

The clone() method saves the extra processing task for creating the exact copy of an object. If we perform it by using the new
keyword, it will take a lot of processing to be performed that is why we use object cloning.

Advantage of Object cloning

Less processing task.

Example of clone() method (Object cloning)

Let's see the simple example of object cloning

class Student18 implements Cloneable{


int rollno;
String name;

Student18(int rollno,String name){


[Link]=rollno;
[Link]=name;
}

public Object clone()throws CloneNotSupportedException{


return [Link]();
. }
.
public static void main(String args[]){
try{
. Student18 s1=new Student18(101,"amit");
.
. Student18 s2=(Student18)[Link]();
.
. [Link]([Link]+" "+[Link]);
. [Link]([Link]+" "+[Link]);
.
. }catch(CloneNotSupportedException c){}
.
. }
. }
Test it Now

Output:101 amit
101 amit

Database connectivity
Unit Structure
15.1 Introduction
15.2 A connection can be open with the help of following steps
15.3 Connecting to an ODBC Data Source
15.4 JDBC Programs

15.1

Introduction :
A Database connection is a facility in computer science that allows client software to
communicate with database server software, whether on the same machine or not. A connection is
required to send commands and receive answers.
Connections are built by supplying an underlying driver or provider with a connection
string, which is a way of addressing a specific database or server and instance as well as user
authentication credentials (for example, Server=sql_box;Database=Common;User
ID=uid;Pwd=password;). Once a connection has been built it can be opened and closed at will,
and properties (such as the command time-out length, or transaction, if one exists) can be set. The
Connection String is composed of a set of key/value pairs as dictated by the data access interface
and data provider being used.

15.2
A connection can be open with the help of following steps
1. Importing Packages
2. Registering the JDBC Drivers
3. Opening a Connection to a Database
4. Creating a Statement Object
5. Executing a Query and Returning a Result Set Object
6. Processing the Result Set
7. Closing the Result Set and Statement Objects
8. Closing the Connection

Step 1. Importing Packages


The following JDBC packages will be imported for creating connection.
[Link].
[Link].
[Link].
[Link].

Step 2. Registering the JDBC Drivers


Following four parameters are required to register JDBC Drivers.
o Database URL
o JDBC Driver name
o User Name
o Password

JDBC Drivers can be register using following methods.


o Class drvClass=[Link](m_driverName);
o [Link]((Driver)[Link]());

Step 3 : Opening a Connection to a Database


Connection to the underlying database can be opened using

Connection m_con=[Link](m_url,m_userName,m_password);

Step 4 : Creating a Statement Object

SQL Statements

Once a connection is established, It is used to pass SQL statements to its underlying


database. JDBC provides three classes for sending SQL Statements to the database, where
PreparedStatement extends from Statement, and CallableStatement extends from
PreparedStatement:
o Statement : For simple SQL statements ( no parameter )
o PreparedStatement : For SQL statements with one or more IN parameters, or simple
SQL statements that are executed frequently.
o CallableStatement : For executing SQL stored procedures.

The statement interface provides three different methods for executing SQL statements :

o executeQuery : For statements that produce a single result set.


o executeUpdate : For executing INSERT, UPDATE, or DELETE statements and
also SQL DDL (Data Definition Language) statements.
o execute : For executing statements that return more than one result set,
more than one update count, or a combination of the two.

A Statement object is used with following steps:

Statement

Statement stmt=m_con.createStatement();
Statement stmt=m_con.createStatement(int resultSetType, int resultSetConcurrency);
PreparedStatement

PreparedStatement pstmt=m_con.prepareStatement(String sql);


PreparedStatement pstmt=m_con.prepareStatement(String sql, int resultSetType, int
resultSetConcurrency),
Note:
The SQL parameter could contain one or more ‗?‘ in it. Before a PreparedStatement
object is executed, the value of each ‗?‘ parameter must be set by calling a setXXX method,
where XXX stands for appropriate type for the parameter. For ex. If the parameter has a java
type of String, the method to use is setString.

CallableStatement

CallableStatemet csmt=m_con.prepareCall(String sql);


CallableStatemet csmt=m_con.prepareCall(String sql, int resultSetType, int
resultSetConcurrency),);

Note :
The sql parameter is in the form of ―{call <stored_procedure_name>[(arg1, arg2,...)]} ― or‖
{ ?=call <stored_procedure_name>[(arg1,arg2...)]}‖. It could contain one or more ‗?‘s in it, which
indiacates IN, OUT or INOUT parameters. The value of each IN parameter is set by calling a
setXXX mehod, while each OUT parameter should be registered by calling a
registerOutParameter method.

Step 5: Executing a Query and Returning a Result Set Object


AND Step 6: Processing the Result set

Execute the Statement

Statement :

ResultSet res=[Link](String sql);


int rowCount=[Link](String sql);
boolean result=[Link](String sql);

PrepaedStatement :

ResultSet res=[Link]();
int rowCount=[Link]();
boolean result=[Link]();

CallableStatement :

ResultSet res=[Link]();
int rowCount=[Link]();
boolean result=[Link]();

Processing the Result set

A result set contains all of the rows which satisfied the conditions in an SQL statement
and it provides access to the data in those rows through getXXX mehods that allow access to the
various columns of the current row.
The [Link]() method is used to move to the next row of the ResultSet, making the
next row become the current row. [Link]() returns true if the new current row is valid,
false if there are no more rows. After all the works have been done, the ResultSet should be
closed with [Link]() method.
Because of limitations imposed by some DBMSs, it is recommended that for maximum
portability, all of the results generated by the execution of a CallableStatement object should be
retrieved before OUT parameters are retrieved using [Link] methods.

Step 7: Closing the Result Set and Statement Objects

Close the statement

After all the works have been done, the result set and statement should be closed with the
following code :

Resultset : [Link]();
Statement : [Link]();
PrepaedStatement : [Link]();
CallableStatement : [Link]();

Step 8: Closing the Connection


After all the works have been done, the Connection should be closed with the following code:

(Connection name)m_con.close();

15.3
Connecting to an ODBC Data Source

A database can be created and managed through Java applications. Java application that
uses a JDBC-ODBC bridge to connect to a database file either a dbase, Excel, FoxPro, Access,
SQL Server, Oracle or any other. Open the ODBC Data source from the control panel. A
database can be created and managed through Java applications.
Follow the following steps to connect to an ODBC Data Source for ―ORACLE‖.

1. Select Control Panel.

2. Select Administrative Tool


3. Select “Data Sources (ODBC)” icon

4. Select the MS-ODBC for oracle or any other driver that felt it required.
5. Once clicking the finish button, the following window appears asking for
Data Source
name, description etc.

6. Provide “Data Source Name”, “Discription”,”Username” and “Server” name. The


username and Server name can be obtained from the Administrator. Click on ok button.

The DSN is now ready and the Java code can be written to access the database‘s tables.
15.4
JDBC Programs

1. Example for creating Table.

// Create Table

import [Link].*; // imports all classes that belongs to the package [Link].*

public class CreateTab


{
public static void main(String args[])
{
try
{
[Link](―[Link]‖);
Connectioncon= [Link]
(jdbc:odbc:nitin‖ ,scott‖,‖tiger‖);
// specifies the type of driver as JdbcOdbcDriver.
Statement stat= [Link]();
String str=‖Create table T1(Rno number(2), Stdname varchar2(20))‖;
[Link](str);
[Link](―Table created successfully‖);
}
Catch(SQLExecution e 1)
{
[Link](―Errors‖ + e 1);
}
Catch(ClassNotFoundException e 2)
{
[Link](―Errors‖ + e 2);
}
}
}
[Link] for inserting records into a Table

// Insert into table

import [Link].*;

public class InsertTab


{
public static void main(String args[])

{
ResultSet result;

try
{
[Link](―[Link]‖);
Connectioncon= [Link]
(jdbc:odbc:nitin‖ ,scott‖,‖tiger‖);

Statement stat= [Link]();

[Link](―Insert into T1 values(20,‘Smith‘)‖);


[Link](―Insert into T1 values(21,‘John‘)‖);
[Link](―Insert into T1 values(22,‘Kate‘)‖);
[Link](―Insert into T1 values(23,‘Stive‘)‖);

[Link](Rows Inserted successfully‖);

result=[Link](―Select * from T1‖);

while([Link]())
{
[Link]([Link](I)+[Link](2));
}
}
catch(Exception e)
{
[Link](―Errors‖+e);
}
}
}
[Link] for viewing rows from a table

// viwing from emp table

import [Link].*;
public class SelectEmp
{
public stativ void main(String args[])
{
String url=‖jdbc:odbc:nitin‖;
Connection con;
String s= ―select ename from emp 1‖;
Statement stmt;
try
{
[Link](―[Link]‖);
}
catch([Link] e)
{
[Link](―ClassNotFoundException:‖);
[Link]([Link]());
}

try
{
con=[Link](url,‖Scott‖,‖Tiger‖);
stmt=[Link]();
resultSet rs=[Link](s);
while([Link]())
{
String s1=[Link](―ename‖);
[Link](―Employee name:‖ +s1);
}
[Link]();
[Link]();
}
catch(SQLException ex)
{
[Link](―SQLException:‖+[Link]());
}
}
}
4. Example using prepared statements

import [Link].*;

public class PreStExample


{
public static void main(String[]
args)
{
Connection con = null;
PreparedStatement prest;
try{
[Link](―[Link]‖);
Connectioncon=
[Link](jdbc:odbc:nitin
‖ ,scott‖,‖tiger‖);
try{
String sql = "SELECT
stdname FROM T1
WHERE Rno = ?"; prest =
[Link](sql);
[Link](1,21);
ResultSet rs1 =
[Link]();
while ([Link]())
{
String stname = [Link](1);

[Link]("student name is: "+stname);


}
[Link](1,23);
ResultSet rs2 = [Link]();

while ([Link]())
{
String stname1 = [Link](1);

[Link]("student name is: "+stname1);


}
}
catch (SQLException s){
[Link]("SQL statement is not executed!");
}
}
catch (Exception e){
[Link]();
}
}
}

You might also like