YPCC ICSE 11th String Handling&Array
YPCC ICSE 11th String Handling&Array
Blue-J
FEATURES:
✓ Well Planned Notes
✓ Mini Test Papers
ISC Class – 11th ✓ Smart Practice Notes
Computer Science (JAVA) ✓ Tricky Worksheets
✓ Group Classes with
Personal Attention
https://www.youtube.com/c/YPComputerClasses ✓ One to One Classes
https://www.instagram.com/yogesh.verma27/ ✓ YT Videos for Revision
✓ Sharing Student’s Progress
https://www.facebook.com/yogesh.verma.79219 with Parents
https://www.YPComputerClasses.in/
STRINGS IN JAVA
String initialization H e l l o J a v a .
str =
String str = "Hello Java.";
0 1 2 3 4 5 6 7 8 9 10
Character initialization
char ch = ‘A’; index / subscript number
It is always starts from zero (0)
Character String
A character is a single alphabet, a digit or a single String is a set of characters in java.
special symbol. It is primitive datatype. It is non-primitive datatype.
It must have only one character. It encloses within single It encloses within double quotes.
inverted quotes.
It has a fixed size of 2 bytes. Size of string is not fixed.
Eg : Characters → 'A' , 'i' , '5' , '=' , ‘$‘, etc. Eg: Strings → “Hello Java.”, “computer1”, etc.
String & character input using scanner String & character input using BufferedReader
4
Methods / Functions
Exercise: Outputs
Eg: → boolean b; Outputs
boolean b;
b = Character.isLetter(‘y’); char ch1 = ‘*’, ch2 = ‘D’ ;
System.out.print(b); b = Character.isLetter(ch1);
System.out.print(b);
b = Character.isLetter(‘5’);
System.out.print(b); b = Character.isLetter(ch2);
System.out.print(b);
Argument
Wrapper Class Method Name
Return Type
character Questions.
Q1→Character conversion into Opposite Case. Q2→WAP to input a character and check it is symbol or not.
8
8. String valueOf(all num type) int a=10; String s = String.valueOf(a); //s = “10”
String Methods
String Methods
11
SYNTAX OF FUNCTION EXAMPLE
boolean b; String s1 = “Computer”, s2 = “Comp”;
17. boolean startsWith(String s)
b = s1.startsWith(s2); sop(b); // b = true
boolean b; String s1 = “Computer”, s2 = “ter”;
18. boolean endsWith(String s)
b = s1.endsWith(s2); sop(b); // b = true
Q1 → WAP to input two strings and concatenate it in to third string without using function and with using function.
Q2 → WAP to input two strings and concatenate second string at the end of first string.
StringBuffer
Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer class in Java is the same as
12 String class except it is mutable i.e. it can be changed.
We declare an object as a StringBuffer type. It creates space in the memory, called Buffer, to contain a String.
Syntax to create object of StringBuffer class
StringBuffer objectname = new StringBuffer();
Eg1:
StringBuffer sb1 = new StringBuffer(); // It allocates an empty space in the memory to store a string.
Eg2:
StringBuffer sb2 = new StringBuffer(“YP Computer”); // It allocates memory for variable sb2 and store YP Computer in it.
Eg3:
StringBuffer sb2 = new StringBuffer(25); // It allocates memory space for a string uptp 25 characters.
StringBuffer Functions
append()
13 It is used to add a string at the end of another string.
Syntax: StringBuffer object1.append(StringBuffer object2);
Eg: StringBuffer sb1 = new StringBuffer(“YP”);
StringBuffer sb2 = new StringBuffer(“Computer”);
sb1.append(sb2);
System.out.print(sb1); //YPComputer
setCharAt()
It is used to replace a character with another character at any specified index.
Syntax: StringBuffer object1.setCharAt(Index, Character);
Eg: StringBuffer sb1 = new StringBuffer(“YP Domputer”);
sb1.setCharAt(3, ‘C’);
System.out.print(sb1); //YP Computer
insert()
It is used to insert a string at a specified index of another string.
Syntax: StringBuffer object1.insert(index, StringBuffer object2);
Eg: StringBuffer sb1 = new StringBuffer(“YP Computer pune”);
StringBuffer sb2 = new StringBuffer(“ in”);
sb1.insert(11, sb2);
System.out.print(sb1); //YP Computer in pune
StringBuffer Functions
delete()
14 It is used to delete the characters from one index to another index in a given string..
Syntax: StringBuffer object1.delete(index1, index2);
Eg: StringBuffer sb1 = new StringBuffer(“YP Computer in pune”);
sb1.delete(3, 11); // index1 is inclusive but index2 is exclusive) when it deletes characters.
System.out.print(sb1); //YP in pune
setLength()
It is used to set the length of a string buffer variable up to specified range. If the string has more than specified length, then
the characters exceeding the length are truncated. In case the length of the string is less than the specified range, then it will
store “\u000” characters in the empty space.
Syntax: StringBuffer object1.setLength(Number of characters);
Eg: StringBuffer sb1 = new StringBuffer(“YP Computer in pune”);
sb1.setLength(11);
System.out.print(sb1); //YP Computer
reverse()
It is used to reverse the character of a given string.
Syntax: StringBuffer object1.reverse();
Eg: StringBuffer sb1 = new StringBuffer(“computer”);
sb1.reverse();
System.out.print(sb1); //retupmoc
StringBuffer Functions
capacity()
15 It is used to represent the buffer capacity of the StringBuffer. It returns the maximum number of characters that can be
entered in the assigned string buffer object. By default, the buffer object gets a storage capacity of 16 characters.
Syntax: int StringBuffer object1.capacity();
Eg: StringBuffer sb1 = new StringBuffer();
StringBuffer sb2 = new StringBuffer(25);
StringBuffer sb3 = new StringBuffer(“Computer”);
int c1, c2, c3;
c1 = sb1.capacity(); //16
c2 = sb2.capacity(); //25
c3 = sb3.capacity(); //24 (16+8)
StringBuffer
Other examples →
16
18
Q1 → WAP to input a string and find out its length and print all characters in vertical order and also print their ASCII values
of every character.
Q2 → WAP to input a string and reverse it in another string. Eg. s=“abc”; rev=“cba”;
Q3 → WAP to input a string and check whether it is palindrome string or not.
Q4 → WAP to input two strings and compare these two strings. If both strings are same then print strings are equals
otherwise print Strings are unequal.
Q5 → Write a program in Java to accept a string in lower case and change the first letter of every word to upper case.
Display the new string.
Sample input: we are in cyber world
Sample output: We Are In Cyber World
Q6 → Write a program to accept a sentence and print only the first letter of each word of the sentence in capital letters
separated by a full stop.
Example : INPUT SENTENCE : “This is a cat” OUTPUT : T.I.A.C.
Q6→ Write a program to accept a sentence and print only the first letter of each word of the sentence in capital
19 letters separated by a full stop. Example: INPUT SENTENCE : “This is a cat” OUTPUT : T.I.A.C.
import java.util.Scanner;
public class GetChars String Programs – based on chars
{
public static void main() Q7 → Special words are those words which starts and ends with
{ the same letter. Examples: EXISTENCE, COMIC, WINDOW
Scanner sc = new Scanner (System.in); Palindrome words are those words which read the same from left
String str; to right and vice-versa.
int i, len; Examples: MALAYALAM, MADAM, LEVEL, ROTATOR, CIVIC
char chr; All palindromes are special words, but all special words are not
System.out.println("Enter a String "); palindromes.
str = sc.nextLine(); Write a program to accept a word check and print whether the
len = str.length(); word is a palindrome or only special word.
str = “ ” + str;
for( i = 0; i < len; i++) Q8→ Write a program in java to accept a string and change the
{ case of each character of the string and display the new string.
chr = str.charAt(i); Sample input : WelComE TO School
if( chr == ‘ ’ ) Output : wELcOMe to sCHOOL
{
chr = str.charAt(i+1);
System.out.println(Character.toUpperCase(chr)+“.”);
}
}
}
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→19
JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science
Q9→
20 a) Write a program to accept a String. Convert the string to Uppercase. Count and output the number of double letter
sequences that exist in the string.
Sample input : “SHE WAS FEEDING THE LITTLE RABBIT WITH AN APPLE”
Sample Output : 4
b) Write a program to accept a String and convert its into its Piglatin form.To translate word into a Piglatin word, convert
the word into Uppercase and then place the first vowel of the original word as the start of the new word along with the
remaining alphabets. The alphabets present before the vowel being shifted towards the end followed by “AY”
Sample Input (1) : London, Sample output (1) : ONDONLAY
Sample Input (1) : Olympics, Sample output (1) : OLYMPICSAY
Q10→Write a program to assign a full path and file name as given below. Using library functions, extract and output the
file path, file name and file extension separately as shown.
Input: c:\users\admin\Pictures\flower.jpg
Output Path : c:\users\admin\Pictures\
File name : flower
Extension : jpg
Q11→Write a program to input a sentence from user and print every alternative characters (leaving space, vowel and
numbers) of it (starting from first character).
e.g; Sample Input : DISARI PUBLIC SCHOOL, HALDIA – 22 Sample output: DSRLCSHLI-
(Note: all alternate characters are underlined, output contains all of them except space, vowel and numbers).
Q10→ Write a program to assign a full path and file name as given below. Using library functions, extract and output the file
21
path, file name and file extension separately as shown. Input: c:\users\admin\Pictures\flower.jpg
Output: Path: c:\users\admin\Pictures\ File name: flower Extension: jpg
A10→ import java.util.Scanner;
public class GetChars
{ Hints:
public static void main() A9 a) A9 b)
{ for( i = 0; i < len; i++) str = str.toUpperCase();
Scanner sc = new Scanner (System.in); { chr1 = str.charAt(i); for( i = 0; i < len; i++)
String str, path = “”, fname=“”, ext=“”; chr2 = str.charAt(i+1); {
System.out.println("Enter a String "); if( chr1 == chr2 ) ch = str.charAt(i);
str = sc.nextLine(); { if(ch==‘A’||ch==‘E’||ch==‘I’||ch==‘O’||ch==‘U’)
ind = str.lastIndexOf(‘\’); cnt++; break;
path = str.substring(0, ind+1); i++; //if(“AEIOU”.indexOf(ch)>=0)
dot_ind = str.indexOf(‘.’); } // break;
fname = str.substring(ind+1, dot_ind+1); } }
ext = str.substring(dot_ind+1); str1 = str.substring(0, i);
System.out.println(“Path: “ + path); str2 = str.substring(i);
System.out.println(“File name: “ + fname); nstr = str2 + str1 + “AY”;
System.out.println(“Extension: “ + ext); Sop(nstr);
}
}
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→21
JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science
Q12→ Write a program to arrange the letters of string in alphabetically order and print the new string. Any
22
character that is Not a part of the alphabet are added at the end of the new string.
E.g: if the input is “@Computer Application 2019”,
then the output is “aAcCeiilmnooppprttu@ 2019”. [Note that there is 2 spaces after @ in output string]
Q13→ Write a program to input any given string to calculate the total number of characters and vowels present in the
23
string and also reverse the string:-
Example : input a string : SNOWY
output
Total number of characters : 05
Number of Vowels : 01
Reverse string : YWONS
Q14→Write a program that asks the user to enter a sentence, and to print the sentence in reverse order, with the
case of each letter reversed. Eg:
Q15→WAP to input a string and find total number of capital, small alphabet, number or symbol.
import java.util.Scanner;
public class GetWords
{
public static void main()
{ for( i = 0; i < len; i++)
Scanner sc = new Scanner (System.in); {
String str, wrd = ""; chr = str.charAt(i);
int i, len; char chr; if(chr != ' ')
System.out.println("Enter a String "); { //hello java program
str = sc.nextLine(); wrd = wrd + chr;
str = str + " "; }
len = str.length(); else
{ /*This is the area
* where we can write the code
* according to given programs. */
System.out.println(wrd);
wrd = "";
}
} // End of for loop
} // End of main()
} // End of class()
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→24
JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science
Q1→ WAP to input a sentence and print all words in vertical order.
25
Q2→ WAP to input a sentence and print all words in vertical order, serial no of words, total no. of character of words
and count the vowels of every word separately with following headings.
Sno. word word length Total vowels
---- ------ --------------- ----------------
Q3→ WAP to input a sentence and print all words in reverse order.
Q4→ WAP to input a sentence and print all palindrome words.
Input: MOM AND DAD ARE LEARNING MALAYALAM
Output: MOM DAD MALAYALAM
Q5→ WAP to input a sentence and print all special words from the sentence. Special words are those words which
starts and ends with the same letter. Eg: window, Existence, comic.
Q6→ Write a program to input a sentence and print the number of characters found in the longest word of the given
sentence.
For example is S = “India is my country” then the output should be 7.
Q7→ WAP to input a sentence and count the words ‘this’, ‘an’, ‘the’ separately.
Q8→ Write a program to enter a sentence from the keyboard and count the number of times a particular word occurs
in it. Display the frequency of the search word.
Eg: INPUT: Enter a sentence : the quick brown fox jumps over the lazy dog.
Enter a word to be searched : the
OUTPUT: Searched word occurs : 2 times.
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→25
JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science
28
Q7→ WAP to input a sentence and count the words ‘this’, ‘an’, ‘the’ separately.
String Theory
String StringBuffer
Once a String object is created you cannot change the StringBuffer objects can be altered on the same instance
characters that comprise the string. after creation.
String objects are immutable. StringBuffer objects are mutable.
New object is required to alter the string. New object is not required.
Similarity: Both the classes are found in java.lang package & are used for string manipulation.
Library classes:
The java environment provides several built-in class libraries that contains many in-built methods for input-output, string
handling etc. This library is also known as Application Programming Interface (API). E.g: Math class, String class,
BufferedReader Class etc.
32
33
Contents
3. Array in java
Array In Java
➢ Array is a collection of data having homogenous (similar) data Input data in array using scanner class
35
type values. Scanner sc = new Scanner (System.in);
➢ Continuous memory is allocated for array. int ar[ ] = new int[5];
There are two types of array for(int i = 0; i <= 4; i++)
1. Single Dimensional array (1 D Array) {
2. Two / Multi-Dimensional array (2 D Array) System.out.println("Enter data ");
ar[i] = sc.nextInt();
1. Single Dimensional array (1 D array)
}
Syntax: datatype arrayname[ ] = new datatype[size] ; Or
Printing an array elements
datatype [ ] arrayname = new datatype[size] ;
for(int i = 0; i <= 4; i++)
Eg: int ar[ ] = new int[5]; //20 bytes
{
double b[ ] = new double[5]; //40 bytes
System.out.println(ar[i] + “ ”);
char c[ ] = new char[5]; //10 bytes
}
Initialization of 1 Dimensional array
int ar[ ] = { 10, 20, 30, 40, 50}; Input data in array using BufferedReader class
double b[ ] = { 5.6, 10.45, 6.7, 8.5, 9.66}; BufferedReader br = new BufferedReader( new
char ch[ ] = { ‘a’, ‘b’, ‘c’, ‘d’, ‘e’}; InputStreamReader (System.in));
String st[ ] = {“abc”, “xyz”, “aaa”}; ar[0] int ar[ ] = new int[5];
for(int i = 0; i <= 4; i++)
{
ar[ ]= 10 20 30 40 50 Array Index no./
System.out.println("Enter data ");
name subscript no.
ar[0] ar[1] ar[2] ar[3] ar[4] ar[i] = Integer.parseInt( br.readLine() );
It always starts
}
from zero(0)
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→35
Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM
Array Questions
Q1→ WAP to input 10 elements in an array and print array.
37 Q2→ WAP to input 5 numbers in an array and find sum and average of array elements.
Q3→ WAP to input 5 or N numbers in an array and find product of even numbers of array elements.
Q4→ WAP to input 5 numbers in an array and copy these numbers in another array.
Q5→ WAP to input 5 numbers in an array and reverse these numbers in another array.
Q6→ WAP to input 5 numbers in an array and reverse these numbers in same array.
Q7→ WAP to input 5 or N numbers in an array and find out maximum and minimum number.
Q8→ WAP to input 5 numbers in an array and find out standard deviation.
Q9→ Write a program to accept the year of graduation from school as an integer value from the user. Using the Binary
Search and linear Search technique on the sorted array of integers given below, output the message “record exists” if
the value input is located in the array. If not, output the message “Record does not exist”.
{1982, 1987, 1993, 1996, 1999, 2003, 2006, 2007, 2009, 2010}
Q10→ Write a program to accept name and total marks of N number of students in two single subscript array name[ ] and
totalmarks[ ]. Calculate and print:
(i) The average of the total marks obtained by N number of students.
[average = (sum of total marks of all the students)/N]
(ii) Deviation of each student’s total marks with the average. [deviation = total marks of a student – average]
Q11→ Write a program to input integer elements into an array of size 20 and perform the following operations:
(i) Display largest number from the array.
(ii) Display smallest number from the array.
(iii) Display sum of all the elements of the array. (iv) Display product of all odd elements of the array.
Q5→ WAP to input 5 numbers in an array and reverse these numbers in another array.
39
Array Questions
Q12→ Write a program to input twenty names in an array. Arrange these names in descending order of alphabets,
40
using the bubble sort technique and selection sort technique. Print the sorted array.
Q13→ Write a program to initialize the seven wonders of the World along with their Locations in two different arrays.
Search for a name of the country input by the user. If found, display the name of the country along with its Wonder,
otherwise display “Sorry Not Found!”.
Seven wonders – CHICHEN ITZA, CHRIST THE REDEEMER, TAJMAHAL, GREAT WALL OF CHINA, MACHU
PICCHU, PETRA, COLOSSEUM.
Location - MEXICO, BRAZIL, INDIA, CHINA, PERU, JORDAN, ITALY
Example - Country Name : INDIA Output : INDIA – TAJMAHAL
Country Name : USA Output : Sorry Not Found!
Linear Search
Q→ WAP to input N numbers in an Array and find key element and also print index number. (Q9)
41
A→ import java.util.*;
public class Linear_Search
{ for( i = 0; i<n; i++)
public static void main() { // if(key. equalsIgnoreCase(arr[i])==true)
{ // Array Input String key; if(key == arr[ i ]) {
int n, key, i, flag=0 ; // String key flag = 1;
Scanner sc = new Scanner(System.in); break;
System.out.println("Enter total number of elements of array:"); }
n = sc.nextInt(); } //end of while loop
int arr[ ] = new int[n]; // String arr[] = new String[n]; if(flag == 1)
for(i = 0; i < n; i++) {
{ System.out.print(key+“ Number is found at ”+i);
System.out.println("Enter array number :"); }
arr[i] = sc.nextInt(); // arr[i] = sc.nextLine(); else
} {
System.out.print(“Number is not found”);
System.out.println("Enter number to be searched :"); }
key = sc.nextInt(); // key = sc.nextLine(); }
}
Linear Search
Q→ WAP to input 20 fractional numbers in an Array and find key element and also print index number. (Q9)
42
A→ import java.util.*;
public class Linear_Search
{ for( i = 0; i < 20; i++)
public static void main() { // if(key. equalsIgnoreCase(arr[i])==true)
{ // Array Input String key; if(key == arr[ i ]) {
int i, flag=0 ; flag = 1;
double key; // String key break;
Scanner sc = new Scanner(System.in); }
double arr[ ] = new double[20]; // String arr[] = new String[20]; } //end of while loop
for(i = 0; i < 20; i++) if(flag == 1)
{ {
System.out.println("Enter array number :"); System.out.print(key+“ Number is found at ”+i);
arr[i] = sc.nextDouble(); // arr[i] = sc.nextLine(); }
} else
{
System.out.println("Enter number/name to be searched :"); System.out.print(“Number is not found”);
key = sc.nextDouble(); // key = sc.nextLine(); }
}
}
Binary Search
Note→ Binary search based on string not in syllabus while(li <= ui)
43 import java.util.*; (Q9) {
public class Binary_Search mid = (li + ui)/2;
{ if(key < arr[mid]) // for first half
public static void main() {
{ ui = mid - 1;
int n, key, i; }
Scanner sc = new Scanner(System.in); else if(key > arr[mid]) // for second half
System.out.print("Enter total no. of elements of array:"); {
n = sc.nextInt(); li = mid + 1;
int arr[] = new int[n]; }
else if(key == arr[mid])
for(i = 0; i<n; i++) {
{ flag = 1;
System.out.println("Enter array number :"); break; }
arr[i] = sc.nextInt(); } //end of while loop
} if(flag == 1)
System.out.print(“Number is found at ”+(mid+1)+ “ position”);
System.out.println("Enter number to be searched :"); else
key = sc.nextInt(); System.out.print(“Number is not found”);
int li = 0, ui = n-1, mid, flag=0; } //end of the main method
} // end of the class
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→43
Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM
Binary Search
Q→ WAP to input N numbers/names in an Array and sort array in ascending order. (Using bubble sort). (Q12)
45
A→ import java.util.*;
public class Bubble_sort int temp; //String temp
{ for ( i = 0; i < n-1; i++)
public static void main() {
{ for ( j = 0; j < (n-1-i); j++)
int n, i, j; { //if( arr[ j ]. compareToIgnoreCase(arr[ j+1 ])>0)
Scanner sc = new Scanner(System.in); if(arr[ j ] > arr[ j+1 ]) // ascending order
System.out.print("Enter total number of element of array"); {
n = sc.nextInt(); temp = arr[ j ];
arr[ j ] = arr[ j+1 ];
int arr[] = new int[n]; //String arr[] = new String[n]; arr[ j+1 ] = temp;
}
for(i = 0; i<n; i++) }
{ }
System.out.println("Enter array number :"); System.out.println("sorted array is ");
arr[i] = sc.nextInt(); // arr[i] = sc.nextLine(); for ( i = 0; i < n; i++)
} {
System.out.println(arr[ i ]+ “ “ );
}
Q→ WAP to input 20 fractional nos in an Array and sort array in descending order. (Using bubble sort). (Q12)
46
A→ import java.util.*;
public class Bubble_sort int temp; //String temp
{ for ( i = 0; i < 19; i++)
public static void main() {
{ for ( j = 0; j < (19 - i); j++)
int i, j; { //if( arr[ j ]. compareToIgnoreCase(arr[ j+1 ])<0)
Scanner sc = new Scanner(System.in); if(arr[ j ] < arr[ j+1 ]) // for descending order
{
double arr[] = new double[20]; //String arr[] = new String[n]; temp = arr[ j ];
arr[ j ] = arr[ j+1 ];
for(i = 0; i<20; i++) arr[ j+1 ] = temp;
{ }
System.out.println("Enter array values :"); }
arr[i] = sc.nextDouble(); // arr[i] = sc.nextLine(); }
} System.out.println("sorted array is ");
for ( i = 0; i < 20; i++)
{
System.out.println(arr[ i ]+ “ “ );
}
Selection Sort
Selection Sort
Q→ Write a program to input twenty names/numbers in an array. int minpos = 0, index = 0, temp;
48
Arrange these names/numbers in ascending order of alphabets, for ( i = 0; i < 19; i++)
using the selection sort technique. Print the sorted array. (Q12) {
minpos = i ;
import java.util.*; for ( j = i+1; j < 20; j++)
public class Selection_sort { //if(arr[ j ] < arr[ maxpos ]) // for ascending
{ if( arr[ j ]. compareToIgnoreCase(arr[minpos])<0)
public static void main() {
{ minpos = j ;
int i; }
Scanner sc = new Scanner(System.in); }
temp = arr[ i ];
String arr[] = new String[20]; // int arr[] = new int[20]; arr[ i ] = arr[ minpos ];
arr[ minpos ] = temp;
for(i = 0; i < 20; i++) }
{ System.out.println(“Sorted Array is ");
System.out.println("Enter 20 names :"); for ( i = 0; i < 20; i++)
arr[i] = sc.nextLine(); // arr[i] = sc.nextInt(); {
} System.out.println(arr[ i ]+ “ ”);
}
Linear Search:
Name the search or sort algorithm that:
50 The item is compare one by one with each element in an
a. Makes n-1 passes to sort the whole array checking the
array, which traverses sequentially to locate the item. It is
adjacent elements in every pass. Bubble Sort
time consuming for large no. of elements. Array need not
b. Compare the sought key with each key element of the
be sorted.
array. linear Search
The range of an array with 10 elements.
Binary Search:
Range of array is from 0 to (length of array – 1), i.e. 0 to 9.
The array has to be in sorted order. The array is divided
Sorting
into two halves and the middle element is compared. If the
Bubble Sort:
search value is not located on middle element then either
In bubble sort the adjacent elements are compared. For
of the two halves is checked depending upon the search
ascending order if the element is greater than it is
value. It is the faster processes for large no. of elements.
interchanged (swapped) with the adjacent element. This
process is repeated for all the elements for n-1 times. It goes
Array Instantiation
through all the loop cycles even if the array is sorted much
To instantiate (or create) an array, write the new keyword,
before.
followed by the square brackets containing the number of
Selection Sort:
elements you want the array to have.
The maximum or minimum value is found and is swapped
int ages[] = new int[100];
with the first element of the array, the same process is
repeated for 2nd , 3rd element and so on. It is faster than
You can also instantiate an array by directly initializing it
Bubble sort.
with data. For example: int arr[] = {1, 2, 3, 4, 5};
Q5: What will this code print ? [2] Q11: What is the difference between the linear search and the
52 int arr[] = new int[5]; binary search technique? [2]
System.out.println(arr); Q12: String x[] = {“Artificial intelligence”, “IOT”, “Machine learning”,
“Big data”};
(i) 0 (iii) 0000
Give the output of the following statements:
(ii) value stored in arr[0] (iv) garbage value (i) System.out.println(x[3]);
(ii) System.out.println(x.length);
Q6: If int x[] = {4, 3, 7, 8, 9,10};
what are the values of p and q ? [2]
Q13: What will this code print ? [2]
(i) p = x.length int arr[] = new int[5];
(ii) q = x[2] + x[5] * x[1] System.out.println(arr[0]);
Q7: Name any one reference data type. [2] (i) 0 (iii) 0000
Q8: String x[] = {“SAMSUNG”, “NOKIA”, “SONY”, “MICROMAX”, (ii) value stored in arr[0] (iv) garbage value
BLACKBERRY};
Give the output of the following statements: [2]
(i) System.out.println(x[1]); Q14: If int x[] = {4, 3, 7, 8, 9,10};
(ii) System.out.println(x[3].length()); what are the values of p and q?
Q9: Differentiate between searching and sorting? (i) p = x[1] % x[0] + ++x[3] * x[3] / x[5]++
Q10: Consider the following String array and give the output. (ii) q = x[2] + x[5] / x[1] * x[2]
String arr[] = {“DELHI”, “CHENNAI”, “MUMBAI”, “LUCKNOW”,
“JAIPUR”};
System.out.println(arr[0].length()>arr[3].length());
System.out.print(arr[4].substring(0,3);
Q15: String x[] = {“Artificial intelligence”, “IOT”, “Machine learning”, “Big data”}; [2]
53
Give the output of the following statements:
(i) System.out.println(x[2].length());
(ii) System.out.println(x[3].substring(2, x.length);
Q16: Consider the following String array and give the output. [2]
String arr[] = {“DELHI”, “CHENNAI”, “MUMBAI”, “LUCKNOW”, “JAIPUR”};
System.out.println(arr.length != arr[0].length());
System.out.print(arr[3].replace(‘N’, ‘m’));
Ans→ 1) a) 2, 3, 4,
3) value of arr are 1,2,3,5,5
value of k is 3
1 4) p = 11 q=28
2-D Array
2-D Array Initialization
54
Syntax: Datatype arrayname[ ] [ ] = {{row 1},{row2}……)
Eg:
int ar4[ ][ ] = { {10, 20, 30}, {40, 50, 60} };
double ar5[ ][ ]= { {1.0, 2.5, 3.4}, {4.6, 5.5, 6.1}}; 10(0,0) 20(0,1)
char ar6[ ][ ] = { {'A’, 'B’, 'C’}, {'D’, 'E’, 'F’} };
30(1,0) 40(1,1)
2-D Array Declaration
Syntax: datatype arrayname[ ] [ ] = new datatype[ row ] [ col ]; 50(2,0) 60(2,1)
datatype [ ] [ ] arrayname = new datatype[ row ] [ col ];
Eg:
int ar1[ ] [ ] = new int[3][4];
double [ ] [ ]ar2 = new double[3][4];
char ar3[ ] [ ] = new char[3][4];
//Printing System.out.println("Array 4'S Elements are ");
for(i=0; i<2; i++)
{
for(j=0; j<3; j++)
{
System.out.print( ar4 [ i ] [ j ] + “ ”);
}
System.out.println();
}
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→54
Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM
2-D Array
Q1→ WAP to input data in two matrixes of order 3x3 and add these two matrixes.
55 Q2→ WAP to input data in a matrix of order 2x3 and find out its transpose of a matrix.
Q3→ WAP to input data in two matrixes and find out product of two matrixes.
Q4→ WAP to input data in a matrix of order 4x4 and print its both diagonal elements separately.
Q5→ WAP to input data in a matrix and print sum of each row and column elements separately.
import java.util.*;
public class Input_in_2DArray
{
public static void main()
{
Scanner sc = new Scanner(System.in);
int ar[][] = new int[3][4]; // 2-D Array Declaration System.out.println("Array Elements are ");
//Input in 2 D Array for(i=0; i<3; i++)
int i, j ; {
for(i=0; i<3; i++) for(j=0; j<4; j++)
{ {
for(j=0; j<4; j++) System.out.print(ar[i][j]+" ");
{ }
System.out.println("Input data in 2-D Array 3x4 Matrix "); System.out.println();
ar[i][j] = sc.nextInt(); }
} }
} }
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→55
Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM
/** WAP to input 2-D array order 3x4 and and find its transpose matrix 4x3 */
import java.util.*;
public class Transpose_2DArray
56 {
public static void main()
{
Scanner sc = new Scanner(System.in);
int arr[ ] [ ] = new int[3][4];
for(i=0; i<3;i++)
int trans[ ] [ ] = new int[4][3]; {
int i, j; for(j=0;j<4;j++)
for(i=0; i<3;i++) {
{ trans[ j ] [ i ] = arr[ i ] [ j ];
for(j=0;j<4;j++) }
{ }
System.out.println("Enter Data in array matrix [3x4] "); System.out.println("Transpose matrix ");
arr[i][j]=sc.nextInt(); for(i=0; i<4;i++)
} {
} for(j=0;j<3;j++)
System.out.println("Original array is "); {
for(i=0; i<3;i++) System.out.print(trans[i][j]+" ");
{ }
for(j=0;j<4;j++) System.out.println();
{ }
System.out.print(arr[i][j]+" ");
}
}
System.out.println(); }
}
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→56
Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM
2-D Array
//WAP to input data in 2-D Array matrix order 3x3 and find sum System.out.println("Original matrix is ");
57 of left(main) and right diagonal individually for(i=0; i<3;i++)
//and print diagonal elements also. {
import java.util.*; for(j=0;j<3;j++)
public class Sum_Of_diagonals_2DArray {
{ System.out.print(arr[i][j]+" ");
public static void main() }
{ System.out.println();
Scanner sc = new Scanner(System.in); }
int arr[][] = new int [3][3]; System.out.print("Left Diagonal elements are ");
int i,j; int suml=0,sumr=0;
//input in 2 d array for(i=0; i<3;i++)
for(i=0; i<3;i++) {
{ for(j=0;j<3;j++)
for(j=0;j<3;j++) {
{ if(i==j)
System.out.println("Enter data in 2 d array "); {
arr[i][j]=sc.nextInt(); suml = suml + arr[i][j];
} System.out.print(arr[i][j]+" ");
} }
}
}
2-D Array
}
}
2-D Array
59
2-D Array
60
2-D Array
61