arrays and strings

Download Report

Transcript arrays and strings

ARRAYS AND
STRINGS
Array- a list of data items that all have the
same type and the same name
- can be created of any data type and
can have one or more dimensions
- a collection of data items that are of
the same data type where each item
can
be uniquely addressed
 index or subscript – an integer that is
contained within square brackets that
allows us to access each of the
elements in
an array
To declare an array, the following must be added:
declare a variable of the desired type
 allocate the memory that will hold the array, using
new, and assign it to the array variable

syntax:
type [] array_name;
e.g.
1. using primitive type
int result []; or
2. using class type
Student stud [];
int [] result;
or
Student [] stud;
When an array is declared, the declaration did not create any computer
memory addresses as yet. There is no array actually created. By declaring
the array, the array name is the reference that can be used to refer to the array.
Creating an Array
The keyword new is used when creating an array object
syntax:




array_name=new type[size];
array_name – an array variable that is a reference to the
array.
new - used to allocate memory to hold the array, that is, to
create an array object.
type – specifies the type of data being allocated.
size – specifies the number of elements in the array.
Example 1:
result = new int [5];
//creates an array of 5 integers and initializes all the elements to zero
Example 2:
stud = new Student [50];
//creates an array of 50 variables of type ‘Student’. But it does not create ‘Student’
objects.
Initializing an Array



numeric array - all elements are initialized to
zero.
character array – all elements are initialized to
‘\u0000’.
boolean array – all elements are initialized to
false.
Example:
int result[];
result=new int[3];
or
int result[]=new int[3];
result[0]=20;
result[1]=30;
result[2]=40;
Or by using array initialiser
- a list of comma-separated expressions
enclosed by curly brackets. The comma
separated
values of the array elements.
int [] result={20,30,40};
//there is no need to used the keyword ‘new’.
//the array will automatically be created large enough to store the
//number of elements specified in the array initializer
the
//creates a 1D array, initialize it and display its contents.
public class ArrayAssign {
public static void main(String []args) {
int[] num=new int[3];
num[0]=10;
num[1]=20;
num[2]=30;
System.out.println("The numbers are: ");
for(int i=0;i<num.length;i++){
System.out.println(num[i]);
}
}
}
//creates a 1D array using array initializer and display its contents.
public class ArrayInitialise {
public static void main(String []args) {
int[] num={11,22,33};
System.out.println("The numbers are: ");
for(int i=0;i<num.length;i++){
System.out.println(num[i]);
}
}
}
/*creates a 1D array, read data from the keyboard and displays the data
stored in the array.*/
import java.io.*;
public class ArrayEntry {
public static void main(String []args) throws Exception {
BufferedReader input=new BufferedReader(new
InputStreamReader(System.in));
int x,count;
String name[];
System.out.println("number of names to be entered: ");
x=Integer.parseInt(input.readLine());
name=new String[x];
//entering of the names
for( count=0;count<x;count++){
System.out.println("name["+count+"]: ");
name[count]=input.readLine();
}
//displaying of names entered
System.out.println("Names stored");
System.out.println("-------------");
for(count=0;count<name.length;++count){
System.out.println(name[count]);
}
}
}
Using an Array length
array length attribute is used to iterate on an array
- helps to indicate the number of elements in an
array
example:
int age={3,17,20};
for(int x=0;x<age.lenght;x++)
{
System.out.println(age[x]);
}
Multidimensional Arrays
Syntax:
type[][] array_name=new int [row][column];
Example:
int [][] marks = new int [2][3];
//creates an array named ‘marks’ that holds two
rows and three columns.
public class TwoDimensionalArray{
public static void main(String [] args ){
int [][] marks = {{99,88,77,66},
{11,22,33}};
System.out.println(" The marks stored in
element[0][2] is " + marks[0][2]);
}
}
Creating a String
String - a sequence of characters which is
enclosed within double quotation marks
- a special type classified as a reference
- class String is defined in java.lang.String
- keyword new and the String constructor
method is used to create a String object
There are different ways of creating a String :
 to create an empty String constructor
e.g. String name=new String();
//this is a default constructor, it creates a String object with no characters in it

to create a String initialized by an array of
characters as a parameter
e.g. char [] name={'M','A','R','Y'};
String myname=new String(name);
//to initialize ‘myname’ with the String “MARY”

to use a string literal to create a String object
e.g. String name="MARY";
The length() Method
length() method – to determine and returns the size of a String
e.g.
public class DemoLength{
public static void main(String [] args){
String name="Mary";
System.out.println(“Length of the name is " +
name.length());
}
}
String Concatenation
The process of joining two or more strings
together, producing a String object is called
String concatenation. We can also concatenate
strings with other data types.
 + operator
 concat() method
e.g. 1:
String msg1="Java";
String msg2="Programming";
System.out.println(msg1+msg2);
e.g. 2:
String msg1="Java";
String msg2=msg1 +"Programming";
System.out.println(msg2);
e.g. 3:
String msg="Java" + "Programming";
System.out.println(msg);
\
\
\
\
e.g. 4:
int total=10;
String msg="Total is" +total+
"numbers";
System.out.println(msg);
\
e.g. 5:
String msg="Total =" +2+3;
\
//this result will show Total = 23
\
\
\
\
\
\
System.out.println(msg);
e.g. 6:
String msg="Total is" +(2+3);
//this result will show Total = 5
System.out.println(msg);
e.g. using concat() method
String msg1="Java";
String msg2="Programming";
System.out.println(msg1.concat(msg2));
Comparing Strings
 equals() method
 equalsIgnoreCase()
- both methods allow us to evaluate the contents
of two String objects to determine if they are
equivalent
 == operator – comparing the memory addresses and
not their values
e.g. 1:
String msg1="Hello";
String msg2="Hello";
if(msg1.equals(msg2))
System.out.println("Both strings are the same");
e.g. 2:
String msg1="Hello";
String msg2="HeLLo";
if(msg1.equalsIgnoreCase(msg2))
System.out.println("Strings are equal ignoring the case");
//this method is the same as equals() except the case is ignored