Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
16 views14 pages

Java - UNIT III

This document covers key concepts in Java programming, focusing on arrays, strings, interfaces, and packages. It explains the declaration, creation, and initialization of one-dimensional and two-dimensional arrays, as well as string manipulation using String and StringBuffer classes. Additionally, it discusses the definition and implementation of interfaces, along with the organization of classes into packages for better namespace management.
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)
16 views14 pages

Java - UNIT III

This document covers key concepts in Java programming, focusing on arrays, strings, interfaces, and packages. It explains the declaration, creation, and initialization of one-dimensional and two-dimensional arrays, as well as string manipulation using String and StringBuffer classes. Additionally, it discusses the definition and implementation of interfaces, along with the organization of classes into packages for better namespace management.
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
You are on page 1/ 14

III B.

Sc CS Java Programming Siri PSG Arts & Science College for


Women

UNIT - III

3.1 ARRAYS, STRINGS AND VECTORS


3.1.1 INTRODUCTION
- An array is a group of contiguous or related data items that share a common name.
- A particular value is indicated by writing a number called index number or subscript in brackets after
the array name.
For ex, salary[10] represents the salary of the 10th 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.

3.1.2 ONE DIMENSIONAL ARRAY


- A list of items can be given one variable name using only one subscript and such a variable is called
a single-subscripted variable or a one-dimensional array.
- The subscript can begin with number 0. That is x[0] is allowed.
- For example, if we want to represent a set of five numbers, say(35,40,20,57,19) by array variable
number, then we may create the 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 shown as follows:

1
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women

Number[0] 353
35
Number[1] 40

Number[2] 20
Number[3]
57
Number[4] 19

3.1.3 CREATING AN ARRAY


- Arrays must be declared and created in the computer memory before they are used.
- Creation of an array involves three steps:
1. Declare the array
2. Create memory locations
3. Put values into the memory locations.
1. Declaration of Arrays
- Arrays in Java may be declared in two forms:
Form1
Type arrayname[];

Form2
Type[] arrayname;

Examples:
int number[];
float average[];
int[] counter;

2. Creation of Arrays
- After declaring an array, we need to create it in the memory.
- Java allows creating arrays using new operator only, as shown below.

Arrayname = new type[size];

Examples:
Number = new int[5];
Average = new float [10];

2
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
3. 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 subscripts as shown below.

Arrayname [subscript] = value;

- We can also initialize arrays automatically in the same way as the ordinary variables when they are
declared, as shown below.

Type arrayname[] = (list of values);

- The array initializer is a list of values separated by commas and surrounded by curly braces.

 Array length
- In java, all arrays store the allocated size in a variable named length.
- We can access the length of the array a using a.length.
- Example: int a Size = a.length;
Example:
Class NumberSorting
{
Public static void main(String args[])
{
int num[] = {55, 40, 80, 65, 71};
int n = num.length;
System.out.println(“Given list:”);
For(int I = 0; I < n; i++)
{
system.out.println(“ “ + num[i]);
}
system.out.println(“\n”);
for(int I = 0; I < n; i++)
{
for (int j = I + 1; j < n; j++){
if(num[i] < num[j])
{
int temp = num[i];

3
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
num[i] = num[j];
num[j] = temp;
}
}
}
system.out.println(“Sorted list :”);
For(int I = 0; I < n; i++){
system.out.println(“ “ + num[i]);
}
system.out.println(“ ”);
}
}
Output:
Given list : 55 40 80 65 71
Sorted list : 80 71 65 55 40

3.1.4 TWO DIMENSIONAL ARRAYS


- In mathematics, we represent a particular value in a matrix by using two subscripts such as v ij . Here
v denotes the entire matrix and vij refers to the value in the ith row and jth coloumn.
Ex: v[4][3];
- For creating two-dimensional arrays, we must follow the same steps as that of simple arrays.
- We may create a two-dimensional array like this:
int myArray[][];
myArray = new int[3][4];
- This creates a table that can store 12 integer values, four across and three down.

 Variable Size Arrays


- Java treats multidimensional arrays 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];

4
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women

- These statements create a two-dimensional array as having different lengths for each row as shown
below:
X[0][1]
X[0]
X[1] x[1][3]
X[2]
X[2][2]

3.1.5 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’;
 Strings are class objects and implemented using two classes, namely String and StringBuffer.
 A java string is an instantiated object of the String class.
 String stringName;
 StringName = new String(“ string”);
Example:
String firstName;
firstName = new String(“Anil”);
 These two statements may be combined as follows:
String firstName = new String(“Anil”);
 Like arrays it is possible to get the length of string using the length method of the string class.
int m = firstName.length( );
String Buffer:
 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.
 We can insert characters and substrings in the middle of a string, or append another string to the end.

5
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
StringBuffer Methods:
 S1. setChartAt(n, ‘x’) - Modifies the nth character to x
 S1.append(s2) - Appends the string s2 to s1 at the end
 S1.insert(n, s2) - Inserts the string s2 at the position n of the string s1
 S1.setLength(n) - Sets the length of the string s1 to n. if n<s1.length() s1 is
truncated. If n>s1.length() zeros are added to s1
Example program of String
Alphabetical ordering of string
Class StringOrdering
{
static String names = {"Joe", "Slim", "Red", "George"};
public static void main(String[ ] args)
{
int size = name.length;
String temp = null;
for (int i = 0; i < size; i++)
{
for (int j = i+1; j < size; j++)
{
if ( name [ j ].compareTo(name [ i ] < 0)
{
temp = name[ i ];
name [ i ] = name [ j ]; // swapping
name [ j ] = temp;
}
} Output:
}
for (int i = 0; i < size; i++) George
{ Joe
System.out.println(name [ i ]; Slim
} Red
}
}

3.2 INTERFACES
3.2.1 INTRODUCTION:
 Interface A collection of methods and variables that other classes may implement. A class that
implements an interface provides implementations for all the methods in the interface.
 Java cannot have more than one superclass. It can implement more than one interface.

6
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
3.2.2 DEFINING AN INTERFACE
 An interface is basically a kind of class. The interface defines only abstract methods and final fields.
 This means that interfaces do not specify any code to implement these methods and data fields
contain only constants.
 General form:

interface InterfaceName
{
Variable declaration;
Methods declaration;
}

 Here, interface is the key word and InterfaceName is any valid Java variable.
 Variables are declared as follows:
Static final type varname = value;
 All variables are declared as constants. Method declaration will contain a list of methods without
the body statements.
Return-type method name (parameter-list)
Example:
interface Item
{
static final int code = 700;
static final String name = ”java”;
void display();
float compute(float x, float y); // The method declaration simply ends with a semicolon.
}

3.2.3 EXTENDING INTERFACES


 An interface can be subinterfaced from other interfaces. The new subinterface will inherit all the
members of the super interface in the manner similar to subclasses.
 This is achieved using the keyword extends as follows below:
Syntax: Example:
interface strdisplay
{
int no=700;
interface name2 extends String name=”java”;
name1 }
{ interface str extends strdisplay
body of name 2; {
void display( );
}

7
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
 Interface Item inherits both the constant code and name into it. It is treated as final and static.
 Several interfaces are combined into a single interface
Example:
interface A {
void meth1();
void meth2();
}
interface B extends A // B now includes meth1() and meth2() -- it adds meth3().
{
void meth3();
}
class MyClass implements B // This class must implement all of A and B
{
public void meth1()
{
System.out.println("Implement meth1().");
}
public void meth2()
{
System.out.println("Implement meth2().");
}
public void meth3()
{
System.out.println("Implement meth3().");
}
}
class IntExtend {
public static void main(String arg[])
{
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}}

8
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
 Trying to remove the implementation for meth1( ) in MyClass will cause a compile-time error.
 Any class that implements an interface must implement all methods defined by that interface,
including any that are inherited from other interfaces.

3.2.4 IMPLEMENTING INTERFACES


 Interfaces are used as “super classes” whose properties are inherited by classes. It is therefore
necessary to create a class that inherits the given interface.
Syntax: 1
class classname implements Interfacename
{
Body of class name
}
Here, the class classname ‘implements’ the interface interfacename.

Syntax: 2
class classname extends superclass implements interface1, interface2
{
Body of class name
}
When a class implements more than one interface, they are separated by a comma.

Example: Implementing interfaces


interface area // interface defined
{
final static float pi = 3.14f;
final compute(float x, float y);
}
class rectangle implements area // interface implemented
{
public float compute(float x, float y)
{
return (x*y);
}
}
3.3 PACKAGES

9
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
3.3.1 INTRODUCTION:
 Packages are containers for classes that are used to keep the class name space compartmentalized.
Packages are stored in a hierarchical manner and are explicitly imported into new class definitions.
 Packages and interfaces are two of the basic components of a Java program. In general, a Java source
file can contain any (or all) of the following four internal parts:
 A single package statement (optional)
 Any number of import statements (optional)
 A single public class declaration (required)
 Any number of classes private to the package (optional)
 Java provides a mechanism for partitioning the class name space into more manageable chunks. This
mechanism is the package.
 The package is both a naming and a visibility control mechanism.
 We can define classes inside a package that are not accessible by code outside that package.
 We can also define class members that are only exposed to other members of the same package.
 Benefits:
 The classes contained in the packages of other programs can be easily reused.
 Classes can be unique compared with classes in other packages. Two classes in two different
packages can have the same name.
 Packages provide a way to “hide” classes thus preventing other programs or packages from accessing
classes that are meant for internal use only.
 Packages also provide a way for separating “design” from “coding”.
 Java packages are classified into two types
1) Java API packages
2) User defined package

3.3.2 JAVA API PACKAGES:


 Java API provides a large number of classes grouped into different packages according to
functionality.
Java

lang util io awt net applet

10
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
Package name Contents
These classes that java compiler itself uses and automatically imported. It
java.lang includes classes for primitive types, string, math functions, threads and
exceptions.
Language utility classes such as vectors, hash tables, random numbers, date.
java.util
etc.
Input/ output support classes. They provide facilities for the input and output
java.io
of data.
Set of classes for implementing graphical user interface. They include classes
java.awt
for windows, buttons, lists, menus and so on.
Classes for networking. They include classes for communicating with local
java.net
computers as well as with internet servers.
Java.applet Classes for creating and implementing applets.

3.3.3 CREATING A PACKAGE


 To create a package is quite easy: simply include a package command as the first statement in a
Java source file.
 Any classes declared within that file will belong to the specified package.
 The package statement defines a name space in which classes are stored.
 If you omit the package statement, the class names are put into the default package, which has no
name.
 While the default package is fine for short, sample programs, it is inadequate for real applications.
Most of the time, you will define a package for your code.

Syntax: package pkg; where pkg  name of the package.


Ex: package MyPackage;
 More than one file can include the same package statement.
 The package statement simply specifies to which package the classes defined in a file belong.
 It does not exclude other classes in other files from being part of that same package.
 Java uses file system directories to store packages.
 To create a hierarchy of packages, simply separate each package name from the one above it by
use of a period.
 The general form of a multileveled package statement is shown here:
Syntax: package pkg1[.pkg2[.pkg3]]; Ex: package java.awt.image;
Finding Packages and CLASSPATH

11
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
1. By default, the Java run-time system uses the current working directory.
2. We can specify a directory path or paths by setting the CLASSPATH environmental variable.
If we are working on source code in a directory called c:\myjava, then set the CLASSPATH to
.;c:\myjava;c:\java\classes
A Short Package Example
package MyPack;
class Balance {
String name;
double bal;
Balance(String n, double b) {
name = n;
bal = b;
}
void show() {
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
class AccountBalance {
public static void main(String args[]) {
Balance current[] = new Balance[3];
current[0] = new Balance("Ball", 123.23);
current[1] = new Balance("Pen", 157.02);
current[2] = new Balance("Pencil", -12.33);
for(int i=0; i<3; i++) current[i].show();
}
}
Note:
1. Save this file as AccountBalance.java, and put it in a directory called MyPack. Next, compile
the file. Make sure that the resulting .class file is also in the MyPack directory. Then execute the
AccountBalance class, using the command line: java MyPack.AccountBalance
2. We cannot use this command line: java AccountBalance because AccountBalance is qualified
with its package name.
3.3.4 ACCESSING PACKAGES:

12
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
 Java includes the import statement to bring certain classes, or entire packages, into visibility.
 Once imported, a class can be referred to directly, using only its name.
 import statements occur immediately following the package statement (if it exists) and before any
class definitions.
General form:
import package1 [.package2] [.package3] […].classname;
 package1  top level package, package2  package that is inside the package1 and so on. The
statement must end with a semicolon;
 All the members of the class can be directly accessed using class name or its objects directly without
using the package name.
Ex: import package name.*;
 The star (*) indicates that the compiler should search the entire package hierarchy when it encounters
a class name.

3.3.5 USING A PACKAGE:


 Some simple programs that will use classes from other packages.

package pack1; import pack1.classA;


public class classA import pack2.*;
{ class packTest
public void displayA( ) { public static void main String(a[]))
{ {
System.out.println (“First package”); classA objA = new classA( );
} objA.displayA( );
} }}

 This source file should be named as classA.java and stored in the subdirectory pack1.
 Now compile this java file. The resultant classA.class will be stored in the same directory.

Importing package1 to the main method


import package1.classA;
import packTest
{ public static void main(String[] args)
{
classA objectA=new classA( );
objectA.displayA( );
}
}

13
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
3.3.6 ADDING A CLASS TO A PACKAGE
 It is simple to add a class to an existing package.
 Consider the following package:
package p1:
public ClassA
{
//body of A
}
 The package p1 contains one public class by name A. Suppose we want to add another class B to this
package.
 This can be done as follows:
1. Define the class and make it public.
2. Place the package statement package p1;
before the class definition as follows:
package p1
pub1ic class B
{
//body or B
}
3. Store this as B.java file under the directory p1.
4. Compile B .java file. This will create a B.class file and place it in the directory p1.
 Note that we can also add a non-public class to a package using the same procedure.
 Now, the package p1 will contain both the classes A and B. A statement like
import p1.*;
will import both of them.
 If we want to create a package with multiple public classes in it, we may follow the following steps:
1. Decide the name of the package.
2. Create a subdirectory with this name under the directory where main source files are stored.
3. Create classes that are to be placed in the package in separate source files and declare the
package statement
package packagename:
at the top of each source file.
4. Switch to the subdirectory created earlier and compile each source file. When completed, the
package would contain .class files or all the source files.

14

You might also like