0% found this document useful (0 votes)
1 views10 pages

7 - Week Java Notes 20cs43p

The document provides an overview of Java arrays, detailing their characteristics, types (single and multidimensional), and methods for creation and manipulation. It also covers Java strings, including how to create string objects, string methods, and the StringBuffer class for mutable strings. Examples are provided to illustrate array operations, string manipulations, and the use of StringBuffer.

Uploaded by

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

7 - Week Java Notes 20cs43p

The document provides an overview of Java arrays, detailing their characteristics, types (single and multidimensional), and methods for creation and manipulation. It also covers Java strings, including how to create string objects, string methods, and the StringBuffer class for mutable strings. Examples are provided to illustrate array operations, string manipulations, and the use of StringBuffer.

Uploaded by

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

Object Oriented Programming and Design with Java 20CS43P

Week – 07

Java Arrays
An array is a collection of similar type of elements which has contiguous memory location.
Java array is an object which contains elements of a similar data type ( homogeneous). Additionally,
the elements of an array are stored in a contiguous memory location. It is a data structure where we
store similar elements (homogeneous). We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is
stored on 1st index and so on.

Features

Here are the basic features of a Java array:

• The array must be constructed. The size of the array is fixed.


• The length property holds the value of the size of the array.
• The array can only hold variables of the same type. So you can have an array of ints, or an
array of doubles, or an array of Strings, or an array of objects. But you cannot have an array of
doubles and ints, or any mixture of types.
• Each element of an array has in index. The index is used to access that individual element. The
index always starts with zero.

Types of Array in java


There are two types of arrays.
• Single Dimensional Array
• Multidimensional Array

Single dimensional array − A single dimensional array of Java is a normal array where; the array
contains sequential elements (of same type) –

Syntax: The general form of a one-dimensional array declaration is

COMPUTER SCIENCE & ENGG ARUNA N- LECTURER/CS


Object Oriented Programming and Design with Java 20CS43P

An array declaration has two components: the type and the name. type declares the element
type of the array. The element type determines the data type of each element that comprises the
array.
int[] myArray; or int myArray[];
// declaring and initializing 1D array
int[] myArray = {10, 20, 30, 40}

Array creation with new operator

1D array also known as a linear array, the elements are stored in a single row. For example:

In this example, we have an array of five elements. They are stored in a single line or adjacent memory
locations.
int intArray[]; //declaring array
intArray = new int[20]; // allocating memory to array OR
int[] intArray = new int[20]; // combining both statements in one
In a situation where the size of the array and variables of the array are already known, array literals can
be used.
Obtaining an array is a two-step process. First, you must declare a variable of the desired array type.
Second, you must allocate the memory to hold the array, using new, and assign it to the array variable.
Thus, in Java, all arrays are dynamically allocated.

Multi-dimensional array − A multi-dimensional array in Java is an array of arrays. A two-


dimensional array is an array of one-dimensional arrays and a three-dimensional array is an array of
two-dimensional arrays.
Syntax:
type[][] var-name (or) type
[][]var-name; (or) type
var-name[][]; (or) type
[]var-name[]; int[][]
intArray; // 2D
ARRAY OR Matrix

COMPUTER SCIENCE & ENGG ARUNA N- LECTURER/CS


Object Oriented Programming and Design with Java 20CS43P

int[][][]
intArray; //3D
ARRAY
// declaring and initializing 2D array
int arr[][] = { {2,7,9},{3,6,1},{7,4,2}
};

Array creation with new operator

Two-dimensional arrays store the data in rows and columns:


In this, the array has two rows and five columns. The index starts from 0,0 in the left-upper corner to
1,4 in the right lower corner.

Working with arrays

Example 1: /* Java program to illustrate creating an array of integers,


puts some values in the array, and prints each value to standard output.
*/
class ArrayDemo1
{
public static void main (String[] args)
{
// declares an Array of integers.
int[] arr;
// allocating memory for 5 integers.
arr = new int[5];
// initialize the first elements of the array
arr[0] = 10;
// initialize the second elements of the array
arr[1] = 20; //so on... arr[2] = 30;
arr[3] = 40; arr[4] = 50;

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i + " : "+ arr[i]);
}
}
Example 2: //Declaring and initializing of 1D arrays
class ArrayDemo2
{

COMPUTER SCIENCE & ENGG ARUNA N- LECTURER/CS


Object Oriented Programming and Design with Java 20CS43P

public static void main (String[] args)


{
// declares & initializes an Array of integers.
int[] arr= {10,20,30,40,50};

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i + " : "+ arr[i]);
}
}

Example 3: //Java program to illustrate creating an array of objects


class Student
{
public int roll_no;
public String name;
Student(int roll_no, String name)
{
this.roll_no = roll_no;
this.name = name;
}
}

// Elements of the array are objects of a class


Student. public class ArrayObject
{
public static void main (String[] args)
{
// declares an Array of integers.
Student[] arr;

// allocating memory for 5 objects of type


Student. arr = new Student[5];

// initialize the first elements of the array


arr[0] = new Student(1,"Afsha");

// initialize the second elements of the array


arr[1] = new Student(2,"Akshatha");

// so on... arr[2] =
new Student(3,"Arun"); arr[3]
= new Student(4,"Aryan");
arr[4] = new Student(5,"Badhri");

// accessing the elements of the specified


array for (int i = 0; i < arr.length; i++)
System.out.println("Element at " + i +
" : " + arr[i].roll_no +" "+
arr[i].name); }
}

COMPUTER SCIENCE & ENGG ARUNA N- LECTURER/CS


Object Oriented Programming and Design with Java 20CS43P

Example 4: Linear Search / sequential Search using input from keyboard


import java.util.Scanner;
public class LinearSearch
{ public static int LSearch(int[] arr, int
key)
{ for(int
i=0;i<arr.length;i++)
{
if(arr[i] == key){
return i;
}
}
return -1;
}
public static void main(String a[])
{
Scanner in = new
Scanner(System.in);
System.out.println("Array Size: ");
int input = in.nextInt(); int
a1[]=new int[input];
//int[] a1= {10,20,30,50,70,90};
System.out.println("enter array elements: ");
for(int i=0;i<input;i++)
{
a1[i] = in.nextInt();
}
System.out.println("enter key
elements: "); int key = in.nextInt();
int v= LSearch(a1, key);
if(v>=0)
System.out.println(key+" is found at index: "+v);
else
System.out.println("key not found");

}
}

Example 4: Addition of 2 Matrices using 2D array


public class Excersice5
{
public static void main(String args[])
{ int a[][]={{1,3,4},{2,4,3},{3,4,5}}; //creating
two matrices int b[][]={{1,3,4},{2,4,3},{1,2,4}};

int c[][]=new int[3][3]; //adding and printing addition of 2 matrices


for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+"\t");
}
System.out.println();//new line
}
}

COMPUTER SCIENCE & ENGG ARUNA N- LECTURER/CS


Object Oriented Programming and Design with Java 20CS43P

}
Java Strings
Generally, 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.

How to create a string object?

There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal

Java String literal is created by using double quotes. For Example:

String s="welcome";

Each time you create a string literal, the JVM checks the "string constant pool" first. If the string
already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the
pool, a new string instance is created and placed in the pool. For example:

String s1="Welcome";

String s2="Welcome";//It doesn't create a new instance

In the above example, only one object will be created. Firstly, JVM will not find any string object with
the value "Welcome" in string constant pool that is why it will create a new object. After that it will
find the string with the value "Welcome" in the pool, it will not create a new object but will return the
reference to the same instance.

2) By new keyword

1. String s=new String("Welcome");//creates two objects and one reference


variable

COMPUTER SCIENCE & ENGG ARUNA N- LECTURER/CS


Object Oriented Programming and Design with Java 20CS43P

In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the object in a heap
(non-pool).

Java String class methods

No. Method Description

1 char charAt(int index) It returns char value for the particular index

int length() It returns string length


2

String substring(int beginIndex) It returns substring for given begin index.


3

4 String substring(int beginIndex, int endIndex)


It returns substring for given begin index
and end index.

5 boolean equals(Object another) It checks the equality of string with the


given object.

6 boolean isEmpty() It checks if string is empty.


String concat(String str) It concatenates the specified string.
7

8 String replace(char old, char new) It replaces all occurrences of the specified
char value.

9 String toLowerCase() It returns a string in lowercase.

10 String toUpperCase() It returns a string in uppercase.

Example : Demonstration of String Class and its Methods.

class StringDemo
{
public static void main(String args[])
{
System.out.println("-------------STRING DEMO-------");
String s1=new String("Sjpcs");
String s2="sjp ";
//String s3=new String("");
String s3="";
System.out.println("the string s1="+s1);
System.out.println("the string s2="+s2);
System.out.println("Char at ="+s2.charAt(2));

COMPUTER SCIENCE & ENGG ARUNA N- LECTURER/CS


Object Oriented Programming and Design with Java 20CS43P

System.out.println("the length of the string s1="+s1.length());


System.out.println("SubString Begin index ="+s1.substring(1));
System.out.println("SubString Begin & end index ="+s1.substring(1,4));
System.out.println("s1 equals s2 is="+s1.equals(s2));
System.out.println("check isempty="+s3.isEmpty());
System.out.println("s1 concatination s2 is="+s1.concat(s2));
System.out.println("the length of the string s .length())
s1="+ 1 ;
System.out.println("Replace="+s1.replace("S", "A"));
System.out.println("Lower case is="+s1.toLowerCase());
System.out.println("Upper case is="+s1.toUpperCase());
System.out.println("s1 equals ignore case s2="+s1.equalsIgnoreCase(s2));
}

Output:

-------------STRING
DEMO------- the string
s1=Sjpcs the string s2=sjp
Char at =p
the length of the string s1=5
SubString Begin index =jpcs
SubString Begin & end index
=jpc s1 equals s2 is=false
check isempty=true
s1 concatination s2 is=Sjpcssjp
the length of the string s1=5
Replace=Ajpcs
Upper case is=SJPCS
Lower case is=sjpcs
s1 equals ignore case s2=false

StringBuffer class in Java


StringBuffer is a peer class of String that provides much of the functionality of strings. The string
represents fixed-length, immutable character sequences while StringBuffer represents growable and
writable character sequences. StringBuffer may have characters and substrings inserted in the middle
or appended to the end. It will automatically grow to make room for such additions and often has more
characters preallocated than are actually needed, to allow room for growth.

Constructors of StringBuffer class

1. StringBuffer(): It reserves room for 16 characters without reallocation

StringBuffer s = new StringBuffer();

2. StringBuffer( int size): It accepts an integer argument that explicitly sets the size of the buffer.

StringBuffer s = new StringBuffer(20);

3. StringBuffer(String str): It accepts a string argument that sets the initial contents of the
StringBuffer object and reserves room for 16 more characters without reallocation.

COMPUTER SCIENCE & ENGG ARUNA N- LECTURER/CS


Object Oriented Programming and Design with Java 20CS43P

StringBuffer s = new StringBuffer("4thSemCS");

Methods Action Performed

append() Used to add text at the end of the existing text.

length() The length of a StringBuffer can be found by the length( ) method capacity()

the total allocated capacity can be found by the capacity( ) method

setCharAt(pos,string) Sets the Char at the specified position insert() Inserts text

at the specified index position

Example : Demonstration of String Buffer Class and its Methods.

class StringBufferDemo
{
public static void main(String args[])
{
System.out.println("-------------STRING DEMO-------");
StringBuffer str=new StringBuffer("Object Language");
System.out.println("original string="+str);
System.out.println("Length:"+str.length());
System.out.println("Capacity:"+str.capacity());
int pos=str.indexOf(" Language");
str.insert(pos," Oriented");
System.out.println("modified string:"+str);
str.setCharAt(6,'-');
System.out.println("String now:"+str);

str.append(" imporve security");


System.out.println("appended string:"+str);
System.out.println("Length:"+str.length());

}
}

Output:

-------------STRING DEMO-------
original string=Object Language
Length:15
Capacity:31
modified string:Object Oriented Language
String now:Object-Oriented Language
appended string:Object-Oriented Language improve security
Length:41

COMPUTER SCIENCE & ENGG ARUNA N- LECTURER/CS


Object Oriented Programming and Design with Java 20CS43P

COMPUTER SCIENCE & ENGG ARUNA N- LECTURER/CS

You might also like