0% found this document useful (0 votes)
416 views61 pages

YPCC ICSE 11th String Handling&Array

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)
416 views61 pages

YPCC ICSE 11th String Handling&Array

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/ 61

JMD-HGGM

Strings & Arrays

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/

YOGESH VERMA (MCA) : 8329686472, 7798453624, 7798161873


JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→2


JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

STRINGS IN JAVA

String is a set of characters in java.


3

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.

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→3


JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

How to input Strings

String & character input using scanner String & character input using BufferedReader
4

import java.util.Scanner; import java.io.*;


class Str_input
class Str_input
{
{ public static void main() throws IOException
public static void main() {
{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner sc = new Scanner (System.in); System.out.println("Enter a String ");
System.out.println("Enter a String "); String str = br.readLine();
str = sc.nextLine(); System.out.println("Enter a character ");
str = sc.next() char ch = (char)br.read();
System.out.println("Enter a character "); }
char ch = sc.next().charAt(0); }
} Note:
} readLine() → It is a method which helps to get a string at run time using object
of BufferedReader class.
read() → It is used to get a character from keyboard but it returns ASCII
→ nextLine() used to get sentence/string. value of a inputted character at run time.
Character ASCII Code
→ next() used to get word. A to Z 65 to 90
A to z 97 to 122
→ next().charAt(0) used to get characters.
0 to 9 48 to 57
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→4
JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

Methods / Functions

1. Pre-Defined Function → Functions/Methods which are pre-defined in ‘JAVA’ language.


5
Examples → pow(), abs(), length(), toUpperCase(), etc.
There are three types of pre-defined java functions.
1. Character methods, 2. String methods, 3. Math Methods.
1. Character methods:
Character.isLetter() → method checks whether a character is a letter/alphabet or not.
Syntax → boolean Character.isLetter( char )
Argument
Return Type
Wrapper Class Method Name

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);

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→5


JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

Character Methods / Functions

Character.toUpperCase() → Method returns a character in upper case.


6

Character.toLowerCase() → Method returns a character in lower case.

Syntax → char Character.toUpperCase( char )

Argument
Wrapper Class Method Name
Return Type

Outputs Eg2: Outputs


Eg1:→ char b;
char b, ch1 = ‘g’, ch2 = ‘M’ ;
b=Character.toUpperCase(‘e’);
b=Character.toUpperCase(ch1);
System.out.print(b);
System.out.print(b);
b=Character.toLowerCase(‘E’);
b=Character.toLowerCase(ch2);
System.out.print(b);
System.out.print(b);

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→6


JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

Character Methods / Functions

SYNTAX OF FUNCTION EXAMPLE


7

1. boolean Character.isLetter(char) boolean b = Character.isLetter(‘y’)

2. boolean Character.isDigit(char) boolean b = Character.isDigit(‘5’)


Note:
Any
3. boolean Character.isLetterOrDigit(char) boolean b = Character.isLetterOrDigit(‘E’) method
start with
4. boolean Character.isWhitespace(char) boolean b = Character.isWhitespace(‘ ’) word ‘is’
that return
5. boolean Character.isUpperCase(char) boolean b = Character.isUpperCase(‘M’) always
6. boolean Character.isLowerCase(char) boolean b = Character.isLowerCase(‘m’) boolean
value.
7. char Character.toUpperCase(char) char ch = Character.toUpperCase(‘y’)

8. char Character.toLowerCase(char) char ch = Character.toLowerCase(‘P’)

Wrapper Class Argument


Return Type Method name true
boolean
false

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→7


JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

character Questions.

Q1→Character conversion into Opposite Case. Q2→WAP to input a character and check it is symbol or not.
8

import java.util.Scanner; import java.util.Scanner;


class Case_conversion class Case_conversion
{ {
public static void main() public static void main()
{ {
Scanner sc = new Scanner (System.in); Scanner sc = new Scanner (System.in);
System.out.println("Enter a character "); System.out.println("Enter a character ");
char ch = sc.next().charAt(0); char ch = sc.next().charAt(0);
if(Character.isUpperCase(ch)) if( !Character.isLetterOrDigit(ch) )
{ {
ch = Character.toLowerCase(ch); System.out.print(“It is symbol”);
} }
else if(Character.isLowerCase(ch)) else
{ {
ch = Character.toUpperCase(ch); System.out.print(“It is not symbol”);
} }
System.out.print( ch ); }
}
}

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→8


JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

String Methods / Functions

SYNTAX OF FUNCTION EXAMPLE


9

String s1 = “Yp”, s2 = “Comp”, s3;


1. String concat(String s)
s3 = s1.concat(s2); sop(s3); // s3 = “YpComp”
String s1 = “yp comp”;
2. String toUpperCase()
s1 = s1.toUpperCase(); sop(s1); // s1 = “YP COMP”
String s1 = “YP COMP”;
3. String toLowerCase()
s1 = s1.toLowerCase(); sop(s1); // s1 = “yp comp”
String s1 = “ JAVA ”;
4. String trim()
s1 = s1.trim(); sop(s1); //s1=“JAVA”
String s1 = “YPCOMPUTER”;
5. String substring(int bi)
s1 = s1.substring(5); sop(s1); //s1=“PUTER” Y P C O M P U T E R
String s1 = “YPCOMPUTER”; 0 1 2 3 4 5 6 7 8 9
6. String substring(int bi, int li)
s1 = s1.substring(2, 7); sop(s1); // s1 = “COMPU”
String s = “java”;
7. String replace(char oldc, char newc)
s = s.replace(‘a’, ‘i’); sop(s); //s = “jivi”

8. String valueOf(all num type) int a=10; String s = String.valueOf(a); //s = “10”

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→9


JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

String Methods

SYNTAX OF FUNCTION EXAMPLE


10
String s=“yp comp.”; int len;
9. int length()
len = s.length(); sop(len); // len = 8
10. int indexOf(char ch) String s=“computer”; int p=s.indexOf(‘m’); sop(p); // p = 2
11. int indexOf(char ch, int i) String s=“malayalam”; int p=s.indexOf(‘a’, 3); sop(p); // p = 3
12. int lastIndexOf(char ch) String s=“malayalam”; int p=s.lastIndexOf(‘a’); sop(p); // p = 7
String s1 = “camp”, s2 = “champ” ; int d;
d = s1.compareTo(s2); sop(d); // d = -7
13a. int compareTo(String s2) if strings are equal then it returns zero (0).
Sop(“computer”.compareTo(“comp”)); // 4
Sop(“comp”.compareTo(“computer”)); // -4
String myStr1 = "HELLO"; String myStr2 = "hello";
13b. int compareToIgnoreCase(String s2)
System.out.println(myStr1.compareToIgnoreCase(myStr2));
14. char charAt(int n) String s = “computer”; char ch = s.charAt(2); //ch = ‘m’
boolean b; String s1 = “Camp”, s2 = “Comp”;
15. boolean equals(String s)
b = s1.equals(s2); sop(b); // b = false
boolean b; String s1 = “comp”, s2 = “Comp”;
16. boolean equalsIgnoreCase(String s)
b = s1.equalsIgnoreCase(s2); sop(b); // b = true
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→10
JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

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

Other examples → String str = “Hello Java.”


System.out.println( str.substring(6, 6) ); → No Errors but it won’t print any thing
System.out.println( str.substring(6, 4) ); → Runtime Error StringIndexOutOfBoundsException
System.out.println( str.substring(12) ); → Runtime Error StringIndexOutOfBoundsException
System.out.println( str.charAt(12) ); → Runtime Error StringIndexOutOfBoundsException

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.

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→11


JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

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.

Characteristics of StringBuffer object:


➢ It reserves specific length in memory to contain characters.
➢ We can change its length by using setLength() function.
➢ If the length of the string is more than the size of the StringBuffer object, then characters exceeding the size are truncated.
➢ If a string is smaller than the size of the StringBuffer object, then it contains extra characters as ‘\u000’ (garbage value) in
the empty space.

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→12


JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

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

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→13


JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

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

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→14


JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

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)

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→15


JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

StringBuffer

Other examples →
16

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→16


JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

String Master Program – based on chars


Master program to get characters from string
17 import java.util.Scanner;
public class GetChars
{
public static void main()
{
Scanner sc = new Scanner (System.in);
int i, len;
char chr;
System.out.println("Enter a String ");
String str = sc.nextLine();
len = str.length();
for( i = 0; i < len; i++)
{
chr = str.charAt(i);
/*
* This is the area where we can write the code
* according to given programs. */
System.out.println(chr);
}
}
}
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→17
JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

String Questions - based on Characters.

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.

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→18


JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

String Programs – based on chars

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

String Programs – based on chars

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).

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→20


JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

String Programs – based on chars

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

String Programs – based on chars

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]

A12→ import java.util.Scanner;


public class Arrange_Letters
for( x = ‘A’; x <= ‘Z’; x++)
{
{
public static void main() for( i = 0; i < len; i++)
{ { chr = str.charAt(i);
Scanner sc = new Scanner (System.in); if( Character.isLetter(chr))
String str, nstr=“”, nstr1=“”; {
int i, len; if(Character.toUpperCase(chr) == x)
nstr = nstr + chr;
char chr, x;
}
System.out.println("Enter a String "); else
str = sc.nextLine(); nstr1 = nstr1 + chr;
len = str.length(); }
}
System.out.println(nstr + nstr1);
} }
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→22
JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

String Programs – based on chars

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.

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→23


JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

Master program - based on words.

Master program to get words from sentence


24

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

String programs - based on words.

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

String programs - based on words.

Q4→ WAP to input a sentence and print all palindrome words.


26
Input: MOM AND DAD ARE LEARNING MALAYALAM
Output: MOM DAD MALAYALAM

A4→ import java.util.Scanner; for( i = 0; i < len; i++)


public class GetWords {
{ chr = str.charAt(i);
public static void main() if(chr != ' ')
{ { //hello java program
Scanner sc = new Scanner (System.in); wrd = wrd + chr;
String str, wrd = “”, rwrd = “”; rwrd = chr + rwrd;
int i, len; char chr; }
System.out.println("Enter a String "); else
str = sc.nextLine(); {
str = str + " "; if( wrd.equals(rwrd) )
len = str.length(); System.out.println(wrd+ “ ”);
wrd = ""; rwrd = “”;
}
}
}
}
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→26
JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

String programs - based on words.

Q9→ Consider the following statement:


27 “January 26 is celebrated as the Republic Day of India”. Write a program to change 26 to 15, January to August,
Republic to Independence and finally print “August 15 is celebrated as the Independence Day of India”.
Q10→ WAP to input a sentence and print max and min word.
Q11→ Write a program to input a sentence and print the smallest word of the given sentence.
For example: if s = “India is my country” then the output should be ‘is’.

A9→ import java.util.Scanner; for( i = 0; i < len; i++)


public class GetWords { chr = str.charAt( i );
{ if( chr != ' ‘ )
public static void main() wrd = wrd + chr;
else
{
{ if( wrd.equals(“26”) )
Scanner sc = new Scanner (System.in); nstr = nstr + “15”;
String str, wrd = “”, nstr = “”; else if( wrd.equals(“January”) )
int i, len, char chr; ; nstr = nstr + “August”;
System.out.println("Enter a String "); else if( wrd.equals(“Republic”) )
str = sc.nextLine(); nstr = nstr + “Independence”;
str = str + " "; else
nstr = nstr + wrd;
len = str.length();
wrd = "";
}
}
System.out.println(“statement =” + nstr);
} }
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→27
JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

Q & A - based on words.

28
Q7→ WAP to input a sentence and count the words ‘this’, ‘an’, ‘the’ separately.

A7→ import java.util.Scanner; for( i = 0; i < len; i++)


public class GetWords {
{ chr = str.charAt(i);
public static void main() if(chr != ' ') //hello java program
{ wrd = wrd + chr;
Scanner sc = new Scanner (System.in); else
String str, wrd = “”; {
char chr; if( wrd.equals(“this”))
int i, len, cnt1=0, cnt2=0, cnt3=0; cnt1++;
System.out.println("Enter a String "); else if( wrd.equals(“an”))
str = sc.nextLine(); cnt2++;
str = str + " "; else if( wrd.equals(“the”))
len = str.length(); cnt3++;
wrd = "";
}}
System.out.println(“this” + cnt1 + “an” + cnt2 + ”the”+ cnt3);
}
}

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→28


JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

Q & A - based on words.

29 Q9→WAP to input a sentence and print max and min word.

A9→ import java.util.Scanner;


public class MaxMinWords
maxw = minw = str.substring(0, str.indexOf(‘ ’));
{
for( i = 0; i < len; i++)
public static void main()
{
{
chr = str.charAt(i);
Scanner sc = new Scanner (System.in);
if(chr != ' ') //hello java program
String str, wrd = “”, maxw=“”, minw=“”;
wrd = wrd + chr;
int i, len; char chr;
else
System.out.println("Enter a String ");
{
str = sc.nextLine();
if( wrd.compareTo(maxw)>0)
str = str + " ";
maxw = wrd;
len = str.length();
if( wrd.compareTo(maxw)<0)
minw = wrd;
}
wrd = ""; rwrd = “”;
}
System.out.println(“max:”+maxw+“\n min:”+min);
}
}
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→29
JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

String Theory

30 Differences & Similarity between String & StringBuffer.

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.

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→30


JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

String output Questions

Q1: Find the output of the following expressions. Outputs


31
a) String st = “YP COMPUTER”;
System.out.println(st.indexOf(st.charAt(6)));
System.out.println("TRANSPARENT".compareTo("TRANSITION"));
b) String s = “application”;
int p = s.indexOf(“a”);
System.out.println(p);
System.out.println(p + s);
System.out.println("ACHIEVEMENT".replace('E', 'A'));
Q2: State the output when the following program segment is executed:
String a = “Smartphone”, b= “Graphic Art”
String h = a.substring(2, 5);
String k = b.substring(8).toUpperCase();
System.out.println(h);
System.out.println(k.equalsIgnoreCase(h));
System.out.println (c.indexOf(‘a’, 2));
System.out.println (c.indexOf(‘a’, 3));
Q3: Write the output for the following:
char ch = '2’; int m = ch; m = m + 5;
System.out.println(m + " " + ch);
String s = "Today is Test" ;
System.out.println(s.substring(0, 7) + " " +"Holiday");
System.out.println(“MISSISSIPPI”.indexOf('S')+“MISSISSIPPI”.lastIndexOf(‘I’));
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→31
JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

32

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→32


JMD HGGM
Ch: String Handling ISC Class 11th Sub: Computer Science

33

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→33


Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM

Contents

34 Ch_no. Topics Page No.

3. Array in java

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→34


Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM

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

Basic Structure Of Array Question - Answer

import java.util.*; // Printing array elements


36 class Array1 for (int i = 0; i < n; i++)
{ {
public static void main() System.out.println( a[ i ] );
{ }
Scanner sc = new Scanner(System.in); Q1→ WAP to input 10 elements in an array and print array.
System.out.println("Enter total number of elements"); A→ import java.util.*;
int n = sc.nextInt(); class Array1
// Array declaration {
int a[ ] = new int [n]; public static void main()
// Array Input {
for ( int i = 0; i < n; i++) Scanner sc = new Scanner(System.in);
{ int a[ ] = new int [10];
System.out.println("Enter data"); for ( int i = 0; i < 10; i++)
a[i] = sc.nextInt(); {
} System.out.println("Enter data");
for (int i = 0; i < n; i++) a[i] = sc.nextInt();
{ }
//calculation code will come here for (int i = 0; i < 10; i++)
// according to given program { System.out.println( a[ i ] ); }
} } }

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→36


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.

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→37


Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM

Array Question - Answer


Q2→ WAP to input N/10 numbers in an array and find sum and average of array elements.
38 A2→ import java.util.*; import java.util.*;
class Array1 class Array1
{ {
public static void main() public static void main()
{ {
Scanner sc = new Scanner(System.in); Scanner sc = new Scanner(System.in);
System.out.println("Enter total number of elements"); nt a[ ] = new int[10];
int n = sc.nextInt(); for(int i=0; i<10;i++)
int a[ ] = new int [n]; //int a[ ] = new int[10]; {
for ( int i = 0; i < n; i++) //for(int i=0; i<10;i++) System.out.println("Enter data");
{ a[i] = sc.nextInt();
System.out.println("Enter data"); }
a[i] = sc.nextInt(); int sum = 0; double avg;
} for(int i=0; i<10;i++)
int sum = 0; double avg; {
for (int i = 0; i < n; i++) //for(int i=0; i<10;i++) sum = sum + a[ i ];
{ }
sum = sum + a[ i ]; avg = sum/n;
} System.out.println(“sum =”+sum );
avg = sum/n; System.out.println(“average =”+avg );
System.out.println(“sum =”+sum ); }
System.out.println(“average =”+avg ); } } //End of class } //End of class
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→38
Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM

Array Question - Answer

Q5→ WAP to input 5 numbers in an array and reverse these numbers in another array.
39

A5→ import java.util.*;


class Array4 System.out.println(“reverse array is ” );
{ for (int i = 0; i < n; i++)
public static void main() {
{ System.out.print( ar[ i ] + “ ”);
Scanner sc = new Scanner(System.in); }
System.out.println("Enter total number of elements"); }
int n = sc.nextInt(); } //end of class
int a[ ] = new int [n];
int ar[ ] = new int [n];
for ( int i = 0; i < n; i++)
{
System.out.println("Enter data");
a[i] = sc.nextInt();
}
for (int i = 0; i < n; i++)
{
ar[ n-1-i ] = a[ i ];
}

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→39


Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM

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!

Searching in Array→ There are 2 types of searching


1) Linear Search (with numbers and string)
2) Binary Search (with numbers only)

Sorting in Array → There are 2 types of sorting in array


1) Bubble sort (with number and string)
2) Selection sort (with number and string)

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→40


Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM

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(); }
}

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→41


Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM

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(); }
}
}

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→42


Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM

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

Note→Binary search based on string not in syllabus while(li <= ui)


44 (Binary search with 20 fractional numbers) {
import java.util.*; (Q9) mid = (li + ui)/2;
public class Binary_Search if(key < arr[mid]) // for first half
{ {
public static void main() ui = mid - 1;
{ }
int i; else if(key > arr[mid]) // for second half
double key; {
double arr[] = new double[20]; li = mid + 1;
Scanner sc = new Scanner(System.in); }
for(i = 0; i<20; i++) else if(key == arr[mid])
{ {
System.out.println("Enter array number :"); flag = 1;
arr[i] = sc.nextDouble(); break; }
} } //end of while loop
if(flag == 1)
System.out.println("Enter number to be searched :"); System.out.print(“Number is found at ”+(mid+1)+ “ position”);
key = sc.nexDouble(); else
int li = 0, ui = 19, mid, flag=0; System.out.print(“Number is not found”);
} //end of the main method
} // end of the class
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→44
Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM

Program of Sorting of numeric & string array using bubble sort

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 ]+ “ “ );
}

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→45


Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM

Program of Sorting of numeric & string array using bubble sort

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 ]+ “ “ );
}

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→46


Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM

Selection Sort

Q→ Write a program to input N names/numbers in an array. int maxpos = 0, index = 0, temp;


47
Arrange these names/numbers in descending order of alphabets, for ( i = 0; i < n-1; i++)
using the selection sort technique. Print the sorted array. (Q12){
maxpos = i ;
import java.util.*; for ( j = i+1; j < n; j++)
public class Selection_sort { //if( arr[ j ]. compareToIgnoreCase(arr[maxpos])>0)
{ if(arr[ j ] > arr[ maxpos ]) // for descending order
public static void main() {
{ maxpos = j ;
int n, i; }
Scanner sc = new Scanner(System.in); }
System.out.print("Enter total number of element of array"); temp = arr[ i ];
n = sc.nextInt(); arr[ i ] = arr[ maxpos ];
arr[ maxpos ] = temp;
int arr[] = new int[n]; //String arr[] = new String[n]; }
System.out.println(“Sorted Array is ");
for(i = 0; i < n; i++) for ( i = 0; i < n; i++)
{ {
System.out.println("Enter array number :"); System.out.println(arr[ i ]+ “ ”);
arr[i] = sc.nextInt(); // arr[i] = sc.nextLine(); }
}

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→47


Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM

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 ]+ “ ”);
}

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→48


Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM

Array Theory Points

Array is a group of elements of same type. It is stored in a Length property:


49 contiguous memory location Length property is used to get total number of elements
of an array. It returns the size of the array.
Advantage: Eg. int a[] = {1, 4, 3, 2, 7};
➢ It can store many values under a single name. int len = a.length; // 5 (counts from 1.)
➢ Every element can be accessed by its index using for loop.
➢ Searching and sorting of elements is easier. Name the error which is caused when the specified
position exceeds the last index of an array.
Dis-advantage: Error arised is ArrayIndexOutOfBoundException.
➢ It can store value of one data-type only. Eg. int a[] = {2, 4, 6, 3, 2, 7};
➢ Length of the array is fixed. System.out.print(a[5]); //index 5 is not available.

Subscript/index number Two types of array:


Index number/subscripts are positions of each element of the 1. Single Dimension Array: The element in single
array, to allow the program to access an individual element of dimension array is accessed by single subscript.
the array. It begins with zero and end at length-1. Eg. Int a[] = new int[10];
2. Multi Dimension Array: The elements in multi
Subscripted variable dimension array are accessed by 2 subscripts.
Subscripted variable is a symbolic name for an array of Eg. Int a[][]=new int[2][3]; //2 rows & 3 columns.
variables whose elements are identified by subscripts.
Eg: a[0]=20; a is subscripted variable and 0 is subscript. 10 20 30
40 50 60
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→49
Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM

Array Theory Points

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};

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→50


Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM

Exercise - Find the outputs:

Q1: Q2: Write java statements for the following


51 a) int ar[ ] = {1, 2, 3, 4, 5}; a) Initialise char A[] with vowels in the English language.
int i = 2;
ar[i] += ar[i++] + 1 - ++ar[i-1]; Q3: Give the values that will be stored in myArr and k after you
for(i=1; i<=3; i++) invoke mystery(myArr,k), Where myArr, k, and mystery() are
System.out.println( ar[i] + “,” ); declared as follows:
int myArr[]={1,2,3,4,5};
b) String x[ ] = { “Hello”, “Word” }; int k = 3;
System.out.println( x[1].length() ); void mystery(int a[], int m)
System.out.print( x.length ); {
++a[m];
c) double a[]={2.93, 4.65, 3.12, 9.0, 6}; --m;
for(int s = 0; s <= 4; s++) }
{
a[s] += 5; Q4: The following numbers: (89,20,31,56,25,64,48) are to be
System.out.println(a[s]); sorted using selection sort. The Array Elements after the 1st
} iteration : ( 20,89,31,56,25,64,48). Show the array elements
after the second iteration.
d) Find out the number of bytes required to store
byte B[20]

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→51


Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM

Array output Questions

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);

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→52


Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM

Array output Questions

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’));

Q17: String x[] = {“SAMSUNG”, “NOKIA”, “SONY”, “MICROMAX”,BLACKBERRY};


Give the output of the following statements: [2]
(i) System.out.println(x[1].toLowerCase());
(ii) System.out.println(x[3].substring(x.length));

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

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→53


Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM

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]+" ");
} }
}
}

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→57


Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM

2-D Array

System.out.print("\nRight Diagonal elements are ");


58 for(i=0; i<3;i++)
{
for(j=0;j<3;j++)
{
if(i+j==2)
{
sumr = sumr + arr[i][j];
System.out.print(arr[i][j]+" ");
}
}
}
System.out.println("\nSum of left diagonal elements = "+suml);
System.out.println("Sum of right diagonal elements = "+sumr);

}
}

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→58


Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM

2-D Array

59

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→59


Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM

2-D Array

60

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→60


Ch: Arrays in Java (1d & 2d) ISC Class 11th Sub: Computer Science
JMD HGGM

2-D Array

61

Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→61

You might also like