STRINGS IN JAVA

LOVELY PROFESSIONAL UNIVERSITY
LOVELY PROFESSIONAL UNIVERSITYStudent at Sri shukmani group of technology um LOVELY PROFESSIONAL UNIVERSITY
Java
ARRAYS & STRINGS
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
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
using the NetBeans Debugger
NetBeansDebuggerVideo1
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
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
Types of Array: There are two types of array.
• Single Dimensional Array
• Multidimensional Array-
• 2D array
• 3D array
• Jagged array
7
Single Dimensional Array
• The syntax for declaring and instantiating
an array:
There are two ways to declare an array,
type[] arrayName;
type arrayName[];
8
• 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
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
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
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
Some other methods:
• equals( arrayName1, arrayName2 )
• copyOf( arrayName, length )
• binarySearch( arrayName, value )
13
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
Jagged array
type[][] arrayName = new
type[rowCount][];
e.g:-int num[][]=new int[4][];
num[0]=new int[1];
num[1]=new int[2];
num[2]=new int[3];
num[3]=new int[4];
15
Enhanced for loop for 2D array
for (int[] num: arr)
{
for(int data: num)
{
System.out.println(data);
}
}
16
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
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
19
4 D Array
• Array of 3 D Array
int [][][][] num=new int[2][2][2][2];
Multi dimensional array means arrya of
arrays.
20
Collection in java
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
Collection
group of individual objects.
Student S1=new
Student() S1 S2
S3 S4
S5 S6
Collection framework
Several classes and interfaces which can be used
a group of objects.
Package: util
import java.util.*;
STRINGS IN JAVA
• 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)
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.
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.
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.
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.
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
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.
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”)
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)
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()
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.
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.
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.
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
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
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
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).
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:---
Memory Allocation in Java
The JVM divided the memory into following
sections.
• Heap
• Stack
• Code
• Static
• 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.
Methods in String class:
• Length(),
• charAt()
• Substring()
• Concat
• indexOf()
• equals()
• compareTo()
• trim()
• replace()
• toUpperCase()
• toLowerCase();
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.
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.
Concatenation()
String word1 = “re”, word2 = “think”; word3 = “ing”;
int num = 2;
• String result = word1.concat (word2);
//the same as word1 + word2 “rethink“
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
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
compareTo()
int diff = word1.compareTo(word2);
returns the “difference” word1 - word2
int diff = word1.compareToIgnoreCase(word2);
returns the “difference” word1 - word2,
case-blind
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
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
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“
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“
1 von 56

Más contenido relacionado

Was ist angesagt?

StringsStrings
Stringsnaslin prestilda
2.6K views30 Folien
Java string handlingJava string handling
Java string handlingSalman Khan
9.2K views25 Folien
Java String Java String
Java String SATYAM SHRIVASTAV
5K views28 Folien
Strings in JavaStrings in Java
Strings in JavaAbhilash Nair
20.9K views23 Folien

Was ist angesagt?(20)

String and string bufferString and string buffer
String and string buffer
kamal kotecha5.5K views
String handling session 5String handling session 5
String handling session 5
Raja Sekhar1.9K views
StringsStrings
Strings
naslin prestilda2.6K views
Java string handlingJava string handling
Java string handling
Salman Khan9.2K views
Java String Java String
Java String
SATYAM SHRIVASTAV5K views
Strings in JavaStrings in Java
Strings in Java
Abhilash Nair20.9K views
String javaString java
String java
774474853 views
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
SSN College of Engineering, Kalavakkam1.4K views
Chapter 7 StringChapter 7 String
Chapter 7 String
OUM SAOKOSAL1.9K views
Java   stringsJava   strings
Java strings
Mohammed Sikander1.1K views
Java StringJava String
Java String
Java2Blog502 views
What is String in Java?What is String in Java?
What is String in Java?
RAKESH P139 views
Fundamental classes in javaFundamental classes in java
Fundamental classes in java
Garuda Trainings4K views
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
Ravi Kant Sahu738 views
String handling(string class)String handling(string class)
String handling(string class)
Ravi Kant Sahu1.3K views
Wrapper classWrapper class
Wrapper class
kamal kotecha12K views
Autoboxing And Unboxing In JavaAutoboxing And Unboxing In Java
Autoboxing And Unboxing In Java
chathuranga kasun bamunusingha1.8K views

Similar a STRINGS IN JAVA(20)

collection framework.pptxcollection framework.pptx
collection framework.pptx
SoniaKapoor563 views
Advanced core javaAdvanced core java
Advanced core java
Rajeev Uppala2.6K views
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40
bhawna sharma139 views
Java collectionsJava collections
Java collections
Hamid Ghorbani308 views
Java  Collections Java  Collections
Java Collections
Kongu Engineering College, Perundurai, Erode843 views
L11 array listL11 array list
L11 array list
teach4uin3K views
Collection Framework-1.pptxCollection Framework-1.pptx
Collection Framework-1.pptx
SarthakSrivastava701 view
12_-_Collections_Framework12_-_Collections_Framework
12_-_Collections_Framework
Krishna Sujeer168 views
Collections TrainingCollections Training
Collections Training
Ramindu Deshapriya582 views
CollectionsCollections
Collections
sagsharma178 views
Array propertiesArray properties
Array properties
Shravan Sharma450 views
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
RatnaJava83 views
Collections frameworkCollections framework
Collections framework
Anand Buddarapu192 views
ArrayList.docxArrayList.docx
ArrayList.docx
veerendranath1213 views
Java utilJava util
Java util
Srikrishna k214 views

Más de LOVELY PROFESSIONAL UNIVERSITY(19)

Enumerations, structure and class IN SWIFTEnumerations, structure and class IN SWIFT
Enumerations, structure and class IN SWIFT
LOVELY PROFESSIONAL UNIVERSITY94 views
Dictionaries IN SWIFTDictionaries IN SWIFT
Dictionaries IN SWIFT
LOVELY PROFESSIONAL UNIVERSITY65 views
Control structures IN SWIFTControl structures IN SWIFT
Control structures IN SWIFT
LOVELY PROFESSIONAL UNIVERSITY89 views
Arrays and its properties IN SWIFTArrays and its properties IN SWIFT
Arrays and its properties IN SWIFT
LOVELY PROFESSIONAL UNIVERSITY61 views
Array and its functionsI SWIFTArray and its functionsI SWIFT
Array and its functionsI SWIFT
LOVELY PROFESSIONAL UNIVERSITY16 views
practice problems on array IN SWIFTpractice problems on array IN SWIFT
practice problems on array IN SWIFT
LOVELY PROFESSIONAL UNIVERSITY7 views
practice problems on array  IN SWIFTpractice problems on array  IN SWIFT
practice problems on array IN SWIFT
LOVELY PROFESSIONAL UNIVERSITY90 views
practice problems on array IN SWIFTpractice problems on array IN SWIFT
practice problems on array IN SWIFT
LOVELY PROFESSIONAL UNIVERSITY85 views
practice problems on functions IN SWIFTpractice problems on functions IN SWIFT
practice problems on functions IN SWIFT
LOVELY PROFESSIONAL UNIVERSITY288 views
10. funtions and closures IN SWIFT PROGRAMMING10. funtions and closures IN SWIFT PROGRAMMING
10. funtions and closures IN SWIFT PROGRAMMING
LOVELY PROFESSIONAL UNIVERSITY73 views
 Variables and data types IN SWIFT Variables and data types IN SWIFT
Variables and data types IN SWIFT
LOVELY PROFESSIONAL UNIVERSITY56 views
Soft skills. pptxSoft skills. pptx
Soft skills. pptx
LOVELY PROFESSIONAL UNIVERSITY56 views
JAVAJAVA
JAVA
LOVELY PROFESSIONAL UNIVERSITY31 views
Unit 5Unit 5
Unit 5
LOVELY PROFESSIONAL UNIVERSITY14 views
Unit 4Unit 4
Unit 4
LOVELY PROFESSIONAL UNIVERSITY23 views
Unit 3Unit 3
Unit 3
LOVELY PROFESSIONAL UNIVERSITY26 views
Unit 1Unit 1
Unit 1
LOVELY PROFESSIONAL UNIVERSITY40 views
COMPLETE CORE JAVACOMPLETE CORE JAVA
COMPLETE CORE JAVA
LOVELY PROFESSIONAL UNIVERSITY14 views
Data wrangling IN R LANGUAGEData wrangling IN R LANGUAGE
Data wrangling IN R LANGUAGE
LOVELY PROFESSIONAL UNIVERSITY55 views

Último(20)

SIMPLE PRESENT TENSE_new.pptxSIMPLE PRESENT TENSE_new.pptx
SIMPLE PRESENT TENSE_new.pptx
nisrinamadani2135 views
2022 CAPE Merit List 2023 2022 CAPE Merit List 2023
2022 CAPE Merit List 2023
Caribbean Examinations Council2.3K views
Industry4wrd.pptxIndustry4wrd.pptx
Industry4wrd.pptx
BC Chew144 views
ANATOMY AND PHYSIOLOGY UNIT 1 { PART-1}ANATOMY AND PHYSIOLOGY UNIT 1 { PART-1}
ANATOMY AND PHYSIOLOGY UNIT 1 { PART-1}
DR .PALLAVI PATHANIA102 views
Scope of Biochemistry.pptxScope of Biochemistry.pptx
Scope of Biochemistry.pptx
shoba shoba104 views
Narration lesson plan.docxNarration lesson plan.docx
Narration lesson plan.docx
Tariq KHAN84 views
Universe revised.pdfUniverse revised.pdf
Universe revised.pdf
DrHafizKosar79 views
STERILITY TEST.pptxSTERILITY TEST.pptx
STERILITY TEST.pptx
Anupkumar Sharma97 views
Class 10 English  lesson plansClass 10 English  lesson plans
Class 10 English lesson plans
Tariq KHAN149 views
Chemistry of sex hormones.pptxChemistry of sex hormones.pptx
Chemistry of sex hormones.pptx
RAJ K. MAURYA93 views
GSoC 2024GSoC 2024
GSoC 2024
DeveloperStudentClub1041 views
A Day At 07.45 Using A CodeA Day At 07.45 Using A Code
A Day At 07.45 Using A Code
Ashley Lott55 views
discussion post.pdfdiscussion post.pdf
discussion post.pdf
jessemercerail57 views
How to present dataHow to present data
How to present data
Pavel Šabatka41 views

STRINGS IN JAVA

  • 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
  • 4. using the NetBeans Debugger NetBeansDebuggerVideo1
  • 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
  • 15. Jagged array type[][] arrayName = new type[rowCount][]; e.g:-int num[][]=new int[4][]; num[0]=new int[1]; num[1]=new int[2]; num[2]=new int[3]; num[3]=new int[4]; 15
  • 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
  • 19. 19
  • 20. 4 D Array • Array of 3 D Array int [][][][] num=new int[2][2][2][2]; Multi dimensional array means arrya of arrays. 20
  • 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
  • 23. Collection group of individual objects. Student S1=new Student() S1 S2 S3 S4 S5 S6
  • 24. Collection framework Several classes and interfaces which can be used a group of objects. Package: util import java.util.*;
  • 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.
  • 46. Methods in String class: • Length(), • charAt() • Substring() • Concat • indexOf() • equals() • compareTo() • trim() • replace() • toUpperCase() • toLowerCase();
  • 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“