2.tushar - Assignment 2
2.tushar - Assignment 2
Array:
Exercise 1: Create a method which accepts an array of integer elements and return the second smallest
element in the array
Argument int[]
ANSWER: public class getSecondSmallest{
public static int getSecondSmallest(int[] a, int total){
int temp;
for (int i = 0; i < total; i++)
{
for (int j = i + 1; j < total; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
} } }
return a[1];//2nd element because index starts from 0
}
public static void main(String args[]){
int a[]={1,2,5,6,3,2};
int b[]={44,66,99,77,313,22,55};
System.out.println("Second smallest: "+getSecondSmallest(a,6));
System.out.println("Second smallest: "+getSecondSmallest(b,7));
}}
OUTPUT: Second smallest: 2 Second smallest: 44
Strings:
Questions and Exercises: Characters and Strings
Questions
1. What is the initial capacity of the following string builder?
c. Write an expression that refers to the letter b in the string referred to by hannah.
Answer: hannah.charAt(15).
3. How long is the string returned by the following expression? What is the string?
4. In the following program, called ComputeResult, what is the value of result after each numbered line
executes?
System.out.println(result);
}
}
Answer:
si
se
swe
sweoft
swear oft
Exercises
1. Show two ways to concatenate the following two strings together to get the string "Hi, mom.":
2. Write a program that computes your initials from your full name and displays them.
Answer: ComputeInitials
if (Character.isUpperCase(myName.charAt(i))) {
myInitials.append(myName.charAt(i));
An anagram is a word or a phrase made by transposing the letters of another word or phrase; for example,
"parliament" is an anagram of "partial men," and "software" is an anagram of "swear oft." Write a program that
figures out whether one string is an anagram of another string. The program should ignore white space and
punctuation.
Answer: Anagram
public class Anagram {
workingCopy1 = workingCopy1.toLowerCase();
workingCopy2 = workingCopy2.toLowerCase();
workingCopy1 = sort(workingCopy1);
workingCopy2 = sort(workingCopy2);
return workingCopy1.equals(workingCopy2);
}
return dest.toString();
}
protected static String sort(String string) {
char[] charArray = string.toCharArray();
java.util.Arrays.sort(charArray);
System.out.println();
System.out.println("Testing whether the following "
+ "strings are anagrams:");
System.out.println(" String 1: " + string1);
System.out.println(" String 2: " + string2);
System.out.println();
if (areAnagrams(string1, string2)) {
System.out.println("They ARE anagrams!");
} else {
System.out.println("They are NOT anagrams!");
}
System.out.println();
}
}
Regular Expression:
Questions
1. What are the three public classes in the java.util.regex package? Describe the purpose of each.
2. Consider the string literal "foo". What is the start index? What is the end index? Explain what these
numbers mean.
Answer: Each character in the string resides in its own cell. Index positions point between cells. The
string "foo" starts at index 0 and ends at index 3, even though the characters only occupy cells 0, 1,
and 2.
3. What is the difference between an ordinary character and a metacharacter? Give an example of each.
Enclose the metacharacter within the quote expressions, \Q (at the beginning) and \E (at the end).
5. What do you call a set of characters enclosed in square brackets? What is it for?
Answer: This is a character class. It matches any single character that is in the class of characters
specified by the expression between the brackets.
6. Here are three predefined character classes: \d, \s, and \w. Describe each one, and rewrite it using
square brackets.
Answer:
7. For each of \d, \s, and \w, write two simple expressions that match the opposite set of characters.
Answer:
\d \D [^\d]
\s \S [^\s]
\w \W [^\w]
8. Consider the regular expression (dog){3}. Identify the two subexpressions. What string does the
expression match?
Answer: The expression consists of a capturing group, (dog), followed by a greedy quantifier {3}. It
matches the string "dogdogdog"
Ex-1
Write a programe to validate a user name. The regular expression pattern allows lower
case alphanumeric characters, allows '-', '_'. Incase if you want to support uppercase
characters then regular expression should be ^[a-zA-Z0-9_-]{6,14}$
Expected output:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
Pattern p = Pattern.compile(regex);
if (name == null) {
return false;
}
Matcher m = p.matcher(name);
return m.matches();
}
Ex-2:
Expected output:
package ASSIGNMENT;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.*;
public class email1 {
public static boolean isValid(String email)
{
String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\."+
"[a-zA-Z0-9_+&*-]+)*@" +
"(?:[a-zA-Z0-9-]+\\.)+[a-z" +
"A-Z]{2,7}$";
address.add("[email protected]");
address.add(" cric*7*&@yahoo.com");
address.add("JAVA2NOVICE.gmail.com");
for(String i : address){
if (isValid(i))
System.out.println(i + " - Yes");
else
System.out.println(i + " - No");
}
}
}
Ex-3:
to validate a password using regular expression. Here this regular expression allows
must contain one digit, one lower case char, one upper case char, some special chars,
length should be within 6 to 15 chars.
Is 'java2novice' a valid password? False
Is 'gabbarsingh' a valid password? false
Is 'Java2NOVICE$' a valid password? true
Is '234aBc#' a valid password? true
package ASSIGNMENT;
import java.util.regex.*;
public class password {
// Driver Code.
public static void main(String args[])
{
// Test Case 1:
String str1 = "java2novice";
System.out.println(isValidPassword(str1));
// Test Case 2:
String str2 = "gabbarsingh";
System.out.println(isValidPassword(str2));
// Test Case 3:
String str3 = "Java2NOVICE$";
System.out.println(isValidPassword(str3));
// Test Case 4:
String str4 = "A234aBc#";
System.out.println(isValidPassword(str4));
}
}