Download Strings - E

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Array data structure wikipedia , lookup

Java ConcurrentMap wikipedia , lookup

Transcript
STUDY MATERIAL
Subject –C++ and Java Programming
Unit – V
Class – II BBA CA
Semester - III
SYLLABUS:
Arrays, Strings & vectors – interfaces- packages
ARRAYS IN JAVA
Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.
This tutorial introduces how to declare array variables, create arrays, and process arrays using
indexed variables.
Declaring Array Variables:
To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference. Here is the syntax for declaring an array
variable:
dataType[] arrayRefVar;
// preferred way.
or
dataType arrayRefVar[];
//
works but not preferred way.
Note: The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[]
comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.
Example:
The following code snippets are examples of this syntax:
double[] myList;
// preferred way.
or
double myList[];
//
works but not preferred way.
Creating Arrays:
You can create an array by using the new operator with the following syntax:
arrayRefVar = new dataType[arraySize];
The above statement does two things:


It creates an array using new dataType[arraySize];
It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below:
dataType[] arrayRefVar = new dataType[arraySize];
Alternatively you can create arrays as follows:
dataType[] arrayRefVar = {value0, value1, ..., valuek};
The array elements are accessed through the index. Array indices are 0-based; that is, they start
from 0 to arrayRefVar.length-1.
Example:
Following statement declares an array variable, myList, creates an array of 10 elements of double
type and assigns its reference to myList:
double[] myList = new double[10];
Following picture represents array myList. Here, myList holds ten double values and the indices
are from 0 to 9.
Processing Arrays:
When processing array elements, we often use either for loop or foreach loop because all of the
elements in an array are of the same type and the size of the array is known.
Example:
Here is a complete example of showing how to create, initialize and process arrays:
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
This would produce the following result:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
Strings
Strings, which are widely used in Java programming, are a sequence of characters. In the Java
programming language, strings are objects.
The Java platform provides the String class to create and manipulate strings.
Strings
Creating Strings
The most direct way to create a string is to write:
String greeting = "Hello world!";
In this case, "Hello world!" is a string literal—a series of characters in your code that is enclosed
in double quotes. Whenever it encounters a string literal in your code, the compiler creates a
String object with its value—in this case, Hello world!.
String Length
Methods used to obtain information about an object are known as accessor methods. One
accessor method that you can use with strings is the length() method, which returns the number
of characters contained in the string object. After the following two lines of code have been
executed, len equals 17:
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
A palindrome is a word or sentence that is symmetric—it is spelled the same forward and
backward, ignoring case and punctuation. Here is a short and inefficient program to reverse a
palindrome string. It invokes the String method charAt(i), which returns the ith character in
the string, counting from 0.
public class StringDemo {
public static void main(String[] args) {
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
char[] tempCharArray = new char[len];
char[] charArray = new char[len];
// put original string in an
// array of chars
for (int i = 0; i < len; i++) {
tempCharArray[i] =
palindrome.charAt(i);
}
// reverse array of chars
for (int j = 0; j < len; j++) {
charArray[j] =
tempCharArray[len - 1 - j];
}
String reversePalindrome =
new String(charArray);
System.out.println(reversePalindrome);
}
}
Running the program produces this output:
doT saw I was toD
To accomplish the string reversal, the program had to convert the string to an array of characters
(first for loop), reverse the array into a second array (second for loop), and then convert back to
a string. The String class includes a method, getChars(), to convert a string, or a portion of a
string, into an array of characters so we could replace the first for loop in the program above
with
palindrome.getChars(0, len, tempCharArray, 0);
Concatenating Strings
The String class includes a method for concatenating two strings:
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end.
String Methods API
length() method

returns int
The length() methods tells you how many characters (including white space) are in a
String.
o Examples
 Example 1)
String myStr="abc"
System.out.println(myStr.length())
3
Example 2)
String myStr2="a b34 "
System.out.println(myStr2.length())
5
Remember, you need to count the space between a and b!
Vectors
Vectors (the java.util.Vector class) are commonly used instead of arrays, because they
expand automatically when new data is added to them. The Java 2 Collections API introduced
the similar ArrayList data structure. ArrayLists are unsynchronized and therefore faster than
Vectors, but less secure in a multithreaded environment. The Vector class was changed in Java 2
to add the additional methods supported by ArrayList. See below for a reasons to use each. The
description below is for the (new) Vector class.
Vectors can hold only Objects and not primitive types (eg, int). If you want to put a primitive
type in a Vector, put it inside an object (eg, to save an integer value use the Integer class or
define your own class). If you use the Integer wrapper, you will not be able to change the integer
value, so it is sometimes useful to define your own class.
To Create a Vector
You must import either import java.util.Vector; or import java.util.*;. Vectors are
implemented with an array, and when that array is full and an additional element is added, a new
array must be allocated. Because it takes time to create a bigger array and copy the elements
from the old array to the new array, it is a little faster to create a Vector with a size that it will
commonly be when full. Of course, if you knew the final size, you could simply use an array.
However, for non-critical sections of code programmers typically don't specify an initial size.

Create a Vector with default initial size
Vector v = new Vector();

Create a Vector with an initial size
Vector v = new Vector(300);
To Add elements to the end of a Vector
v.add(s); // adds s to the end of the Vector v
To get the elements from a Vector (ListIterator)
You can use a for loop to get all the elements from a Vector, but another very common way to
go over all elements in a Vector is to use a ListIterator. The advantage of an iterator is that it it
can be used with other data structures, so that if you later change to using a linked list for
example, you won't have to change your code. Here is an example of using an iterator to print all
elements (Strings) in a vector. The two most useful methods are hasNext(), which returns true if
there are more elements, and next(), which returns the next element.
ListIterator iter = v.listIterator();
while (iter.hasNext()) {
System.out.println((String)iter.next());
}
Common Vector Methods
There are many useful methods in the Vector class and its parent classes. Here are some of the
most useful. v is a Vector, i is an int index, o is an Object.
Method
Description
v.add(o)
adds Object o to Vector v
v.add(i, o)
Inserts Object o at index i, shifting elements up as necessary.
v.clear()
removes all elements from Vector v
v.contains(o)
Returns true if Vector v contains Object o
v.firstElement(i)
Returns the first element.
v.get(i)
Returns the object at int index i.
v.lastElement(i)
Returns the last element.
Returns a ListIterator that can be used to go over the Vector. This is a
v.listIterator()
useful alternative to the for loop.
Removes the element at position i, and shifts all following elements
v.remove(i)
down.
v.set(i,o)
Sets the element at index i to o.
v.size()
Returns the number of elements in Vector v.
The array parameter can be any Object subclass (eg, String). This returns
the vector values in that array (or a larger array if necessary). This is
v.toArray(Object[])
useful when you need the generality of a Vector for input, but need the
speed of arrays when processing the data.
Old and New Vector Methods
When the new Collections API was introduced in Java 2 to provide uniform data structure
classes, the Vector class was updated to implement the List interface. Use the List methods
because they are common to other data structure. If you later decide to use something other than
a Vector (eg, ArrayList, or LinkedList, your other code will not need to change.
Even up thru the first several versions of Java 2 (SDK 1.4), the language had not entirely
changed to use the new Collections methods. For example, the DefaultListModel still uses the
old methods, so if you are using a JList, you will need to use the old method names. There are
hints that they plan to change this, but still and interesting omission.
Replacements for old methods
The following methods have been changed from the old to the new Vector API.
Old Method
void addElement(Object)
void copyInto(Object[])
Object elementAt(int)
New Method
boolean add(Object)
Object[] toArray()
Object get(int)
Iterator iterator()
ListIterator listIterator()
void insertElementAt(Object, int) void add(index, Object)
void removeAllElements()
void clear()
boolean removeElement(Object) boolean remove(Object)
void removeElementAt(int)
void remove(int)
void setElementAt(int)
Object set(int, Object)
Enumeration elements()
Insuring use of the new API
When you create a Vector, you can assign it to a List (a Collections interface). This will
guarantee that only the List methods are called.
Vector v1 = new Vector();
List
v2 = new Vector();
// allows old or new methods.
// allows only the new (List) methods.
Interfaces: An interface is a specification of method properties. We can not create on object in interface. We
createreference variable for interface.
Interface class
Implementation class
implementation class
Driver: - A driver represents implementation classes of an interface.
void connect( );
{
-------}
Oracle
SyBase
My Sql
API
 // interface example
interface MyInter
{
void connect( );
}
class OracleDB implements MyInter
{
public void connect( )
{
System.out.println("Connecting to oracle data base .....");
}
}
class SybaseDB implements MyInter
{
public void connect( )
{
System.out.println("Connecting to Sybase data base .....");
}
}
class DataBase
{
public static void main(String args[]) throws Exception
{
// accapt user dats base name through command line arguments store in an object c
Class c=Class.forName(args[0]);
// create another object to the class whose name is in c
MyInter mi=(MyInter)c.newInstance( );
// call convert method of the object
mi.connect( );
}
}
D:\psr\Core java>javac DataBase.java
D:\psr\Core java>java DataBase SybaseDB
Connecting to sybase data base.....
D:\psr\Core java>java DataBase OracleDB
Connecting to oracle data base.....
C
I
OracleDB
mi
II
connect( )
 1) An interface is a specification of method prototype.
2) An interface contains 0 or more abstract methods.
3) All the methods as the interface are public and abstract by default.
4) An interface can also contain variables which are public, static and final by default.
5) We can not create an object to an interface.
6) But we can create a reference variable of interface type.
7) All the methods of the interface should be implemented in its implementation classes.
8) If any method is not implemented, then that class should be declared as ‘abstract’.
9) Interface reference can be used to refer to all the objects of its implementation classes.
10) Once an interface is written, any third party vendor can provide implementation classes.
11) An interface can not implement another interface.
12) An interface can extend another interface.
13) We can create classes in an interface.
14) A class can implement multiple interfaces.
Class A implements B,C…
What is the difference between abstract & interface? : A) Interface contains only abstract methods. Abstract class contains instance variables. Interface
contains constant. The abstract method should be implemented in its sub classes. All the methods
of interface should be implemented in implemented classes. An abstract class is declared using
the key word ‘abstract’. Interface is declared using ‘interface’.
* A programmer writes an abstract class when there are some common features shared by
all the objects.
* A programmer writes an interface when all the features should be implemented
differently in different objects.
When abstract class is written the programmer should provide the sub class.
When interface is written any third party vendor can provide implementation class.
 How much memory is taken by class two’s object?
1) 4 b 2) 8 b 3) >8 b 4) <8 b
A) Ans is >8 b because
it is also taken memory of class two
Ex: class One
{
int x;
}
int x
int x
class Two extends One
{
int x;
}
4+4
8
Types of inheritance: 1) Single inheritance: - A producing sub class from a single super class is called single
inheritance.
A
class A
class B extends A
B
A
B
class A
class B extends A
class C extends A
class D extends A
C
D
2) Multiple inheritances: - Producing sub class from multiple super classes is called multiple
inheritances. Multiple means more than one.
Multiple inheritances are not supported in java.
EX: -
A
B
class A
class B
class C extends A,B
C
A
B
D
C
class A
class B
class C
class D extends A,B,C
class E extends A,B,C
E
 Why multiple inheritances are not supported in java?
// invalid
Statements
in java
A)
1) Multiple inheritance leads to confusion for a programmer. Operator over loading,
multiple inheritances are not available in java.
A
B
x
x
C
x
2) If the programmer wants we can achieve multiple inheritance using interfaces.
class D extends A,B,C
// invalid
class D implements A,B,C // valid
Here A,B,C are not classes only interfaces. So it is not multiple inheritances. This
is way of multiple inheritances indirectly.
3) A programmer can achieve multiple inheritances by using single inheritance
repeatedly.
Because the above reasons the direct multiple inheritances is not available in java.
// multiple inheritances Using interfaces
interface Father
{
int prop1=500000;
float ht1=6.2f;
}
interface Mother
{
int prop2=400000;
float ht2=5.2f;
}
class Child implements Father,Mother
{
void property( )
{
System.out.println("child property="+(prop1+prop2));
}
void height( )
{
System.out.println("child height="+(ht1+ht2)/2);
}
}
class Multi
{
public static void main(String args[])
{
Child ch=new Child( );
ch.property( );
ch.height( );
}
}
D:\psr\Core java>javac Multi.java
D:\psr\Core java>java Multi
child property=900000
child height=5.7
Multi
Inheritance
Hierarchical
Inheritance
Hybrid
Inheritance
Packages: A package represents a sub directory that contains a group of elements.
EX: - import.java.io.*;
Compile: - javac –d . class name.java
Advantages of packages: 1) Packages hide classes & interfaces. Thus they provide protection for them.
2) The classes of one Package are isolated from the classes of another Package. So it is
possible to use same names for the classes into different packages.
3) Using package concept we can create our own Packages & also we can extend already
available Packages.
4) Packages provide re usability of code.
 // creating our own Package: pack
package pack;
public class Addition
{
private double d1,d2;
public Addition(double a,double b)
{
d1=a;
d2=b;
}
public void sum( )
{
System.out.println("Sum="+(d1+d2));
}
}
D:\psr\Core java>javac -d . Addition.java
 // using package: pack (Addition)
class AdditionUse
{
public static void main(String args[])
{
pack.Addition obj=new pack.Addition(10,15.5);
obj.sum( );
}
}
D:\psr\Core java>javac -d . AdditionUse.java
D:\psr\Core java>java AdditionUse
Sum=25.5
 // using package: pack
package pack;
public class Subtraction
{
public static double sub(double a,double b)
{
return a-b;
}
}
D:\psr\Core java>javac -d . Subtraction.java
 // using package: pack (Subtraction)
class SubtractionUse
{
public static void main(String args[])
{
pack.Addition obj=new pack.Addition(13,43.5);
obj.sum( );
double res=pack.Subtraction.sub(13,43.5);
System.out.println("result = "+res);
}
}
D:\psr\Core java>javac -d . SubtractionUse.java
D:\psr\Core java>java SubtractionUse
Sum=56.5
result = -30.5
(or)
import pack.Addition;
import pack.*
import pack.Subtraction;
class SubtractionUse1
{
public static void main(String args[])
{
Addition obj=new Addition(13,43.5);
obj.sum( );
double res=Subtraction.sub(13,43.5);
System.out.println("result = "+res);
}
}
Import the package name eliminates the before adding class names.
Error: - bad class file : .\Addition.java
We can handle these errors must follow some steps
Step 1: - Java compile searches from the package in .jar(java archair)
following directory
C:\program files\java\jre1.5.0\lib\ext
file format in the
 What is java archair file?
A) Jar file is a compressed version of several. Class or. Java files. A jar file created using jar
utility provided by sun micro systems.
Class path: Class path is an operating system variable. That stores active directory path.
 To sea the class path
 // adding interface to the package: pack
package pack;
public interface MyDate // just display date & time
{
void showDate( ); // public abstract
}
D:\psr\Core java>javac -d . MyDate.java
 // this is implementation class of MyDate
package pack;
import pack.MyDate;
import java.util.Date;
public class MyDateImpl implements MyDate
{
public void showDate( )
{
Date d=new Date( );
System.out.println(d);
}
}
D:\psr\Core java>javac -d . MyDateImpl.java
 // using the implementation class object
import pack.MyDateImpl;
class MyDateImplUse
{
public static void main(String[] args)
{
MyDateImpl obj=new MyDateImpl( );
obj.showDate( );
}
}
D:\psr\Core java>javac -d . MyDateImplUse.java
D:\psr\Core java>java MyDateImplUse
Mon Sep 03 13:23:55 IST 2007
 // creating sub package
package inet;
public class Sample
{
public void show( )
{
System.out.println("Hai how are u");
}
}
D:\psr\Core java>javac –d . Sample.java
 // using the sub package
import inet.Sample;
public class SampleUse
{
public static void main(String args[])
{
Sample s=new Sample( );
s.show( );
}
}
D:\psr\Core java>javac SampleUse.java
D:\psr\Core java>java SampleUse
Hai how are u
Suppose inet directory cut & paste the directory in the drive pskr directory and set the path
set classpath d:\pskr;.;%classpath%
Access specifiers (or) access modifiers: - An access specifier is a key word that specifies how
to read or access the members of a class or the class itself. There are 4 types of access specifiers.
They are
1) private 2) public 3) protected 4) default
1) private members of a class are not accessible in other classes of same package or another
package.
2) public members of a class are available to other classes of same package or another package.
Its scope is global scope.
3) protected members are accessible to the other classes of the same package but not in another
package.
B
A
C
private
public
protected
default
Same directory
another
4) default members are accessible in other classes of the same package. They are not accessible
in another package. Its scope is package scope.
Note: - protected members of a class are always available to its sub classes in the same package
or another package also. The scope of protected of some times global scope & some time
package scope.
 // access specifiers
package same;
public class A
{
private int a=1;
public int b=2;
protected int c=3;
int d=4;
}
D:\psr\Core java>javac -d . A.java
 // access specifier with same package
package same;
import same.A;
public class B
{
public static void main(String args[])
{
A obj=new A( );
System.out.println(obj.a);
System.out.println(obj.b);
System.out.println(obj.c);
System.out.println(obj.d);
}
}
D:\psr\Core java>javac -d . B.java
B.java:9: a has private access in same.A
System.out.println(obj.a);
^
1 error
 // access specifier with another package
package another;
import same.A;
public class C
{
public static void main(String args[])
{
A obj=new A( );
System.out.println(obj.a);
System.out.println(obj.b);
System.out.println(obj.c);
System.out.println(obj.d);
}
}
Exception handling: - An exception is a runtime error.
An error is software is called a bug. Removing errors from software is called debugging.
1) Compile time errors: - These are errors in the syntax or the grammar of the language.
These errors are detected by the compiler at run time of compilation. (Java compiler can
display up to 100 errors). Desk checking is the solution of compile time errors.
2) Run time errors: - These errors are the errors which occur because in sufficiently of
compiler system. These errors are detected by JVM at the time of running the program.
Run time errors are serious errors. Only the programmers are responsible for it.
3) Logical errors: - These errors represent bad logic (or) these errors are not detected by the
compiler or JVM. Logical errors are detected by comparing the program out put with
manually calculated result.
Exception: - Any abnormal event in the program is called an exception. All exception are
represented by classes in java
 // Exception example
class ExceptionDemo
{
public static void main(String args[])
{
System.out.println("open files");
int n=args.length;
System.out.println("n="+n);
int a=45/n;
System.out.println("a="+a);
System.out.println("close files");
}
}