Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
91 views

Programming

The document contains 10 questions and answers related to Java string operations and manipulation. Some key examples include: 1) Removing duplicate elements from an arraylist and array using for loops and HashSet respectively. 2) Sorting a string without using string methods by converting it to a character array and using a bubble sort approach. 3) Checking if two strings are anagrams by sorting the characters of each and comparing. 4) Finding the maximum occurring character in a string by storing counts in a HashMap. 5) Splitting a string on a delimiter using the split() method and checking for the delimiter's presence.

Uploaded by

Shashank Gupta
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)
91 views

Programming

The document contains 10 questions and answers related to Java string operations and manipulation. Some key examples include: 1) Removing duplicate elements from an arraylist and array using for loops and HashSet respectively. 2) Sorting a string without using string methods by converting it to a character array and using a bubble sort approach. 3) Checking if two strings are anagrams by sorting the characters of each and comparing. 4) Finding the maximum occurring character in a string by storing counts in a HashMap. 5) Splitting a string on a delimiter using the split() method and checking for the delimiter's presence.

Uploaded by

Shashank Gupta
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/ 15

Qus-1 Write a Java program to remove duplicate elements from an array list without using

collections (without using set) ??==================


Ans- ArrayList<Object> al = new ArrayList<Object>();
al.add("java");
al.add('a');
al.add('b');
al.add('a');
for(int i=0;i<al.size();i++){
for(int j=i+1;j<al.size();j++){
if(al.get(i).equals(al.get(j))){
al.remove(j);
j--;
}}}
sopln(al);
}
}
Qus-2 Write a Java program to remove duplicate elements from an array using
Collections (Linkedhashset)
Ans- List<String> arraylist = new ArrayList<String>();

arraylist.add("instanceofjava");
arraylist.add("Interview Questions");
arraylist.add("instanceofjava");

HashSet<String> hashset = new HashSet<String>();


hashset.addAll(arraylist);
arraylist.clear();
arraylist.addAll(hashset );
System.out.println("After Removing duplicate elements:"+arraylist);
}
}

Qus-3 Sorting String without using String methods ?==============


Ans- String str = "edcba";
int j=0;
char temp=0;
char[] chars = str.toCharArray();{
for (int i = 0; i <chars.length; i++) {
for ( j = 0; j < chars.length; j++) {
if(chars[j]>chars[i]){
temp=chars[i];
chars[i]=chars[j];
chars[j]=temp;
} }}

for(int k=0;k<chars.length;k++){
System.out.println(chars[k]);
} }
} }

Qus-4 Sort the String using string method ??============


Ans- String original = "edcba";

char[] chars = original.toCharArray();

Arrays.sort(chars);

String str = new String(chars);


System.out.println(str);
} }

Qus-5 Count the no. of Occurance of a character in a string ?=============


Ans-

repeat("i love my india");


}
public static void repeat(String str)
{

HashMap<Character, Integer>map=new HashMap<Character,Integer>();


char arr[]=str.toCharArray();
for (Character c : arr) {
if(map.containsKey(c)){
map.put(c, map.get(c)+1);
}else
{
map.put(c, 1);
}
}
System.out.println(map);
}
}

Qus-6 Reverse a String Without using String API?=============


Ans-String str="ajay";
String revstring="";

for(int i=str.length()-1;i>=0;--i){
revstring +=str.charAt(i);
}

System.out.println(revstring);
} }

Qus-7 check string is palindrome or not ?=======================


ans- String str="MADAM";
String revstring="";
for(int i=str.length()-1;i>=0;--i){
revstring +=str.charAt(i);
}
System.out.println(revstring);
if(revstring.equalsIgnoreCase(str)){
System.out.println("The string is Palindrome");
}
else{
System.out.println("Not Palindrome");
}}}
Qus-8 Java Program to count number of words in a String.?=================
Ans- String s="";
int count=0;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a String");
s=in.nextLine();
char ch[]= new char[s.length()];
for(int i=0;i<s.length();i++)
{
ch[i]= s.charAt(i);
if( ((i>0)&&(ch[i]!=' ')&&(ch[i-1]==' ')) || ((ch[0]!=' ')&&(i==0)) )
count++;
}
System.out.println("Number of words in given String: "+count);
}

Qus-9 Java program to return maximum occurring character in the input string=======
ans- repeat("i love my india");
}
public static void repeat(String str)
{
HashMap<Character, Integer>map=new HashMap<Character,Integer>();
char arr[]=str.toCharArray();
for (Character c : arr) {
if(map.containsKey(c)){
map.put(c, map.get(c)+1);
}else
{
map.put(c, 1);
}
}
System.out.println(map);
}
}
public static void main(String[] args) {
String str1=MaxOccuredChar("instanceofjava");
System.out.println(str1);
String str2=MaxOccuredChar("aaaabbbccc");
System.out.println(str2);
String str3=MaxOccuredChar("ssssiiinnn");
System.out.println(str3);
String str4=MaxOccuredChar("jaaaavvvvvvvvaaaaaaaaaa");
System.out.println(str4);

Qus-10 Java Program to check two strings are anagrams or not ?================
Ans-import java.util.Arrays;
public class CheckAnagramStrings {
private static boolean isAnagram(String str1, String str2) {
if (str1.length() != str2.length()) {
return false;
}
str1 = sortCharacters(str1);
str2 = sortCharacters(str2);
return str1.equals(str2);
}

private static String sortCharacters(String str) {


char[] charArray = str.toLowerCase().toCharArray();
Arrays.sort(charArray);
return String.valueOf(charArray);
}

public static void main(String[] args) {

String str1 = "bemru";


String str2 = "mureb";

if (isAnagram(str1, str2)) {
System.out.println(str2 + " is anagram of " + str1);
} else {
System.out.println("Strings are not anagrams.");
}}

}op=mureb is anagram of bemru

****************************************************************
****************************************************************
qus-11 How to split a String in java using String Split() method: ?
ans-String str = "Instance-of-Java";
String strarray[]=str.split("-");

for (int i = 0; i < strarray.length; i++) {


System.out.println(strarray[i]);
}}}
Output:
Instance
of
Java
Qus-12 Java Program to split a String using String Split() method: Before splitting check whether
deliminator is there or not.
ans-class SplitString{
public static void main(String [] args){
String str = "Instance-of-Java";
if(str.contains(".")){

//(". ") for print if not delimeter.

String strarray[]=str.split("-");
for (String string : strarray) {
System.out.println(string);
}
}
else{
System.out.println("String does not contains specified char so splitting is not possible");
}}}
Output:String does not contains specified char so splitting is not possible .

qus13 Java Program to Remove non ASCII chars from String?


ans-String str = "Instance??of??java";
System.out.println(str);
str = str.replaceAll("[^\\p{ASCII}]", "");
System.out.println("After removing non ASCII chars:");
System.out.println(str);
}}
Qus-14 Java Program to Remove multiple spaces in a string?==============
ans-String str = "Instance of java";
StringTokenizer st = new StringTokenizer(str, " ");
StringBuffer sb = new StringBuffer();
while(st.hasMoreElements()){
sb.append(st.nextElement()).append(" ");
}
System.out.println(sb.toString().trim());
}}}

Output:
Instance of java

Qus-15 Java Program to Remove all occurrences of a string ?


ans-class RemoveCharString{

public static void main(String [] args){

String str = "Java";


str = str.replace("a", "");
System.out.println(str);
}}
Output:
Jv

qus-16 Java Program to Replace First occurance of Specific index char in a String ?
ans- class RemoveCharString{
public static void main(String [] args){
String str = "Java";
//String result = str.substring(0, index) + str.substring(index+1);
String result = str.substring(0, 1) + str.substring(1+1);
System.out.println(result);
}}
Output:
Jva
qus-17 Java Program to Remove all Numbers from a string.??
ans- class RemoveNumberString{
public static void main(String [] args){
String str = "Instance12ofjava143";
str = str.replaceAll("[0-9]","")
System.out.println(str);
}}
Output:
Instanceofjava

qus-18 Java program to count the number of vowels,digit,blanks in a string.=========


ans- int vowels = 0, digits = 0, blanks = 0; char ch;
System.out.println("Please enter a String");
Scanner in = new Scanner(System.in);
String testString= in.nextLine();
for(int i = 0; i < testString.length(); i ++)
{
ch = testString.charAt(i);
if(ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' ||
ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
vowels ++;
else if(Character.isDigit(ch))
digits ++;
else if(Character.isWhitespace(ch))
blanks ++;
}

System.out.println("Vowels : " + vowels);


System.out.println("Digits : " + digits);
System.out.println("Blanks : " + blanks);

}
Output:
Please enter a String
vowels and consonants
Vowels : 6
Digits : 0
Blanks : 2

qus-19 Java Interview Program to find second highest number in an integer array without sorting
the elements.
ans- int numbers[] = {6,3,37,12,46,5,64,21};
int highest = 0;
int second_highest = 0;

for(int n:numbers){

if(highest < n){

second_highest = highest;
highest =n;

} else if(second_highest < n){

second_highest = n;

}
System.out.println("First Max Number: "+highest);
System.out.println("Second Max Number: "+second_highest);

}
Output:

First Max Number: 64


Second Max Number: 46

qus-20 Java Interview Program to find second highest number in an integer array by sorting the
elements.?
ans-int numbers[] = {6,3,37,12,46,5,64,21};

Arrays.sort(numbers);

System.out.println("Largest Number: "+numbers[numbers.length-1]);


System.out.println("Second Largest Number: "+numbers[numbers.length-2]);
}

qus-21 how to split a string from a given statements ??=======


ansString str = "Gold:Stocks:Fixed Income:Commodity:Interest Rates";
String[] st = str.split(":");

System.out.println(st.length);

for(String s: st){

System.out.println(s);

}
OutPut
5
Gold
Stocks
Fixed Income
Commodity

qus-22 How to Convert String to Integer to String in Java with Example

ans-

int i = Integer.parseInt("12");
System.out.println("i: " + i);

Qus-23 write program for padding ??

ans--

public class PAdding {


public static void main(String[] args) {
System.out.println(Padding("ajay", 5, "aaa"));
}

public static String Padding(String str,int len,String pad) {


String ss=null;

if(len<str.length())
{
return str.substring(0,len);
}
else if(len>str.length()){
int k=0;
int diff=len-str.length();
while(k<diff){
str=str+pad;
k=k+1;
}return str;
}else{
return str;}}}

qus-- what will be the output ?/


public class Demo {
void test(){
String a="abc";
StringBuffer b=new StringBuffer("abc");
int c=10;
test2(a,b,c);
System.out.println(a+" "+b+" "+c);
}
void test2(String a,StringBuffer b,int c){
a=a+"xyz";
b=b.append("xyz");
c=c+10;

public static void main(String[] args) {

new Demo().test();

}
}

op- abc abcxyz 10

Qus- how to iterate key and values from map using foreach loop?=======
ans-HashMap<Integer,String> map=new HashMap<Integer,String>();
map.put(101, "a");
map.put(102, "b");
map.put(103, "c");
for(Map.Entry entry:map.entrySet()){
sopln(entry.getKey()+" "+entry.getValue());
}
}
}

OR SECOND WAY==

HashMap<Integer,String> map=new HashMap<Integer,String>();


map.put(101, "a");
map.put(102, "b");
map.put(103, "c");
/*Set set=map.entrySet();
Iterator itr=set.iterator();
while(itr.hasNext()){
Map.Entry<Integer,String> entry=(Map.Entry<Integer,String>)itr.next();
Integer key=entry.getKey();
String val=entry.getValue();
System.out.println(key+" "+val);
}
}
}

You might also like