0% found this document useful (0 votes)
47 views68 pages

5-Arrays, 1 D and Multi-Dimensional, Enhanced For Loop, Strings, Wrapper Classes-14!08!2023

Uploaded by

msd77sy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views68 pages

5-Arrays, 1 D and Multi-Dimensional, Enhanced For Loop, Strings, Wrapper Classes-14!08!2023

Uploaded by

msd77sy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

Module 2

Looping Constructs and Array

Control and looping constructs Arrays


one dimensional and multi-dimensional-
enhanced for loop-Strings-Wrapper Classes.
Arrays
• The array – a data structure
• stores a fixed-size sequential collection of
elements of the same type.
• elements of an array are stored in a contiguous
memory location.
• as a collection of variables of the same type.
• an object which contains elements of a similar
data type
Declaring Array
Syntax
dataType[] arrayRefVar; // preferred way
dataType arrayRefVar[]; // works but not preferred way
Eg. double[] myList;
Creating Array
Using new operator.
Syntax:
arrayRefVar = new dataType[arraySize];
dataType[] arrayRefVar = new dataType[arraySize];
dataType[] arrayRefVar = {value0, value1, ..., valuek};
Eg. double[] myList = new double[10];
Creating Array
Array Representation
Array Length

• built-in length property helps to determine the size of


any array.
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
Processing Array // Finding the largest element
double max = myList[0];
public class TestArray {
for (int i = 1; i < myList.length; i++)
public static void main(String[] args)
{
{
if (myList[i] > max)
double[] myList = {1.9, 2.9, 3.4, 3.5};
max = myList[i];
for (int i = 0; i < myList.length; i++)
}
{
System.out.println("Max is " +
System.out.println(myList[i] + " ");
max);
}
}
double total = 0;
}
for (int i = 0; i < myList.length; i++) Ouput:
{ 1.9
total += myList[i]; 2.9
} 3.4
System.out.println("Total is " + total); 3.5
Total is 11.7
Max is 3.5
Passing Arrays to Methods

void printArray(int[] array)


{
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i] + " ");
}
}
Returning an Array from a Method

int[] reverse(int[] list)


{
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1; i < list.length; i++, j--)
{
result[j] = list[i];
}
return result;
}
Types of Array in java

There are two types of array.


• Single Dimensional Array
• Multidimensional Array
Multidimensional Arrays

• A multidimensional array is an array of arrays. That is,


each element of a multidimensional array is an array
itself.
For example,
double[][] matrix = {{1.2, 4.3, 4.0}, {4.1, -1.1} };
2-D Array
int[][] a = new int[3][4];
2-D Initialization
int[][] a = { {1, 2, 3}, {4, 5, 6, 9}, {7} };
3-D Array

String[][][] data = new String[3][4][2];


• each row of the multidimensional array in Java
can be of different lengths.
int[][][] test = { { {1, -2, 3}, {2, 3, 4} }, { {-4, -5, 6,
9}, {1}, {2, 3} } };
The Arrays Class

• java.util.Arrays class
• contains static methods for sorting and searching arrays, comparing
arrays, and filling array elements.
Copying Arrays using System.arraycopy

• The System class has an arraycopy method to copy


data from one array into another
public static void arraycopy(Object src, int srcPos, Object
dest, int destPos, int length)
• The two Object arguments specify the array to
copy from and the array to copy to.
• The three int arguments specify the starting position in
the source array, the starting position in the destination
array, and the number of array elements to copy.
Example
class ArrayCopyDemo
{
public static void main(String[] args)
{
String[] array1= { "Affogato", "Americano", "Cappuccino", "Corretto",
"Cortado", "Doppio", "Espresso", "Frappucino", "Freddo", "Lungo",
"Macchiato", "Marocchino", "Ristretto" };
String[] array2= new String[7];
System.arraycopy(array1, 2, array2, 0, 7);
for (String display : array2)
{
System.out.print(display+ " ");
}
}}
Copying Arrays using java.util.Arrays

• copyOfRange method of the java.util.Arrays class


• The difference is that using the copyOfRange method
does not require to create the destination array before
calling the method, because the destination array is
returned by the method:
Array2=java.util.Arrays.copyOfRange(Array1, 2, 9);
Array1-source array
2 – start position
9- end position
Prints elements from 2 to 8 .
public static int binarySearch(Object[] a, Object
key)

• Searches the specified array of Object ( Byte, Int , double,


etc.) for the specified value using the binary search
algorithm.
• The array must be sorted prior to making this call.
• This returns index of the search key, if it is contained in
the list; otherwise, it returns ( – (insertion point + 1)).
public static boolean equals(long[] a, long[] a2)

• Returns true if the two specified arrays of longs are equal


to one another.
• Two arrays are considered equal if both arrays contain
the same number of elements, and all corresponding
pairs of elements in the two arrays are equal.
• This returns true if the two arrays are equal. Same
method could be used by all other primitive data types
(Byte, short, Int, etc.)
public static void fill(int[] a, int val)

• Assigns the specified int value to each element of


the specified array of ints.
• The same method could be used by all other
primitive data types (Byte, short, Int, etc.)
public static void sort(Object[] a)

• Sorts the specified array of objects into an


ascending order, according to the natural
ordering of its elements.
• The same method could be used by all other
primitive data types ( Byte, short, Int, etc.)
Command Line Arguments

• The java command-line argument is an argument i.e. passed at the


time of running the java program.
• The arguments passed from the console can be received in the java
program and it can be used as an input.
• Command line arguments are received as String input
Command Line Arguments
public class A{
public static void main(String args[]){
OUTPUT:
for(int i=0;i<args.length;i++)
hello
System.out.println(args[i]); I
am
} VIT
Student
}
• compile by > javac A.java
• run by > java A hello I am VIT
student
String
• String represents a sequence of characters
• Easiest way to represent sequence of character is char
array
char sample[]=new char[10]; but doesn’t support string
operations.
In JAVA
• Strings are class objects implemented using two classes
o String
o StringBuffer

• Not a char array. It is not null terminated.


String and Character Processing Classes

o Class java.lang.String
o Class java.lang.StringBuffer
o Class java.lang.Character
o Class java.util.StringTokenizer
All classes has its own constructors and
methods
Declaration and Definition of Strings in Java
• Normally Objects in Java is created using new.
• So string is created using object of String class.
String first= new String(“ Suvilin”);
Or
String first;
first = new String(“Suvilin”);
Or
String first=“Suvilin”;
Strings are immutable. For mutable we use StringBuffer
class.
Reading String Input

• Method 1
BufferedReader br= new BufferedReader(new
InputStreamReader(System.in));
String my= br.readLine();
• Method 2
Scanner sc=new Scanner(System.in);
String my=sc.nextLine();
String you=sc.next();
Java String Pool

• In Java String create reference to the objects.


• Java String pool refers to collection of Strings which are
stored in heap memory.
• In this, whenever a new object is created, String pool
first checks whether the object is already present in the
pool or not.
• If it is present, then same reference is returned to the
variable else new object will be created in the String pool
and the respective reference will be returned.
Java String Pool or Intern Pool or Constant pool
Java String Pool & Heap
Java String Pool & Heap
String Constructor

• Class String
o Provides nine constructors
o Null constructor String() has no characters and a
length of zero
o String (array, offset, number of
characters)
String Constructor
public class StringConstructors {
public static void main( String args[] )
{
char charArray[] = { 'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y' };
byte byteArray[] = { ( byte ) 'n', ( byte ) 'e', ( byte ) 'w', ( byte ) ' ', (
byte ) 'y', ( byte ) 'e', ( byte ) 'a', ( byte ) 'r' };
String s = new String( "hello" );
// use String constructors
String s1 = new String( ); //String default constructor instantiates empty string
String Constructor
String s2 = new String( s );
String s3 = new String( charArray );
String s4 = new String( charArray, 6, 3 );
String s5 = new String( byteArray, 4, 4 );
String s6 = new String( byteArray );
// append Strings to output
String output = "s1 = " + s1 + "\ns2 = " + s2 + "\ns3 = " + s3 + "\ns4 =
" + s4 + "\ns5 = " + s5 + "\ns6 = " + s6;
}
}
String Methods length, charAt and getChars

• Method length
o Determine String length
• Like arrays, Strings always “know” their size by using length
method(not instance variable).
• s1.length()
• Method charAt
o Get character at specific location in String
o s1.charAt( offset )
• Method getChars
o Get entire set of characters in String
o s1.getChars( start, first after, charArray, start );
String Methods length, charAt and getChars

public class StringMiscellaneous {


public static void main( String args[] )
{
String s1 = "hello there";
char charArray[] = new char[ 5 ];
String output = "s1: " + s1;
// test length method
output += "\nLength of s1: " + s1.length();
// loop through characters in s1 and display reversed
output += "\nThe string reversed is: ";
String Methods length, charAt and getChars

for ( int count = s1.length() - 1; count >= 0; count-- )


output += s1.charAt( count ) + " ";
s1.getChars( 0, 5, charArray, 0 );
output += "\nThe character array is: ";
for ( int count = 0; count < charArray.length; count++ )
output += charArray[ count ];
System.out.println(output);
}
}
Miscellaneous String Methods

• Miscellaneous String methods


o Return modified copies of String
• replace(char,char)
• toUpperCase()
• toLowerCase()
• trim() (remove all white space from beginning and end of
string)
o Return character array
• toCharArray()
String Methods
1 char charAt(int index)
Returns the character at the specified index.

2 int compareTo(Object o)
Compares this String to another Object.

3 int compareTo(String anotherString)


Compares two strings lexicographically.

4 int compareToIgnoreCase(String str)


Compares two strings lexicographically, ignoring case differences.

5 String concat(String str)


Concatenates the specified string to the end of this string.
String Methods
6 boolean contentEquals(StringBuffer sb)
Returns true if and only if this String represents the same sequence of
characters as the specified StringBuffer.
7 static String copyValueOf(char[] data)
Returns a String that represents the character sequence in the array
specified.
8 static String copyValueOf(char[] data, int offset, int count)
Returns a String that represents the character sequence in the array
specified.
9 boolean endsWith(String suffix)
Tests if this string ends with the specified suffix.

10 boolean equals(Object anObject)


Compares this string to the specified object.
String Methods
11 boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
12 byte[] getBytes()
Encodes this String into a sequence of bytes using the platform's default
charset, storing the result into a new byte array.
13 byte[] getBytes(String charsetName)
Encodes this String into a sequence of bytes using the named charset, storing
the result into a new byte array.
14 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
15 int hashCode()
Returns a hash code for this string.
String Methods
16 int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified
character.
17 int indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified
character, starting the search at the specified index.
18 int indexOf(String str)
Returns the index within this string of the first occurrence of the specified
substring.
19 int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified
substring, starting at the specified index.
20 String intern()
Returns a canonical representation for the string object.
String

21 int lastIndexOf(int ch)


Returns the index within this string of the last occurrence of the specified character.

22 int lastIndexOf(int ch, int fromIndex)


Returns the index within this string of the last occurrence of the specified character, searching
backward starting at the specified index.

23 int lastIndexOf(String str)


Returns the index within this string of the rightmost occurrence of the specified substring.

24 int lastIndexOf(String str, int fromIndex)


Returns the index within this string of the last occurrence of the specified substring, searching
backward starting at the specified index.

25 int length()
Returns the length of this string.
String Methods

26 boolean matches(String regex)


Tells whether or not this string matches the given regular expression.
27 boolean regionMatches(boolean ignoreCase, int toffset, String
other, int ooffset, int len)
Tests if two string regions are equal.
28 boolean regionMatches(int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
29 String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in
this string with newChar.
30 String replaceAll(String regex, String replacement
Replaces each substring of this string that matches the given regular
expression with the given replacement.
String Methods

31 String replaceFirst(String regex, String replacement)


Replaces the first substring of this string that matches the given regular
expression with the given replacement.
32 String[] split(String regex)
Splits this string around matches of the given regular expression.
33 String[] split(String regex, int limit)
Splits this string around matches of the given regular expression.
34 boolean startsWith(String prefix)
Tests if this string starts with the specified prefix.
35 boolean startsWith(String prefix, int toffset)
Tests if this string starts with the specified prefix beginning a specified
index.
String Methods
36 CharSequence subSequence(int beginIndex, int endIndex)
Returns a new character sequence that is a subsequence of this
sequence.
37 String substring(int beginIndex)
Returns a new string that is a substring of this string.
38 String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string.
39 char[] toCharArray()
Converts this string to a new character array.
40 String toLowerCase()
Converts all of the characters in this String to lower case using the
rules of the default locale.
String

41 String toLowerCase(Locale locale)


Converts all of the characters in this String to lower case using the rules of the given Locale.

42 String toString()
This object (which is already a string!) is itself returned.

43 String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.

44 String toUpperCase(Locale locale)


Converts all of the characters in this String to upper case using the rules of the given Locale.

45 String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.

46 static String valueOf(primitive data type x)


Returns the string representation of the passed data type argument.
Wrapper classes in Java
• The wrapper class in Java provides the mechanism to
convert primitive into object and object into primitive.
Primitive Type Wrapper class

boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Need of Wrapper Classes

• They convert primitive data types into objects. Objects are


needed if we wish to modify the arguments passed into a
method (because primitive types are passed by value).
• The classes in java.util package handles only objects and
hence wrapper classes help in this case also.
• Data structures in the Collection framework, such
as ArrayList and Vector, store only objects (reference types)
and not primitive types.
• An object is needed to support synchronization in
multithreading.
Autoboxing and Unboxing

• Autoboxing: Automatic conversion of primitive types to the object


of their corresponding wrapper classes is known as autoboxing. For
example – conversion of int to Integer, long to Long, double to
Double etc.
• Unboxing: It is just the reverse process of autoboxing.
Automatically converting an object of a wrapper class to its
corresponding primitive type is known as unboxing. For example –
conversion of Integer to int, Long to long, Double to double, etc.
Primitive Types to Wrapper Objects - boxing

class Main {
if(aObj instanceof Integer) {
public static void main(String[]
args) {
System.out.println("An
// create primitive types object of Integer is created.");
int a = 5; }
double b = 5.65;
//converts into wrapper objects
if(bObj instanceof Double) {
Integer aObj = Integer.valueOf(a);
Double bObj = Double.valueOf(b);
System.out.println("An
object of Double is created.");
}
}
Wrapper Objects into Primitive Types-Unboxing
class Main {
public static void main(String[] args) {
// creates objects of wrapper class
Integer aObj = Integer.valueOf(23);
Double bObj = Double.valueOf(5.55);
// converts into primitive types
int a = aObj.intValue();
double b = bObj.doubleValue();
System.out.println("The value of a: " + a);
System.out.println("The value of b: " + b); }}

You might also like