0% found this document useful (0 votes)
7 views54 pages

Java Unit III Notes

This document covers Unit III of Object-Oriented Programming with Java, focusing on arrays, strings, and interfaces. It explains the creation, initialization, and manipulation of one-dimensional and two-dimensional arrays, as well as string handling using the String and StringBuffer classes. Additionally, it includes sample programs demonstrating various array and string operations in Java.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views54 pages

Java Unit III Notes

This document covers Unit III of Object-Oriented Programming with Java, focusing on arrays, strings, and interfaces. It explains the creation, initialization, and manipulation of one-dimensional and two-dimensional arrays, as well as string handling using the String and StringBuffer classes. Additionally, it includes sample programs demonstrating various array and string operations in Java.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

OBJECT ORIENTED PROGRAMMING WITH

JAVA

UNIT III

ARRAYS AND INTERFACES

Prepared by
[Link]
Assistant Professor
PG & Research Department of Computer Science & Data
Analytics
Tiruppur Kumaran College for Women – Tirupur.
UNIT– III
Arrays, Strings and Vectors – Interfaces: Multiple Inheritance – Packages:
Putting Classes together – Multithreaded Programming.

ARRAYS
INTRODUCTION
An array is a group of contiguous or related data items that share a common name.
example Salary [10], represents the salary of 10 th employee. While the complete set of
values is referred to as an array, the individual values are called elements. Array can be
of any variable type.
One-dimensional Arrays
A list of items can be given one variable name using only one subscript and such a
variable is called a single subscripted or a one dimensional array. In mathematics, we
often deal with variables that are single subscripted. For instance, we use the equation, to
calculate the average of n values of x. In java, single subscripted variable x1 can be
expressed as
x[1],x[2],x[3]............................x[n].
For example, if we want to represent a setof five numbers, say(35, 40, 20, 57, 19), by an
array variable number as follows
Int number[]=new int [5];
And the computer reserves five storage locations as shown below:

number[0]

number[1]

number[2]

number[3]

number[4]

The values to the array elements can be assigned as follows:


number[0] = 35;
number[1]=40;
number[2]=20;
number[3]=57;
number[4]=19;

This would cause the array number to store the values,


number[0] 35

number[1] 40

20
number[2]

number[3] 57

number[4] 19

Creating an Array
Like any other variables, arrays must be declared and created in the computer memory
before they are used. Creation of an array involves three steps:
1. Declaring the array
2. Creating memory locations
3. Putting values into the memory locations.
Declaration of Arrays
Arrays in java may be declared in two forms:
For
typearrayname[];
m1
:
For type[]arrayname;
m2
:
Example:
Int number[ ];
float[] marks;
Creation of
Arrays
After declaring an array we need to create it in the memory. Java allows us to create arrays
using new operator only, as shown below:

EXAMPLE: arrayname=new type[size];


number=newint[5]
;
illustrates creation of an array in memory.

Statement Result

int number[]; number

points nowhere
number=new int[5];

number

number[0] number[1] number[2] number[3]


number[4]

Figure:Creation of array in memory

Initialization of arrays
The final step is to put values into the array created. This process is known as initialization.
This is done using the array subscribes as shown below:

Example: number[2]=20;
number[0]=35; number[3]=57;
number[1]=4 number[4]=19;
0;
arrayname[sub
script]=
value;
Note that java creates arrays starting with subscript of 0 and end with a value one less than
the size specified. We can also initialize arrays automatically like,

type arrayname[subscript] ={ list of values};


ArrayLength
In java, all arrays store the allocated size in a variable named length. We can obtain the
length of the array using a length.
Example:
int aSize = [Link];

Sample program to Reverse an array list by using collections reverse


(ArrayList)method:
import [Link];
import
[Link];
public class Main {
public static void main(String[]args)
{ ArrayList
arrayList=newArrayList();
[Link]("A");
[Link]("B");
[Link]("C");
[Link]("D");
[Link]("E");
[Link]("Before Reverse Order:"+arrayList);
[Link](arrayList);
[Link]("After Reverse Order:"+arrayList);
}
}
Output:
Before Reverse Order:[A,B,C,D,E]
After Reverse Order: [E, D, C, B,
A]

Sample program for sorting a set of numbers using array:


class NumberSorting
{
public static void main(String args[])
{
int number[]={ 55,40,80,65,71};
int n=[Link];//Array length
[Link](―Given list :‖);
for(int i=0;i<n;i++)
{
[Link](――+number[i]);
}
[Link](―/n‖);
//sorting begins
for(inti=0;i<n;i++)
{
for(intj=i+1;j<n;j++)
{
if(number[i]<number[j])
{
int temp=number[i];
number[i]=number[j]
; number[j]=temp;
}
}
}
[Link](―Sortedlist:‖);
for(int i=0;i<n;i++)
{
[Link](――+number[i]);
}
[Link](――);
}}

Output:
Givenlist:5540806571
Sortedlist:8071655540

Sample program to merge two arrays:


import [Link];
import [Link];
import [Link];
public class Main {
public static void main(String args[]){ String
a[ ] = { "A", "E", "I" };
Stringb[]={"O","U"};
Listlist=newArrayList([Link](a));
[Link]([Link](b));
Object[] c = [Link]();
[Link]([Link](c));
}
}

Output:
[A,E,I,O,U]

Two-dimensional Arrays
So far we have discussed the array variables that can store a list of values. There will be
Situations where a table of values will have to be stored. Consider the following data
table, which shows the value of sales for three items by four salesgirls:
i it it
e
m
2
sales 3 2 3
girl 7
#1 5
sales 2 1 3
girl 9
#2 0
sales 4 2 2
girl 3
#3 5
sales 2 3 3
girl 0
#4 0

Two-dimensional arrays are stored in memory as shown in figure. As with the single
dimensional arrays, each dimension of the array is indexed from zero to its maximum
size minus one; the first index selects the row and the second index select the column
within that row.
Example:
int myArray[ ][ ];
myArray=new int[3]
[4];
(or)int myArray[][]=new[3][4];

Figure:Representation of a two-dimensional array in memory

Sample program to display multiplication table:


class MulTable
{
final static int ROWS = 20;
final static int COLUMNS=20;
{
public static void main(string args[])
{
int product[][]=new int[ROWS][COLUMNS]; int
[Link];
[Link](―MULTIPLICATION TABLE‖);
[Link](― ― );
int i,j;
for ( i=10;i<ROWS;i++)
{ for(j=10;j<COLUMNS;j++)
{
product[i][j]=i*j;
[Link](― ― +product[i][j]);
}
[Link](――);}}

Output:

Variable Size Arrays


Java treats multidimensional array as "arrays of arrays". It is possible to declare a two
dimensional array as follows:
int x[][]=new int[3][];
x[0] = new int[2];
x[1]=new int[4];
x[2]=new int[3];

These statements create a two dimensional array as having different lengths for each
row.

STRINGS
String manipulation is the most common part of many Java programs. Strings represent a
sequence of characters. The easiest way to represent a sequence of characters in Java is
by using a character array.
Example:
char charArray[]=new char[4];
charArray[0]=' J ';
charArray[1]=' a ';
charArray[2]=' v ';
charArray[3]=' a ';
Although character arrays have the advantage of being able to query their length, they
themselves are not good enough to support the range of operations we may like to
perform on strings.
In Java, strings are class objects and implemented using two classes, namely, String and
StringBuffer. A Java string is an instantiated object of the String class. Strings may be
declared and created as follows:

String stringName; StringName=newString("string");

Example:
String firstName;
firstName=newString("Anil");
String Arrays
String itemArray[]=new String[3];
Will create an itemArray of size 3 to hold three string constants.
String Methods
The String class defines a number of methods that allow accomplishing a variety of string
manipulation tasks. Some of the most commonly used string methods are:

1. s2=[Link]; [Link]()
2. s2=[Link]; [Link](s2)
3. s2=[Link](‗X‘,‘Y‘); 9. [Link](s2)
4. s2=[Link](); [Link](‗X‘)
5. [Link](s2) [Link](n)
6. [Link]() [Link](n,m)

Command Description
"Testing".equals(text1); Return true if text1 is equal to "Testing". The
check is case-sensitive.
"Testing".equalsIgnoreC Return true if text1 is equal to "Testing". The
ase(text1); check is not case-sensitive. For example, it
would also be true for "testing".
StringBuffer str1 = new Define a new String with a variable length.
StringBuffer();
[Link](1); Return the character at position 1. (Note: strings
are arrays of chars starting with 0)
[Link](1); Removes the first characters.
[Link](1, 5); Gets the substring from the second to the fifth
character.
[Link]("Test") Look for the String "Test" in String str. Returns
the index of the first occurrence of the
specified string.
[Link]("ing") Returns the index of the last occurrence of the
specified String "ing" in the String str.
StringBuffer does not support this method.
Hence first convert the StringBuffer to String
via method toString.
[Link]("ing") Returns true if str ends with String "ing"
[Link]("Test") Returns true if String str starts with String
"Test".
[Link]() Removes leading and trailing spaces.
[Link](str1, str2) Replaces all occurrences of str1 by str2
[Link](str1); Concatenates str1 at the end of str2.
[Link]() / Converts the string to lower- or uppercase
[Link]()
str1 + str2 Concatenate str1 and str2
String[] array = Splits the character separated myString into an
[Link]("-"); array of strings. Attention: the split string is a
String[]array2=myStrin regular expression, so if you using special
[Link]("\\."); characters which have a meaning in regular
expressions, you need to quote them. In the
second example the . is used and must be
quoted by two backslashes.

Sample program for Alphabetical ordering of strings:


class StringOrdering
{
staticStringname[]={―Madras‖,―Delhi‖,―Ahmedabad‖,―Calcutta‖,―Bombay‖); public
static void main(String args[ ] )
{
int size =[Link];
String temp= null ;
for(inti=0;i<size;j++)
{
for(intj=i+1;j<size;j++)
{
if( name[j].compareTo(name[j])<0)
{
temp=name[j];
name[i]=name[j];
name[j]=temp;
}
}
}
for(inti=0;i<size;i++)
{
[Link](name[i]);
}
}
}
Output:
Ahmedabad Bombay
Calcutta Delhi Madras
Sample program using equals method to check whether two arrays are or not:
[Link];
public class Main {
public static void main(String[]args)throws Exception{ int[]
ary = {1,2,3,4,5,6};
int[]ary1= {1,2,3,4,5,6};
int[]ary2= {1,2,3,4};
[Link]("Isarray1equaltoarray2??"+[Link](ary,ary1));
[Link]("Isarray1equaltoarray3??"+[Link](ary,ary2));
}
}

Output:
Is array 1 equal to array 2??
true
Isarray1equaltoarray3??
false

Sample program to find the


Substring:
Public class Java Substring
Example
{
public static void main(String args[])
{
String name="Hello World";
[Link]([Link](6));
[Link]([Link](0,5));
}
}
Output
World
Hello
Sample program to convert a string to uppercase:
public class StringToUpperCaseExample
{
public static void main(String[] args)
{
String str = "string to uppercase example";
String strUpper = [Link]();
[Link]("Original String:"+str);
[Link]("Stringchangedtouppercase:"+strUpper);
}
}
Output:
Original String:string to uppercase example
String changed to uppercase: STRING TO UPPERCASE EXAMPLE

Sample program to compare strings:


public class JavaStringCompareExample
{
public static void main(String args[])
{
Stringstr="HelloWorld";
String anotherString="helloworld";
Object objStr = str;
[Link]( [Link](anotherString) );
[Link]([Link](anotherString));
[Link]( [Link](objStr) );
}
}

Output:
-32
0
0
Sample program to perform string concatenation:
public class JavaStringConcat
{
public static void main(String args[])
{
String str1 = "Hello";
Stringstr2="World";
//1. Using + operator
Stringstr3=str1+str2;
[Link]("String concat using+operator:"+str3);
//[Link]()method
String str4 = [Link](str2);
[Link]("String concat using String concat method:"+str4);
//[Link]
String str5 = new StringBuffer().append(str1).append(str2).toString();
[Link]("StringconcatusingStringBufferappendmethod:"+str5);
}
}

Output:
String concat using +operator:HelloWorld
String concat using String concat method:HelloWorld
String concat using String Buffer append method:HelloWorld

Sample program to perform string


reversing:
public class StringReverseExample
{
public static void main(String args[])
{
//declareorinialstring
String strOriginal = "Hello World"; [Link]("Original
String : " + strOriginal); strOriginal=new
StringBuffer(strOriginal).reverse().toString();
[Link]("Reversed String : " + strOriginal);
}
}
Output:
Original String : Hello World
Reversed String : dlroW
olleH Sample program to
split a string:
public class JavaStringSplitExample
{
public static void main(String args[])
{
/*Stringtosplit.*/
Stringstr="one-two-three"; String[]
temp;
/*delimiter*/
Stringdelimiter="-";

/*given string will be split by the argument delimiter provided.*/


temp = [Link](delimiter);
/*printsubstrings*/
for(inti=0;i<[Link];i++)
[Link](temp[i]);
[Link]("");
str="[Link]";
delimiter = "\\.";
temp=[Link](delimiter);
for(inti=0;i<[Link];i++)
[Link](temp[i]);
[Link]("");
temp = [Link](delimiter,2);
for(inti=0;i<[Link];i++)
[Link](temp[i]);
}
}

Output:
one two
three one
two three
one two
three
Sampleprogramtotrimastring :
publicclassRemoveLeadingTrailingSpace
{
publicstaticvoidmain(String[]args)
{
String str = " String Trim Example "; String strTrimmed = [Link]();
[Link]("Original String is: " + str);
[Link]("RemovedLeadingandtrailingspace");
[Link]("New String is: " + strTrimmed);
}}
Output:
Original String is:String Trim
Example Removed Leading and
trailing space New String is:
String Trim Example

Sample program using starts With:


public class StringStartsWithExample
{
public static void main(String[] args)
{
//declare the original String
String strOrig="HelloWorld";
if([Link]("Hello"))
{
[Link]("String starts with Hello");
}
else
{
[Link]("String doesnot start with Hello");
}
}
}

Output:
String starts with Hello
Sample program to convert a String to Date:
import [Link];
[Link]
; import [Link];
public class JavaStringToDate
{
public static void main(String args[])
{
//Java String having date String
strDate="21/08/2011"; try
{
SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy");
//convertJavaStringtoDateusingparsemethodofSimpleDateFormat

Datedate=[Link](strDate);
//PleasenotethatparsemethodthrowsParseExceptioniftheStringdatecouldnotbe parsed.
[Link]("Date is:"+date);
}
catch(ParseException e){
[Link]("Java String could not be converted toDate:"+e);
}
}
}
Output:
FriJan2100:00:00IST 2011

StringBuffer Class
StringBuffer is a peer class of String. While String creates strings of fixed_length,
StringBuffer creates strings of flexible length that can be modified in terms of both
length and content. Some of the most commonly used StringBuffer methods are:
1. [Link](n,‗x‘)
2. [Link](s2)
3. [Link](n,s2)
4. [Link](n)
Method Task
[Link](n,
Modifies the nth character to x
‗x‘)
[Link](s2) Appends the string s2 to s1 at the end
Inserts the string s2 at the position n of the
[Link](n,s2)
string
s1
Sets the length s1 to n. If(n<[Link]()s1is
[Link](n)
truncated. Ifn>[Link]()zeros are added to
s1.

Example for string manipulation


class Stringmanipulation
{
public static void main()
{
Stringbuffer str=new Stringbuffer(―object language‖);

[Link](―original string :‖ +str);


[Link](―length of string:―+[Link]());
for(int i =0 ; i <[Link]( ); i ++)
{
intp=i+1;
[Link](―character at position:‖+p+‖is―+[Link](i));
}
String aString=new String([Link]());
int pos=[Link](― language‖);
str .insert(process.‖Oriented‖);
[Link](―Modifiedstring:‖,+str);
[Link](6, ‗-‗);
[Link](―String now‖, +str);
[Link](― improves security,‖);
[Link](―Appendedstring:‖+str);
}}
Output:
OriginalString:Objectlangua
ge Length of string : 15
Character at position : 1 is 0
Character at position : 2 is b
Character at position 3 is j
Character at posit. : 4 is e
Character at position : 5 is
c Character at position : 6
is t Character at position :
7 is Character at position :
8 is 1 Character at position
: 9 is a
Characteratposition:10isn
Character at position:11 is
g Character at position:12
is u
Characteratposition:13isa
Characteratposition:14isg
Character at posit. 15 is e
Modified string:Object Oriented
language String now : Object-Oriented
language
Appendedstring:Object-Orientedlanguageimprovessecurity.

Sample program to set length


public class JavaStringBufferSetLengthExample{
public static void main(String[]args)
{
StringBuffer sbf=new StringBuffer("StringBuffersetLengthmethodexample");
[Link](12);
[Link]("StringBuffercontents:"+sbf);
[Link](0);
[Link]("StringBuffercontentsdeleted:"+sbf);
}
}

Output of Java StringBuffersetLengthexample wouldbe


StringBuffer contents: StringBuffer
StringBuffer contents deleted:
Sample program to append a string
public classTest{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Test");
[Link](" String Buffer");
[Link](sb);
}
}
Output
Test String Buffer

Sample for inserting in a string


The insert() method inserts the given string with this string at the given
position. class A{
public static void main(String args[])
{ StringBuffer sb=new StringBuffer("Hello ");
[Link](1,"Java");//noworiginalstringischang
ed [Link](sb);//prints HJavaello
}
}

Sample program to replace a string


The replace() method replaces the given string from the specified begin Index and end
Index. class A{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
[Link](1,3,"Java");
[Link](sb);//prints HJavalo
}
}
Sample program to delete a string
The delete()method of String Buffer class deletes the string from the specified begin Index
to end Index.
ClassA{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello"); [Link](1,3);
[Link](sb);//printsHlo
}}

Sample program of capacity() method of StringBuffer class:


The capacity() method of StringBuffer class returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the number of character increases from its current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current
capacity is 16, it will be (16*2)+2=34.

classA
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
[Link]([Link]());//default16
[Link]("Hello");
[Link]([Link]());//now 16
[Link]("java is my favourite language");
[Link]([Link]());//now(16*2)+2=34i.e(oldcapacity*2)+2
}
}

Sample progam of ensure Capacity()method of StringBuffer class


The ensure Capacity() method of StringBuffer class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.

classA
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
[Link]([Link]());//default16
[Link]("Hello");
[Link]([Link]());//now 16
[Link]("java is my favourite language");
[Link]([Link]());//now(16*2)+2=34i.e(oldcapacity*2)+2
[Link](10);//now no change
[Link]([Link]());//now 34
[Link](50);//now (34*2)+2
[Link]([Link]());//now70
}
}

VECTORS
Vector class is contained in the [Link] package. This class can be used to create a
generic array known as vector that can hold objects of any type and any number. Arrays
can be easily implemented as vectors. Vectors are created like arrays as follows:
Vectorint Vect=new Vector();
Vector list=new Vector (3);

Vectors possess a number of advantages over arrays.


1. It is convenient to use vectors to store objects.
2. A vector can be used to store a list of objects that may vary in size.
3. We can add and delete objects from the list as and when required.

Example:
import [Link].*;
class vector
{
public static void main(String args[])
{
Vector list=new Vector();
int length=[Link];
for(inti=0;i<length;i++)
{
[Link](args[i]);
}
[Link](―COBOL‖,2);
int size = [Link]( );
String listArray[]=new String[size];
[Link](listArray);
[Link](―List of Languages‖);
for(int I =0 ;i< size;i++)
{
[Link](listArray[i]);
}
}
}

Output:
Command line input and output are:
C:\JAVA\prog>javaLanguageVectorAdaBASICC+
+FORTRANJava List of Languages
Ada
BASIC
COBOL
C++
FORTRAN
Java

Wrapper Classes
Primitive data types like int,float,long,char and double may be converted into object types
by using the wrapper classes contained in the [Link] package.
Wrapper classes for converting Simple Types are:

Converting Numbers to String using to String() Method are:


Example for conversion function:

Converting Numbers to String:

Example for converting string to primitive integer:


Auto boxing and Unboxing
The autoboxing and unboxing feature, introduced in J2SE 5.0, facilitates the process of
handling primitive data types in collections. This feature is used to convert primitive data
types to wrapper class types automatically. For example:
Doubled_object=98.42;
doubled_primitive=d_object.doubleValue();
Usingtheautoboxingandunboxingfeature,canberewriteas
: Double d_object=98.42;
doubled_primitive=d_object:
Enumerated Types
J2SE5.0 allows using the enumerated type in java using the enum keyword. This keyword
can be used similarto the static final constants in the earlier version of java. The
statement with enum keyword is written as follows:
Public enum Day {SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY, FRIDAY,SATURDAY}
The advantages of using the enumerated type are:
1. Compile-time type safety.
2. Enum keyword can be used with switch statements.

Sample Program:
public class Workingdays
{
enum Days
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
public static void main(String args([])
for (Days d : [Link]( ))
{
weekend(d);
}
}
private static void weekend(Daysd)
{
if([Link]([Link])
[Link](―value=+d+'is a Holiday‖);
else
[Link]("value'+(14,is a workingday.);
}
}

Output:
value=Sunday is a Holiday
value = Monday is a Working
Day value = Tuesday is a
Working Day
value=Wednesday is a
WorkingDay value =
Thursday is a Working Day
value = Friday is a Working
Day value = Saturday is a
Working Day

Annotations
The annotations feature, introduced by J2SE 5.0,is also known as metadata. This feature is
used to merge additional Java elements with the programming elements, such as classes,
methods, parameters, local variables, packages and fields.
Metadata is stored in java class files by the compiler and these class files are used by the
JVM or by the program to find the metadata for interacting with the programming
elements. Java contains the following standard annotations:
1. @Deprecated
2. @Overrides
The following are the meta-annotations:
1. @Documented
2. @Inherited
3. @Retention
4. @Target
The following are the code that contains the declaration of an
annotation: Package [Link]:
Import [Link].*;
@Retention([Link])
@Target(([Link]))
Public @interface UnitTest
{
Stringvalue();
}
INTERFACES:MULTIPLEINHERITANCES
Introduction
Java provides an alternate approach known as interfaces to support the concept of multiple
inheritances.
Defining Interfaces
An interface is basically a kind of class. Like classes, interfaces contain methods and
variables but with a major difference. The difference is that interfaces define only
abstract methods and final fields. They syntax for defining an interface is very similar to
that for defining a class. The general form of an interface definition is:
interface InterfaceName
{
Variables declaration; methods
declaration;
}
Here, interface is the keyword and Interface Name is any valid Java variable. Variables
are declared as follows:
static final typeVariableName=Value;
Note that all variables are declared as constants. Methods declaration will contain only a
list of methods without any body statements.
return-type methodName1(parameter_list);

Anexampleforinterfacedefinitionthatcontainstwovariablesandonemethod:
interface Item
{
static final int code =1001; static
final String name=‖fan‖; void
display( );
}
The code for the method is not included in the interface and the method declaration ends
with semicolon. The class that implements this interface must define the code for the
method. example is,
interface Area
{
final static floar pi=3.142f; float
compute(floatx,floaty); void
show( );
}
Extending Interfaces
Like classes, interfaces can also be extended. That is, an interface can be sub interfaced
from other interfaces. The new sub interface will inherit all the members of the super
interface in the manner similar to subclasses. This is achieved using the keyword extends
as shown below:
interfacename2extendsname1
{
bod y of name2
}
This will enable us to use the constants in classes where the methods are not required.
Example:
interface ItemConstants
{
int code=1001; string
name="Fan";
}
interface Item extends ItemConstants
{
void display();
}
The interface item would inherit both the constants code and name into it. Note that the
variables name and code are declared like simple variables. It is allowed because all the
variables in an interface are treated as constants although the keywords final and static
are not present. We can also combine several interfaces together into a single interface.
Following declarations are valid:
interface ItemConstants
{
int code=1001;
String
name="Fan";
}
interface ItemMethods
{
void display();
}
interface Item extends ItemConstants, ItemMethods
{
..................
..................
}

Implementing Interfaces
Interfaces are used as"superclasses"whose properties are inherited by [Link] is therefore
necessary to create a class that inherits the given interface. This is done as follows:
class classname implements interfacename
{
bodyof classname
}

A more general form of implementation may look like this:


class classname extends superclass implements interface1,interface2,.............
{
bodyof Classname
}
When a class implements more than one interface,they are separated by a comma.
Example:
interface Area
{
final static float pi=3.14F; float
compute(floatx,floaty);
}
class Rectangle implements Area
{
.................
..............
}
class Circle Area
{
.................
...............
}
class Test
{
public static void main(String args[])
{
Rectangle rect=new Rectangle();
Circle cir=new Circle();
Area area;
.................
.................
}}

Sample program using interface:


public class Main
{
public static void main(String[] args)
{
shape circleshape=new circle();

[Link]();
}
}
interface shape
{
public String
baseclass="shape"; public void
Draw();
}
class circle implements shape
{
public void Draw()
{
[Link]("Drawing Circle here");
}
}

Output:
Drawing Circle here

Accessing Interface Variables


Interfaces can be used to declare a set of constants that can be used in different classes.
This is similar to creating header files in C++ to contain a large number of constants.
The value can be used in any method, as part of any variable declaration or anywhere
where we can use a final value.
Example:
interface A
{
int m=10;
int n=50;
}
class B implements A
{
int x=m;
void method(int size)
{
...........
...........
if (size<n)
............
}}
PACKAGES:PUTTING CLASSES TOGETHER
Introduction
A package is a concept similar to class libraries in other languages. Packages are Java‘s
way of grouping a variety of classes and/or interfaces together. The grouping is usually
done according to functionality. Packages act as container for classes.
Java API Packages
Java API provides large number of classes grouped into different packages according to
functionality. Java API consists of six packages. They are:

Java

lang util io awt appl


net
et
Using System Packages
The packages are organized in a hierarchical structure as shown below.

Java

Package containing awt


package
Color
Package containing classes
Graphics

Font

Image Classes containing methods

The package name can give in import statement with class name such as:
import [Link];
Or
importpackagename.*;
Example:[Link]
Or
[Link].*;
Naming Conventions
Packages can be named using the standard Java naming rules. By convention, packages
begin with lowercase letters. This makes it easy for users to distinguish package names
from classnames when looking at an explicit reference to a class. All classnames, again by
convention, begin with an uppercase letter.
Example:
• double y = [Link](x);

package class method
This statement uses a fully qualified classname Math to invoke the method sqrt().
Methods begin with lowercase.
Creating Packages
First declare the name of the package using the package keyword followed by a package
name. Then define a class such as:
package firstPackage; //package declaration
publicclass FirstClass //class definition
{
…………..
…………..
}
The following are the steps to create our own packages are:
1. Declare the package at the beginning of a file using the form

package packagename;
2. Define the class that is to be put in the package and declare it public.
3. Create a sub directory under the directory where the main source files are stored.
4. Store the listing as the classname . java file in the sub directory created.
5. Compile the file .This creates .class file in the sub directory.

Accessing a Package Java system package can be accessed either using a fully qualified
class name or using a shortcut approach through the import statement. The same
approaches can be used to access the user-defined packages as well. The general form of
import statement for searching a class is as follows:
import package1[.package2][package3].classname;
The following is an example of importing a particular class:
import [Link];
This can also
written as:
import packagename.*;
Here, package name may denote a single package or a hierarchy of packages. The star(*)
indicates that the compiler should search this entire package hierarchy when it
encounters a class name.
Using a Package
Example:
package package1;
public class ClassA
{
public void displayA()
{
[Link](―ClassA‖);
}}
This source file should be named Class [Link] and stored in the subdirectory package1.
Adding a Class to a Package
The simple way to add a class to an existing package is
package p1; public ClassA
{
//bodyofA
}
To add another class B to this package, the following steps to be followed:
1. Define the class and make it public.
2. Place the package
statement package p1;
Before theclass definition as follows:
package p1;
public classB
{
//bodyofB
}
3. Store this as [Link] file under the directory p1.
4. Compile [Link] [Link] will create a [Link] file and place it in the directory p1.

Sample program to display Hello using package:


//[Link]
package pack;
public class A
{
public void msg()
{
[Link]("Hello");
}
}
//save by [Link]
package
mypack; import
pack.*; class B
{
public static void main(String args[])
{
A obj=new A();
[Link]();
}
}
Output:
Hello

Hiding Classes
Some of the classes can be hide from accessing from out side of the package. Such classes
should be declared ―not public‖. For EXAMPLE:
packagep1;
public classX //public class,available outside
{
//body of X
}
Class Y //notpublic,hidden
{
//bodyofY
}

Static Import
Static import is another language feature introduced with the J2SE 5.0 release. This
feature eliminates the need of qualifying a static member with the class name. The static
import declaration is similar to that of import. The Syntax is:
import static [Link]-name;(or)
import static [Link]-name.*;
The interface can be imported using the static import statementas follows:
import static employee.employee_details.Salary_increment;
Here, employee is package name, employee_details is subpackage and Salary_increment
is static member name.
Example:

import staticj [Link].*;


public class mathop
{
public void circle(double r)
{
double area=PI*r*r;
[Link](―The area of circle is :―+area);
}
public static void main(Strings args[])
{
mathop obj=new mathop();
[Link](2,3);
}

MULTITHREADED PROGRAMMING
Introduction
The ability to execute several programs simultaneously is called multitasking. In system‘s
terminology, it is called multithreading. Multithreading is a conceptual programming
paradigm where a program (process) is divided into two or more subprograms
(processes), which can be implemented at the same time in parallel. A thread is similar
to a program that has a single flow of control. Java enables us to use multiple flows of
control in developing programs.

Creating Threads
Creating threads in Java is simple. Threads are implemented in the form of objects that
contain a method called run(). The run() method is the heart and soul of any thread. It
makes up the entire body of a thread and is the only method in which the threads
behavior can be implemented. A typical run() would appear as follows:
public void run()
{
..................
..................
}
A new thread can be created in two ways:
1. By creating a thread class: Define a class that extends Thread class and override its
run() method with the code required by the thread.
2. By converting a class to a thread: Define a class that implements Runnable
interface. The runnable interface has only one method, run() that is to be defined in the
method with the code to be executed by the thread.
Extending theThread Class
We can make our class runnable as thread by extending the class [Link]. This
gives us access to all the thread methods directly. It includes the following steps:
1. Declare the class as extending theThread class.
2. Implement the run() method that is responsible for executing sequence of code that
the thread will execute.
3. Createathreadobjectandcallthestart()methodtoinitiatethethreadexecution.
a) Declaring the Class
The Thread class can be extended as follows:
class MyThread extends Thread
{
...................
...................
}

b) Implementing the run() Method


The run() method has been inherited by the class MyThread. We have to override this
method in order to implement the code to be executed by our thread. The basic
implementation of run() will look like this:
public void run()
{
...............
...............
}
c) Starting New Thread
To actually create and run an instance of our thread class,we must write the following:
MyThread aThread=new MyThread();
[Link]();
d) An example of Using theThread Class
The below program creates three threads A,B and C for undertaking three different tasks.
The main method in the Thread Test class also constitutes another thread which we may
call the "main thread".
Note the statement like
new A().start;
In the main [Link] is just a compact way of starting a thread. This is
equivalent to: A threadA=new A();
[Link]();
Example:
class A extends
Thread{ public void run()
{
................
................
}}
class B extends Thread
{
public void run()
{
.....................
....................
}}
class C extends Thread
{
public void run()
{
................
...............
}}
class Thread Test
{
public static void main(String args[])
{
new A().start();
new B().start();
new C().start();
}
}
Example:
To findout what kind of scheduler you have on your system, try out the following code:
public class RunnablePotato implements Runnable
{
public void run()
{
while (true)
[Link]([Link]().getN
ame());
}}
public class PotatoThreadTester
{
public static void main(String argv[])
{
RunnablePotato aRP= new
RunnablePotato(); new Thread(aRP, "one
potato").start();
newThread(aRP,"twopotato").start();
}
}
If your system employs an on preemptive scheduler, this code results in the following
output: one potato
one potato
one potato
...
This output will go on forever or until you interrupt the program.

Stopping and Blocking Thread


Stopping a Thread
Whenever we want to stop a thread from running further, we may do so by calling its stop(
) method, like:
[Link]();
This statement causes the thread to move to the dead state. A thread will also move to the
dead state automatically when it reaches the end of its method. The stop() method may
be used when the premature death of a thread is desired.
Blocking a Thread
A thread can also be temporarily suspended or blocked from entering into the runnable
and subsequently running state by using either of the following thread methods:
sleep( ) //blocked for a specified
time suspend( ) //blocked until further
orders
wait() //blocked until certain condition occurs
Life Cycle of aThread
During the life time of athread, there are many states it can [Link] include:
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
6.
1. Newborn state
When we create a thread object, the thread is born and is said to be in newborn state. At
this state we can do only one of the following things with it:
 Schedule it for running using start()method.
 Kill it using stop() method.
Newborn

Start Stop

Runnable Dead

2. Runnable state
The runnable state means that the thread is ready for execution and is waiting for the
availability of the processor. That is, the thread has joined the queue of threads that are
waiting for execution.
The thread that relinquishes control joins the queue at the end and again waits for its turn.
This process of assigning time to thread is known as time-slicing.

yield

Running
thread

Runnable threads

3. Running state
Running means that the processor has given its time to the thread for its execution.
a) It has been suspended using suspend() method. A suspended thread can be revived
by using the resume() method.
b) It has been made to sleep. We can put a thread to sleep for a specified time period
using the method sleep where time is in milliseconds.
c) It has been told to wait until some event occurs. This is done using the wait()
method. The thread can be scheduled to run again using the notify() method.
Suspend,sleep(),wait

Running Suspended

Resume,alert,notify

4. Blocked state
A thread is said to be blocked when it is prevented from entering into the runnable state
and subsequently the running state. This happens when the thread is suspended, sleeping
or waiting in order to satisfy certain requirements.
5. Dead state
Every thread has a life cycle. A running thread ends its life when it has completed
executing its run() method. It is a natural death.
Using Thread Methods
We have discussed how Thread class methods can be used to control the behavior of a
thread. We have used the methods start() and run(). Then the use of yield(), sleep() and
stop() methods.

Example:
class A extends Thread
{
public void run()
{
................
...............
}}
class B extends Thread
{
public void run()
{
................
...............
}}
class C extends Thread
{
public void run()
{
................
...............}}
class ThreadTest
{
public static void main(String args[])
{
A threadA=new A();
B threadB=new B();
C threadC=new C();
.....................
.....................
}}
Example for Yield() thread:
public class RunnablePotato implements Runnable
{
public void run()
{
while(true)
{
[Link]([Link]().getName());
[Link]();// let another thread run for a while
}
}
}
Normally , we would have to use [Link]().yield() to get your hands on the
current thread, and then call yield().Because this pattern is so common, however, the
Thread class can be used as a shortcut.
The yield()method explicitly gives any other threads that want to run a chance to begin
running. (If there are no threads waiting to run, the thread that made the yield() simply
continues.) In our example, there's another thread that's just dying to run, so when you
now execute the class Thread Tester, it should output the following:
onepotato
twopotato
onepotato
twopotato
onepotato
twopotato
...

This output will be the same regardless of the type of scheduler you have.

Thread Exceptions
The call to sleep() method is enclosed in a try block and followed by a catch block. This is
necessary because the sleep() method throws an exception, which should be caught. Java
run system will throw Illegal Thread State Exception whenever we attempt to invoke a
method that a thread cannot handle in the given state. The same is true with the
suspend() method when its used on a blocked thread. The catch statement may take one
of the following forms:
catch(ThreadDeath e)
{
.................
................
}
catch(InterruptedException e)
{
................
................
}
catch(IllegalArgumentException e)
{
..................
..................
}
catch(Exception e)
{
....................
....................
}

Thread Priority
In Java each thread is assigned a priority, which affects the order in which it is scheduled
for running. The threads that we have discussed so far are of the same priority.
Java permits us to set the priority of a thread using the setPriority() method as follows:
[Link](intNumber);
For athread of lower priority to gain control,one of the following things should happen:
1. It stops running at the end of run().
2. It is made to sleep using sleep().
3. It is told to wait using wait().

Example:
class A extends Thread
{
public void run()
{
................
...............
}}
class B extends Thread
{
public void run()
{
................
...............
}}
class C extends Thread
{
public void run()
{
................
...............
}}
class ThreadTest
{
public static void main(String args[])
{
A threadA=new A();
B threadB=newB();
C threadC=newC();
.....................
.....................
}}

Sample program:
public class Main
{
public static void main(String[] args)throws Exception
{
Thread thread1=new Thread(newTestThread(1));
Threadt hread2=new
Thread(newTestThread(2));
[Link](Thread.MAX_PRIORITY);
[Link](Thread.MIN_PRIORITY);
[Link]();
[Link]
();
[Link]
n();
[Link]
n();
[Link]("The priority has been set.");
}
}

Output:
The priority has been set.

Sample program:
//Create a second thread by extending
Thread class NewThread extends Thread
{
NewThread()
{
// Create a new, second thread
super("Demo Thread");
[Link]("Childthread:"+this
); start( ); // Start the thread
}
//This is the entry point for the second
thread. public void run()
{

try
{
for(inti=5;i >0; i--)
{
[Link]("ChildThread:"+i);
[Link](500);
}
}
catch(InterruptedException e)
{
[Link]("Child interrupted.");
}
[Link]("Exiting childthread.");
}
}
class ExtendThread
{
public static void main(String args[])
{
new NewThread();//create a new thread try
{
for(inti=5;i >0;i—)
{
[Link]("Main Thread:"+i);
[Link](1000);
}
}catch(InterruptedException e)
{
[Link]("Main thread interrupted.");
}
[Link]("Main thread exiting.");
}
}
Output:
Childthread:Thread[DemoThread,5,main]
Main Thread: 5
ChildThread:5
ChildThread:4
MainThread:4
ChildThread:3
ChildThread:2
MainThread:3
Child Thread: 1
Exitingchildthread.
Main Thread: 2
Main Thread: 1
Mainthreadexiting.

Sample Program to read Number from Consolea nd Check if it is a Palindrome


number:
import [Link];
import [Link];
[Link]
;
public class InputPalindromeNumberExample
{
public static void main(String[]args)
{
[Link]("Enter the number to check..");
int number = 0;
try
{
//take input from console
BufferedReader br=newBufferedReader(newInputStreamReader([Link]));
//parsethelineinto int
number=[Link]([Link]());
}
catch(NumberFormatException ne)
{
[Link]("Invalidinput:"+ne);
[Link](0);
}
catch(IOException ioe)
{
[Link]("I/OError:"+ioe);
[Link](0);
}
[Link]("Number is"+number);
int n = number;
int reversedNumber=0;
int temp=0;
//reverse the number
while(n > 0){
temp=n%10; n
= n / 10;
reversed Number=reversedNumber*10+temp;
}
if(number == reversedNumber)
[Link](number+"is a palindrome number");
else
[Link](number+"is not a palindrome number");
}
}

Output:
Enter the number to check..
121
Numberis121
121isapalindromenumber

Synchronization
So far we have seen threads that use their own data and methods provided inside their
run() methods. Depending on the situation, we may get strange results. Java enables us to
overcome this problem using a technique known as Synchronization. In case of Java, the
keyword synchronized helps to solve such problems by keeping a watch on such
locations.
Example:
synchronized void update()
{
.......................
. //code here is synchronized
}
It is also possible to mark a block of code as synchronized as shown below:
synchronized (lock-object)
{
.......................
....................... }
Whenever a thread has completed its work of using synchronized method(or block of
code),it will hand over the monitor to the next thread that is ready to use the same
resource. Deadlock is the condition on which the waiting threads rely on to gain control
does not happen. For example, assume that the thread A must access Method1 before it
can release Method2,but the thread B cannot release Method1 until it gets hold of
[Link] these are mutually exclusive conditions, a deadlock occurs. The code
below illustrates this:
ThreadA
synchronizedmethod2()
{
synchronizedmethod1()
{
.......................
.......................
}}
ThreadB
synchronizedmethod1()
{
synchronizedmethod2()
{
.......................
.......................}}
Implementing the 'Runnable' Interface
The Runnable interface declares the run()method that is required for implementing threads
in our programs. To do this, we must perform the steps listed below:
1. Declare the class as implementing the Runnable interface.
2. Implement the run()method.
3. Create a thread by defining an object that is instantiated from this"runnable"class as
the target of the thread.
4. Call the thread's start() method to run the thread.
If the direct reference to the thread threadX is not required, then we may use a shortcut as
shown below:
new Thread (new X()).start();
class X implements
Runnable{ public void run() {
................
. }}
class RunnableTest{
public static void main(String args[])
{
X runnable=new X();
Thread threadX=new Thread(runnable);
[Link]();
. }}
Sample program using threads:
class thrun implements
Runnable{ Thread t;
boolean runn = true;
thrun(Stringst,intp){
t=newThread(this,st);
[Link](p);
[Link]();}
public void run(){
[Link]("Thread name : " + [Link]());
[Link]("ThreadPriority:"+[Link]());}}
class priority{
public static void main(String args[]){
[Link]().setPriority(Thread.MAX_PRIORITY);
thrunt1=newthrun("Thread1",Thread.NORM_PRIORITY+2);
thrun t2 = new thrun("Thread2",Thread.NORM_PRIORITY - 2);
[Link]("Main Thread : " + [Link]());
[Link]("Main Thread Priority:"+[Link]().getPriority());}}
Output:
Thread name: Thread1
Main Thread:Thread[main,10,main]
Thread name : Thread2
Thread Priority:7
Main Thread
Priority:10 Thread
Priority :

You might also like