2. Topics Covered:
• using the NetBeans Debugger
• doing more with Arrays,
• parsing the args Array, two-dimensional
Arrays,
• collection, the ArrayList class
• working with list of items
• processing a list of items
3. Continued……..
• working with Dates
• using the String Class,
• using the StringBuilder Class, String Buffer,
• more about primitive data types,
• promoting and casting variables
• using the Java API Docs
5. Array
• Array is a collection of similar type of
elements that have contiguous memory
location.
• In java, array is an object the contains
elements of similar data type.
• It is a data structure where we store
similar elements. We can store only fixed
elements in an array.
• Array is index based, first element of the
array is stored at 0 index.
5
6. Advantage of Array
Code Optimization: It makes the code
optimized, we can retrieve or sort the data
easily.
Random access: We can get any data located
at any index position.
Disadvantage of Array
Size Limit: We can store only fixed size of
elements in the array. It doesn't grow its size
at runtime. To solve this problem, collection
framework is used in java.
6
7. Types of Array: There are two types of array.
• Single Dimensional Array
• Multidimensional Array-
• 2D array
• 3D array
• Jagged array
7
8. Single Dimensional Array
• The syntax for declaring and instantiating
an array:
There are two ways to declare an array,
type[] arrayName;
type arrayName[];
8
9. • How to instantiate an array
arrayName = new type[length];
• How to declare and instantiate an array in
one statement
type[] arrayName = new type[length];
9
10. Examples
• Array of integers
int[] num = new int[5];
• Array of Strings
String[] nameList = new String[5];
nameList[0] = "Amanda Green";
nameList[1] = "Vijay Arora";
nameList[2] = "Sheila Mann";
nameList[3] = "Rohit Sharma";
nameList[4] = "Mandy Johnson";10
11. Array length
• The syntax for getting the length of an
array
arrayName.length
e.g-
int[] values = new int[10];
for (int i = 0; i < values.length; i++)
{
values[i] = i;
} 11
12. The Arrays class
• Arrays.sort
e.g-
int[] numbers = {2,6,4,1,8,5,9,3,7,0};
Arrays.sort(numbers);
for (int num : numbers)
{
System.out.print(num + " ");
}
12
13. Some other methods:
• equals( arrayName1, arrayName2 )
• copyOf( arrayName, length )
• binarySearch( arrayName, value )
13
14. Two-dimensional arrays
The syntax for creating a rectangular array-
type[][] arrayName = new
type[rowCount][columnCount];
• A statement that creates a 3x2 array
int[][] numbers = new int[3][2];
• 3x2 array and initializes it in one
statement
int[][] numbers = { { 1, 2 }, { 3, 4 }, { 5, 6 } };14
16. Enhanced for loop for 2D array
for (int[] num: arr)
{
for(int data: num)
{
System.out.println(data);
}
}
16
17. parsing the args Array :anonymous array
An array without any name is called anonymous array.
Anonymous array is passed as an argument of method
Syntax: new arrayType[]{ array elements};
// anonymous int array
new int[] { 1, 2, 3, 4};
// anonymous char array
new char[] {'x', 'y', 'z‘};
// anonymous String array
new String[] {“hello", “hi", “bye"};
// anonymous multidimensional array
new int[][] { {10, 20}, {30, 40, 50} };
17
18. 3 d array:
Syntax:
array_type[][][] array_name = new
array_type[x][y][z];
Ex:
int[][][] num=new int[2][3][4];
Here, num[i][j][k] where ‘i’ is the array
number, ‘j’ is the row number and ‘k’ is
the column number.
18
22. Problem with array/limitations
• Fixed size
• Contain homogeneous elements
• Not contain Predefine data structure like:
stack,linked list,queue etc.
To overcome this problem go for collections
26. • Keyword: extends and implements
• Used in case of inheritance:
• Class to class-extends
(class classA extends classB)
• Interface to interface: extends
• Class to interfcae: implements
(class classA implements interfaceA)
27. Iterator interface
• Iterator is an interface that iterates the elements.
• Iterator can traverse elements in a collection only
in forward direction.
• It is used to traverse the list and modify the
elements. Iterator interface has three methods:
• public boolean hasNext() – This method returns
true if the iterator has more elements.
• public object next() – It returns the element and
moves the cursor pointer to the next element.
• public void remove() – This method removes the
last elements returned by the iterator.
28. ListIterator
• ListIterator is an interface in a Collection
framework, and it extends the
Iterator interface.
• Using ListIterator, you can traverse the
elements of the collection in
both forward and backwards directions.
29. Methods in ListIterator
• void add(Object object): It inserts object immediately before the element
that is returned by the next( ) function.
• boolean hasNext( ): It returns true if the list has a next element.
• boolean hasPrevious( ): It returns true if the list has a previous element.
• Object next( ): It returns the next element of the list. It throws
‘NoSuchElementException’ if there is no next element in the list.
• Object previous( ): It returns the previous element of the list. It throws
‘NoSuchElementException’ if there is no previous element.
• void remove( ): It removes the current element from the list. It throws
‘IllegalStateException’ if this function is called before next( ) or previous( )
is invoked.
30. Collection interface
Methods:
Method Description
public boolean add(E e) It is used to insert an element
in this collection.
public boolean remove(Object
element)
It is used to delete an element
from the collection.
public int size() It returns the total number of
elements in the collection.
public void clear() It removes the total number
of elements from the
collection.
public boolean
contains(Object element)
It is used to search an
element.
public boolean isEmpty() It checks if collection is
empty.
31. List interface
It is an interface that extends the Collection
interface.
List interface is implemented by the classes
ArrayList, LinkedList, Vector, and Stack.
Lists are further classified into the following:
• ArrayList
• LinkedList
• Vectors
32. ArrayList al=new ArrayList();
//creating old non-generic arraylist
ArrayList<String> al=new ArrayList<String>();
//creating new generic arraylist
Java new generic collection allows you to have
only one type of object in a collection. Now it
is type safe so typecasting is not required at
runtime.
33. Methods in ArrayList:
1. Add():
Add new elements to an ArrayList using the add() method.
Syntax:
arrayListObj.add(arrayListElement)
Ex:
List.add(“java”)
2. Adding an element at a particular index in an ArrayList.
Syntax:
arrayListObj.add(arrayListIndex, arrayListElement)
Ex:
List.add(2, “java”)
34. 3. size():
to find the size of an ArrayList using the size() method.
Syntax:
arrayListObj.size()
Ex:
List.size()
4. get():
access the element at a particular index in an ArrayList using the
get() method.
Syntax:
arrayListObj.get(0)
Ex:
List.get(0)
35. 5. Set():
to modify the element at a particular index in an
ArrayList using the set() method.
Syntax:
arrayListObj.set(index,element)
Ex:
List.set(4, “java”)
6. isEmpty():
To check if an ArrayList is empty using the isEmpty()
method.
It will return true or false
List.isEmpty()
36. 7. contains():
This method returns true if this list contains the
specified element.
Ex:
boolean retval = arrlist.contains(10);
8. remove():
to remove the element at a given index in an ArrayList
Syntax:
arrayListObj.remove(int index)
9. removeAll():
to remove all the elements from an ArrayList.
37. 10. indexOf():
The indexOf() method of ArrayList returns the
index of the first occurrence of the specified
element in this list, or -1 if this list does not
contain the element.
38. Methods in Stack class
• Object push(Object element) : Pushes an element on the top
of the stack.
• Object pop() : Removes and returns the top element of the
stack. An ‘EmptyStackException’ exception is thrown if we call
pop() when the invoking stack is empty.
• Object peek() : Returns the element on the top of the stack,
but does not remove it.
• boolean empty() : It returns true if nothing is on the top of
the stack. Else, returns false.
• int search(Object element) : It determines whether an object
exists in the stack. If the element is found, it returns the
position of the element from the top of the stack. Else, it
returns -1.
39. working with Dates
Date class in Java
The Date class of java.util package provides
constructors and methods to deal with date
and time with java.
Date() : Creates date object representing current
date and time.
java.text.SimpleDateFormat: provides date
format(hh:mm:ss a dd-MMM-yyyy)
Note: a is Am/pm marker
40. using the String Class
• String is a sequence of characters. But in Java,
string is an object that represents a sequence
of characters.
• The java.lang.String class is used to create a
string object.
• In java, Strings are immutable which means a
constant and cannot be changed once
created.
There are two ways to create String object:
By string literal
By new keyword
41. string literal:
String s=“kumar";
Each time you create a string literal, the JVM checks the "string
pool" first. If the string already exists in the pool, a reference
to the pooled object is returned. If the string doesn't exist in
the pool, a new string object is created and placed in the
pool.
String s1=“kumar";
String s2=“kumar";
//It doesn't create a new string object
kumar
s
kumar
s1
s2
string constant pool
string constant pool
42. By new keyword:
String s=new String(“kumar")
In this case, JVM will create a new string object
in normal (non-pool) heap memory, and the
literal “kumar" will be placed in the string
constant pool. The variable s will refer to the
object in a heap (non-pool).
43. S
Heap
string pool
String s1=“kumar”
String s2=“kumar”
String s3= “Rahul”
kumar
Rahul
s1
s2
s3String s4=new String(“kumar”)
s4 kumars1==s2 // true
s1==s3//false
s1==s4//false
Note:- Here s1,s2,s3 and s4 are references of string object kumar, Rahul, kumar
Concept:---
44. Memory Allocation in Java
The JVM divided the memory into following
sections.
• Heap
• Stack
• Code
• Static
45. • The code section contains your bytecode.
• The Stack section of memory
contains methods, local variables, and
reference variables.
• The Heap section contains Objects (may also
contain reference variables).
• The Static section contains Static
data/methods.
47. Length(), charAt()
int length();
char charAt(i);
Returns the number of characters in
the string
Returns the char at position i.
7
’n'
”Problem".length();
”Window".charAt (2);
Returns:
Character positions in strings are numbered
starting from 0 – just like arrays.
48. Substring()
“lev"
“mutable"
"" (empty string)
”television".substring (2,5);
“immutable".substring (2);
“bob".substring (9);
Returns:
television
i k
television
i
• String subs = word.substring (i, k);
– returns the substring of chars in
positions from i to k-1
• String subs = word.substring (i);
– returns the substring from the i-th
char to the end
Returns a new String by copying characters from an existing String.
49. Concatenation()
String word1 = “re”, word2 = “think”; word3 = “ing”;
int num = 2;
• String result = word1.concat (word2);
//the same as word1 + word2 “rethink“
50. indexOf()
String name =“President George Washington";
date.indexOf (‘P'); 0
date.indexOf (‘e'); 2
date.indexOf (“George"); 10
date.indexOf (‘e', 3); 6
date.indexOf (“Bob"); -1
date.lastIndexOf (‘e'); 15
Returns:
(not found)
(starts searching
at position 3)
0 2 6 10 15
51. equals()
boolean b = word1.equals(word2);
returns true if the string word1 is equal to word2
boolean b = word1.equalsIgnoreCase(word2);
returns true if the string word1 matches word2, case-
blind
b = “Raiders”.equals(“Raiders”);//true
b = “Raiders”.equals(“raiders”);//false
b = “Raiders”.equalsIgnoreCase(“raiders”);//true
52. compareTo()
int diff = word1.compareTo(word2);
returns the “difference” word1 - word2
int diff = word1.compareToIgnoreCase(word2);
returns the “difference” word1 - word2,
case-blind
53. Comparison Examples
//negative differences
diff = “apple”.compareTo(“berry”);//a before b
diff = “Zebra”.compareTo(“apple”);//Z before a
diff = “dig”.compareTo(“dug”);//i before u
diff = “dig”.compareTo(“digs”);//dig is shorter
//zero differences
diff = “apple”.compareTo(“apple”);//equal
diff = “dig”.compareToIgnoreCase(“DIG”);//equal
//positive differences
diff = “berry”.compareTo(“apple”);//b after a
diff = “apple”.compareTo(“Apple”);//a after A
diff = “BIT”.compareTo(“BIG”);//T after G
diff = “huge”.compareTo(“hug”);//huge is longer
54. trim()
String word2 = word1.trim ();
returns a new string formed from word1 by
removing white space at both ends
does not affect whites space in the middle
String word1 = “ Hi Bob “;
String word2 = word1.trim();
//word2 is “Hi Bob” – no spaces on either end
//word1 is still “ Hi Bob “ – with spaces
55. replace()
String word2 = word1.replace(oldCh, newCh);
returns a new string formed from word1 by
replacing all occurrences of oldCh with newCh
String word1 = “rare“;
String word2 = “rare“.replace(‘r’, ‘d’);
//word2 is “dade”, but word1 is still “rare“
56. Methods — Changing Case
String word2 = word1.toUpperCase();
String word3 = word1.toLowerCase();
returns a new string formed from word1 by
converting its characters to upper (lower) case
String word1 = “HeLLo“;
String word2 = word1.toUpperCase();//”HELLO”
String word3 = word1.toLowerCase();//”hello”
//word1 is still “HeLLo“