Sie sind auf Seite 1von 46

ARRAYS

ARRAYS-INTRODUCTION

 Array is a group of contiguous or related data


item that share a common name.
 Eg: of an array..

 Salary[10]

 Two types of array.

1) One dimensional

2) Two dimennsional
 To create an array, you first must create an
array variable of the desired type.
 The general form of a onedimensional array
declaration is
 type var-name[ ];

 type declares what type of data the array will


hold.
 Eg:
 int number[];

 This describes that the number is an array


variable.
 and number = new int[5];

 This links number with an actual, physical


array of integers.
 Note: In java , subscript starts with the value
0.
CREATING AN ARRAY

 1. Declaring an array
 2. Creating memory location

 3. Putting values into the memory location

 Array in java can be declared in the two forms:


 1. type arrayname[];

 2. type [] arrayname;
 Creation of array can be done by the following
line :
 Arrayname = new type[size];
 Eg : number = new int [5];
 we can also combine the two steps like:
 Int number [] = new int [5];
 Finally initiallization can be done as:
 Arrayname[subscript] = value;
 Note : Unlike C, java protects array from overrun
and underruns .ie trying to access an array
bound its boundaries will generate an error.
ARRAY LENGTH

 In java all array store the allocated size in a


variable named length.
 int aSize = a.length

 This info will be useful in the manipulation of


arrays when their sizes are not known.
TWO DIMENSIONAL ARRAY
 In Java, multidimensional arrays are actually
arrays of arrays
 To declare a multidimensional array variable,
specify each additional index using another set of
square brackets
 int twoD[][] = new int[4][5];
 This allocates a 4 by 5 array and assigns it to
twoD.
 Internally this matrix is implemented as an array of
arrays of int.
 When you allocate memory for a
multidimensional array, you need only specify
the memory for the first (leftmost) dimension
 You can allocate the remaining dimensions

 separately.

 Eg: int twoD[][] = new int[4][];

 twoD[0] = new int[5];

 twoD[1]=new int[5];
 You can Manually allocate differing size second
dimensions.
 int twoD[][] = new int[4][];

 twoD[0] = new int[1];

 twoD[1] = new int[2];

 twoD[2] = new int[3];

 twoD[3] = new int[4];


STRINGS

 String represent a sequence of characters.


 Unlike many other languages that implement
strings as character arrays, Java implements
strings as objects of type String.
 In java strings are class object and
implemented using two classes,
 String and StringBuffer
 In java String is an instantiated object of the
String class.
 Java strings, as compared to C string are more
reliable and predictable.
 This is because C lack the bound-checking.

 A java string is not a character array and is not


NULL terminated.
 String may be declared and created as:
 String stringname;
 Stringname = new String (“string”);
 Eg:
 String fname;
 fname = new String (“john”);
 Note:when you create a String object, you are
creating a string that cannot be changed.
 That is, once a String object has been created, you
cannot change the characters that comprise that
string.
 Each time you need an altered version of an
existing string, a new String object is created that
contains the modifications. The original string is
left unchanged.
 This approach is used because fixed, immutable
strings can be implemented more efficiently than
changeable ones.
 There is a companion class to String called
StringBuffer, whose objects contain strings that
can be modified after they are created.
 Both the String and StringBuffer classes are
defined in java.lang.
 To create a String initialized by an array of
characters, use the constructor shown here:
 String(char chars[ ])

 char chars[] = { 'a', 'b', 'c' };

 String s = new String(chars);

 This constructor initializes s with the string


“abc”.
 You can specify a subrange of a character array as
an initializer using the following constructor:
 String(char chars[ ], int startIndex, int numChars)

 Here, startIndex specifies the index at which the


subrange begins, and numChars specifies the
number of characters to use. Here is an example:
 char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };

 String s = new String(chars, 2, 3);

 This initializes s with the characters cde.


 You can construct a String object that contains
the same character sequence as another String
object using this constructor:
 String s2 = new String(s1);

 System.out.println(s1);

 System.out.println(s2);
SPECIAL STRING OPERATIONS

 String Concatenation:
 In general, Java does not allow operators to be
applied to String objects.
 The one exception to this rule is the + operator,
which concatenates two strings, producing a
 String object as the result.

 You can concatenate strings with other types of


data.
STRING FUNCTIONS

 charAt(int index)
Returns the character at the specified
index. An index ranges from 0 to length() - 1.
Eg:char ch;
ch = "abc".charAt(1); //assigns the value “b” to ch
 getChars:
 If you need to extract more than one character
at a time, you can use the getChars( ) method.
It has this general form:
 void getChars(int sourceStart, int sourceEnd,
char target[ ], int targetStart)
 Care must be taken to assure that the target
array is large enough to hold the number of
characters in the specified substring.
 Eg: getCharsDemo program
 toCharArray( ):
 If you want to convert all the characters in a
String object into a character array, the easiest
way is to call toCharArray( ).
 char[ ] toCharArray( )

 Alternate function is getChars( )


STRING COMPARISON
 equals( ) and equalsIgnoreCase( )
 To compare two strings for equality, use
 equals( ). It has this general form:
 boolean equals(Object str)
 To perform a comparison that ignores case
differences, call equalsIgnoreCase( ).
 boolean equalsIgnoreCase(String str)
 Eg:equalsDemo
 regionMatches( ):
 The regionMatches( ) method compares a
specific region inside a string with another
specific region in another string.
 boolean regionMatches(boolean ignoreCase,
int startIndex,String
str2, int
str2StartIndex, int numChars)
 startsWith( ) and endsWith( ):
 The startsWith( ) method determines whether a
given String begins with a specified string.
 endsWith( ) determines whether the String in
 question ends with a specified string.
 boolean startsWith(String str)
 boolean endsWith(String str)
 str is the String being tested. If the string matches,
true is returned
 equals( ) Versus ==
 It is important to understand that the equals( )
method and the == operator perform two
different operations.
 The equals( ) method compares the characters
inside a String object.
 The == operator compares two object
references to see whether they refer to the
same instance
 compareTo(Object o)
Compares this String to another Object
 If the Object is a String, this function behaves
like compareTo(String). Otherwise, it throws
a ClassCastException
 Value Meaning
 Less than zero : The invoking string is less than str.
 Greater than zero: The invoking string is greater than str.
 Zero :The two strings are equal.
STRING BUFFER CLASS

 It’s a pear class of String.


 While string creates string 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 substring in the
middle of a string, or append another string to
the end.
COMMONLY USED STRINGBUFFER METHODS

Method Task
S1.setCharAt(n,’x’) Modifies the nth character to x
S1.append(s2) Appends the string s2 to s1 at
the end
S1.insert(n,s2) Insert 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.
 public class StringBufferFunctionsDemo {

 public static void main(String[] args) {


 // Examples of Creation of Strings
 StringBuffer strBuf1 = new StringBuffer("johny");
 StringBuffer strBuf2 = new StringBuffer(100); //With capacity
100
 StringBuffer strBuf3 = new StringBuffer(); //Default Capacity
16
 System.out.println("strBuf1 : " + strBuf1);
 System.out.println("strBuf1 capacity : " + strBuf1.capacity());
 System.out.println("strBuf2 capacity : " + strBuf2.capacity());
 System.out.println("strBuf3 capacity : " + strBuf3.capacity());
 System.out.println("strBuf1 length : " + strBuf1.length());
 System.out.println("strBuf1 charAt 2 : " + strBuf1.charAt(2));
 // A StringIndexOutOfBoundsException is thrown if the
index is not valid.

strBuf1.setCharAt(1, 't');
System.out.println("strBuf1 after setCharAt 1 to t is : "
+ strBuf1);
System.out
.println("strBuf1 toString() is : " + strBuf1.toString());
strBuf3.append("beginner-java-tutorial");
System.out.println("strBuf3 when appended with a String : "
+ strBuf3.toString());
strBuf3.insert(1, 'c');
System.out.println("strBuf3 when c is inserted at 1 : "
+ strBuf3.toString());
strBuf3.delete(1, 'c');
System.out.println("strBuf3 when c is deleted at 1 : "
+ strBuf3.toString());
strBuf3.reverse();
System.out.println("Reversed strBuf3 : " + strBuf3);
strBuf2.setLength(5);
strBuf2.append("jdbc-tutorial");
System.out.println("strBuf2 : " + strBuf2);
// We can clear a StringBuffer using the following line
strBuf2.setLength(0);
System.out.println("strBuf2 when cleared using setLength(0): "
+ strBuf2);
}
}
VECTORS

 Vectors can hold objects of any type and any


number.
 Vector class contained in the java.util package
can be used to achieve the concept of variable
arguments to method.
 The objects can be of various types.

 Arrays can be easily implemented as vectors.


CREATION
 Vectors are created like arrays as follows.

 Vector intVect = new Vector(); // without size


 Vector list = new Vector(3); // with size

 A vector without size can accommodate an


unknown number of items.
 Even when a size is specified it can be
overlooked and a different no of items may be
put into the vector
ADVANTAGES OVER ARRAY
1) It is convenient to use vector 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.
Disadvantage:
A major constraint in using vectors is that we
cannot directly store simple datatypes in
vector. We can only store objects.
Important Vectors methods
WRAPPER CLASS
 Java’s primitive data types (boolean, int, etc.)
are not classes.
 And vectors can not handle primitive datatypes
 Primitive datatypes may be converted into
objects by using the wrapper class
 They are contained in the java.lang package.
 Wrapper classes are used in situations where
objects are required.
PRIMITIVES & WRAPPERS

 Java has a wrapper class for each of the eight


primitive data types:
Primitive Wrapper Primitive Wrapper
Type Class Type Class

boolean Boolean float Float

byte Byte int Integer

char Character long Long

double Double short Short


CREATION
 Wrapper.valueOf()takes a value
(or string) and returns an
object of that class:
Integer i1 = Integer.valueOf(42);
Integer i2 = Integer.valueOf(“42”);

Boolean b1 = Boolean .valueOf(true);


Boolean b2 = Boolean .valueOf(“true”);

Long n1 = Long.valueOf(42000000L);
Long n1 = Long.valueOf(“42000000L”);
WRAPPER CLASS METHODS
 The wrapper class have a number of methods for
handling primitive datatypes and objects.
 They are as follows:
 Converting primitive numbers to Objects numbers using
Constructor Methods
 Integer IntVal = new Integer(i); // converts integer to
Integer object
 Float FloatVal = new Float(f); // primitive float to Float
object
 Same for Double and Long.
 Here i and f are denoting primitive datavalues denoting
int, float.They may be constants or variable
 Converting Object numbers to primitive
numbers using typeValue() Methods
 Method calling

 int j = IntVal.intValue() ; //Object to primitive


integer
 float f = FloatVal.floatValue(); // object to
primitive float
 Same goes for double and long
 Converting numbers to Strings using to String()
Method
 Method Calling

 str = Integer.toString(i); // Primitive integer to


string
 str = Float.toString(f); // Primitive integer to
string
 Same for double and long
 Converting String Objects to numeric objects
using the Static Method Valueof()
 Method Calling:

 DoubleVal = Double.Valueof(str); //convert


string to Double object
 LongVal = Long.Valueof(str); // convert string to
Long object
 Converting Numeric Strings to primitive
numbers using parsing method
 Method calling:

 int i = Integer.parseInt(str); // converts string


to primitive integer
 long l = Long.parseLong(str); // Converts string
to primitive long
 Note : If str does not represent an integer both
the above method throws a
NumberFormatException
ENUMERATED TYPES

 An enum type is a type whose fields consist of


a fixed set of constants.
 Common examples include compass directions
(values of NORTH, SOUTH, EAST, and WEST)
and the days of the week.
 Because they are constants, the names of an
enum type's fields are in uppercase letters
 Eg:
 public enum Day {

 SUNDAY, MONDAY, TUESDAY, WEDNESDAY,


THURSDAY, FRIDAY, SATURDAY ; // ; is optional
}
ADVANTAGES OF ENUM

 Compile-time type safty


 We can use the enum keyword in switch
statements.

Das könnte Ihnen auch gefallen