Date post: | 26-Dec-2015 |
Category: |
Documents |
Upload: | nora-daniel |
View: | 253 times |
Download: | 0 times |
Session 5
java.lang packageUsing arrayjava.io package: StringTokenizer, ArrayList, VectorUsing Generic
java.lang package The package consists classes and interface which are
fundamental to Java programming All the program automaticlly import java.lang package It contains
Wrapper classes
Wrapper classes (cont…)
Common methods
Math class Defining methods for basic numeric
operations as well as trigonomethic functions
All the methods are static This is final class Methods
public static double pow(double x, double y) public static double exp(double x) public static double log(double x)
Methods of Math class Trigonometric methods
public static double sin(double x) public static double cos(double x) public static double tan(double x)
Arirthmetic methods
Array Stored many values Elements in array have the same datatype Elements in array are accessed throught by
subscript
Types of array: Single dimension array (one dimension array) Multi demension array
One Dimensional Array Declarations Three ways to declare an array are:
datatype identifier [ ];
int a[]; or int [] a;
datatype identifier [ ] = new datatype[size];
char ch[] = new char[10];
datatype identifier [ ] = {value1,value2,….valueN};
byte b[] = {12, 3, 5};
Initialize elements in array Init value for each elementa[0] = 12;
a[1] = 15; Init when creating arrayint a[] = {12, 15, 17};
Using loopfor(int i = 0 ; i < a.length ; i++)
a[i] = …;
Example
class ArrDemo{public static void main(String [] arg){double nums[] = {10.1, 11.3, 12.5,13.7, 14.9};System.out.println(" The value at location 3 is : " +
nums[3]);}
}
Two dimension array Array that has more than one dimention
Syntax:int a[][];
int []a[] = new int[2][3];
int [][]a = {{1, 2}, {3, 4}, {-9, 0}};
a[0][0] a[0][1] a[0][2]
a[0] 1 3 5
a[1] 9 -81 7
a[1][0] a[1][1] a[1][2]
Initialize 2 dimension array Initialize for each elementsa[0][0] = ‘c’;
a[0][1] = ‘e’; Initialize when declaring arrayint a[][] = {{1, 2}, {13, -78}};
Using loopfor(int i = 0 ; i < n ; i++)
for(int j = 0 ; j < m ; j++)
a[i][j] = …;
String class In Java, a string literal is an object of
type String class. Hence manipulation of strings will be
done through the use of the methods provided by the String class.
String class is in java.lang package Every time we need an altered version
of the String, a new String object is created with the modifications in it.
Compare two String String length(): This method determines the
length of a string. The == operator and equals(), compareTo()
method can be used for strings comparison. The == operator checks if the two operands being used
are one and the same object. The equals() method checks if the contents of the two
operands are the same. compareTo() return value = 0 if s1 = s2, return value >0
if s1 > s2, return value < 0 if s1 < s2
Methods of String trim () substring (int start, int
end) equals (Object s) equalsIgnoreCase (String
s)
charAt(int i)
endsWith (String s)
startsWith (String s)
indexOf (String s)
lastIndexOf (String s)
toLowerCase ()
toUpperCase ()
Exampleclass StringTest {
public static void main(String[] args) { String name = args[0]; if(name.startsWith("M")) System.out.println("Hey my name also starts with an M! "); int length = name.length(); System.out.println("Your name has "+length+" characters"); String name_in_caps = name.toUpperCase(); System.out.println(name_in_caps); }}
Convert String into numberString s = “12”;
String to intint a = Interger.parseInt(s);
String to floatfloat f = Float.parseFloat(s);
Array of Strings
String s[];
s = new String[3];
Or String s[] = new String[3];
Or String []s = {“a”, “b”, “c”};
Learn Java By Example 19/21
Immutability of String Strings in Java once created cannot be
changed directly.
This is known as immutability in Strings.
Learn Java By Example 20/21
Exampleclass Testing { public static void main(String[] args) {
String str = "Hello"; str.concat("And Goodbye"); System.out.println(str); }}
Learn Java By Example 21/21
java.util package Contains useful classes
providing a broard range of functionality
Collection classes are useful for working with groups of objects
Contains classes that provides date and time, calendar, dictionary facilities
StringTokenizer Placed at java.util Seperated String into token Methods
countTokens() hasMoreElements() hasMoreTokens() nextElement() nextToken()
Example: s = “22+3-5/3” Token: 22 3 5 3 Separator: + - /
ArrayList An ArrayList object is a variable length
array of object references. Used to create dynamic arrays Extends AbstractList and implements List interface.
ArrayLists are created with an initial size.
As elements are added, size increases and the array expands.
ArrayList (cont…) Constructors Methods
•size()
•add(int index, E element)
•get(int index)
•indexOf(Object elem)
•lastIndexOf(Object elem)
•remove(int index)
•remove(Object o)
•set(int index, E element)
Vector class Similar to ArrayList class, allows to implement
dynamic array Storing an array of objects that size can increase
or decrease At any given point of time, an instance of type Vector has the capacity to hold a certain number of elements.
When it becomes full, its capacity is incremented by an amount specific to that Vector object.
Diffirence between Vector and ArrayList is that methods of Vector are synchronized and are thread-safe
Vector class (cont…)
Generic Earlier Collection treated elements as a collection of objects.
To retrieve an element from a Collection required an explicit cast
Thus, there was always a risk of runtime exception, ClassCastException
Generic allows the programmer to communicate the type of a collection to the compiler so that it can be checked.
The compiler consistently checks for the element type of the collection.
And inserts the correct cast on elements being taken out of the collection.
Example
Example of Generic Code
required explicit cast
No required explicit cast
Type of element