String & Array Questions in Java

Basic String & Array Questions in Java

String array questions are the most basic data structure question but having a good grip on this is a must for all programmers.

String & Array Questions in Java


String & Array Questions in Java:

1) WAP to create an array with 10 size and of int holding ability. Store values 1-10 in it. Using the length variable, access each element of the array and print it to the console. Create the array in 2 ways - one using the new operator and then storing the values individually, two by creating the array with the values directly in the array. Loop over the array using an index variable. Also, loop over it using for-each loop.

Ex:

int[] arr1 = new int[10]; // to create an empty array

int[] arr2 = {10,20,30}; // to create a literal array

for(int i = 0 ; i < arr1.length ; i++) // to loop over the array

System.out.println("value in "+i+"th box = "+arr1[i]);

for(int val : arr2)

System.out.println(val);

2) Create an array of ints with size 10. Insert 10-1 integer numbers into it (using a for loop). Print out its value to the console using the length variable (in another for loop) and for-each loop.

3) Create an array of ints with size 10. Insert 10 random integer values between 0-100 into it (using a for loop). Print out its value to the console using the length variable (in another for loop) and for-each loop.

4) Create a method called public static void test(int[] arr). Create literal array {10,20,30,40} in main(). Invoke test() and pass this literal array as parameter. Print out its value to the console using the length variable (in another for loop) and for-each loop in test().

5)Code an add() method that will add all the numbers given and return the result (use array of ints as param to the add() method).

Now compile and run TestStringMethods.java given as an example (when you run, pass 2 command line inputs like this - java TestStringMethods abcd pqrs). Go through the code to recap the methods on String we discussed in class and verify if you understand how it is working. In case you have any doubt, ask the Lab Instructor. Methods that you need to use are given in the bottom of the document as well. You can also go through other given .java files (TestStringMethods.java, TestMath.java,AddArrayElements.java)

6) Write a main() program to test methods of string to perform the 

following (directly create a string in main() like String str = “abcdef”):

a) check its length

b) print all the chars in string one at a time

c) convert string to an array of chars and print chars

d) convert string to uppercase and lowercase and print

e) take 2 strings and check if they are equal (create 2 strings directly in main())

f) take 2 strings and check which is bigger or lesser (alphabetical comparison)

g) take 2 strings and find out if one string occurs in another. Print the first occurring index

7) Basic String programs(all main() based programs): 

a) Create a String object using a new operator and using a string literal 

and print out its value using SOP to the console 

b) Create a String and print out its length to the console using SOP 

c) Take the input of a string from the command line (arg[0]) and print 

"You have a good name, <name concatenated>!" if the length of the string is < 12 chars and "You have a very long name, <name concatenated>!" if the length of the name is >=12 chars. If no input has been given, show an appropriate error message. 

d) Take a string input from arg[0]. Print the chars one at a time to the console. 

e) Take a string input from arg[0]. Print the even chars only. 

f) Take a string input from arg[0]. Print the alternate chars in one line and the remaining in another. 

g) Take string inputs from arg[0], arg[1]. Print "equal" if they have the same contents or "not equal" if they are not. 

h) Take string inputs from arg[0], arg[1]. Print whichever string is bigger then the other alphabetically 

i) Take string inputs from arg[0], arg[1]. Find out if arg[1] is present in arg[0] string and print if the search succeeds. 

j) Take string inputs from arg[0], arg[1]. Convert their cases and print them to the console. 

8) WAP in main() to test Math.sqrt(), Math.cbrt(), Math.random(), 

Math.pow() usage. See TestMath.java for sample code.

9) WAP (directly in main()) to create an array of strings with 5 colors as values. Use Math.random() to randomly print out 5 values from the array.

10) WAM to pass 2 arrays of ints to a method. The method should return the max value present across both the array elements.

11) WAM to pass 2 arrays of ints to a method. The method should return the average of the values across the 2 arrays. The avg returned should be exact and not an approximation.

12) WAM to pass 2 arrays of ints to a method. The method should return the second highest of the values across the 2 arrays.

13) WAM to pass 2 arrays of ints to a method. The method should return the max value present across both the array elements.

14) WAM to pass 2 arrays of ints to a method. The method should return the average of the values across the 2 arrays. The avg returned should be exact and not an approximation.

15) WAM to swap the first and last chars of a passed string and return it.

 char at length-1 + substring from 1, length-1 + char at 0

str.charAt(str.length()-1) + str.substr(1,str.length()-1) +str.charAt(0)

16) WAM to test whether a given string is a palindrome.


String & Array Questions in Java with Solution:

1) WAP to create an array with 10 size and of int holding ability. Store values 1-10 in it. Using the length variable, access each element of the array and print it to the console. Create the array in 2 ways - one using the new operator and then storing the values individually, two by creating the array with the values directly in the array. Loop over the array using an index variable. Also, loop over it using for-each loop.

Ex:

int[] arr1 = new int[10]; // to create an empty array

int[] arr2 = {10,20,30}; // to create a literal array

for(int i = 0 ; i < arr1.length ; i++) // to loop over the array

System.out.println("value in "+i+"th box = "+arr1[i]);

for(int val : arr2)

System.out.println(val);




public class Q1
{
	public static void main(String[] args)
	{
		int[] arr = new int[10];//int array with 10 size
		int[] arr1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

		for(int i = 0; i < arr.length; i++)//accessing all 10 element with 0-9 index
		{
			arr[i] = i+1; //storing 1 to 10 value
			System.out.print(arr[i]+" "); //printing value
		}

		System.out.println(); // for better readablity

		for(int i = 0; i < arr1.length; i++)//accessing all 10 element with 0-9 index
		{
			System.out.print(arr1[i]+" "); //printing value
		}

		System.out.println(); // for better readablity

		for(int x : arr1)
		{
			System.out.print(x+" "); // print all the values of arr1
		}
	}
}


2) Create an array of ints with size 10. Insert 10-1 integer numbers into it (using a for loop). Print out its value to the console using the length variable (in another for loop) and for-each loop.



public class Q2
{
	public static void main(String[] args)
	{
		int[] arr = new int[10]; // array of size 10
		//storing value using for loop
		for(int i = 0; i < arr.length; i++)
		{
			arr[i] = arr.length - i;
		}
		// printing value using another for loop
		for(int i = 0; i < arr.length; i++)
		{
			System.out.print(arr[i]+" ");
		}
		System.out.println(); //for readability
		// printing value using for each loop
		for(int x: arr)
		{
			System.out.print(x+" ");
		}

	}
}



3) Create an array of ints with size 10. Insert 10 random integer values between 0-100 into it (using a for loop). Print out its value to the console using the length variable (in another for loop) and for-each loop.




import java.util.Random;
public class Q3
{
	public static void main(String[] args)
	{
		int[] arr = new int[10]; // array of size 10

		//inserting 10 random value betwen 0 to 100

		for(int i = 0; i < arr.length; i++)
		{
			Random r = new Random(); //Istance of random class
			arr[i] = r.nextInt(101); //setting upper bound it will return o to 100
		}
		//another for loop for printing value
		for(int i = 0; i < arr.length; i++)
		{
			System.out.print(arr[i]+" ");
		}
		System.out.println();// readability
		//printing using for each loop
		for(int x: arr)
		{
			System.out.print(x+" ");
		}
	}
}


4) Create a method called public static void test(int[] arr). Create literal array {10,20,30,40} in main(). Invoke test() and pass this literal array as parameter. Print out its value to the console using the length variable (in another for loop) and for-each loop in test().




public class Q4
{
	public static void main(String[] args)
	{
		int[] arr = {10,20,30,40};  //letral array
		test(arr);
	}
	// static test method
	public static void test(int[] arr)
	{
		//printing value using for loop
		for(int i = 0; i <  arr.length; i++)
		{
			System.out.print(arr[i]+" ");
		}
		System.out.println();
		//using for each printing value
		for(int i: arr)
		{
			System.out.print(i+" ");
		}
	}
}



5)Code an add() method that will add all the numbers given and return the result (use array of ints as param to the add() method).Now compile and run TestStringMethods.java given as an example (when you run, pass 2 command line inputs like this - java TestStringMethods abcd pqrs). Go through the code to recap the methods on String we discussed in class and verify if you understand how it is working. In case you have any doubt, ask the Lab Instructor. Methods that you need to use are given in the bottom of the document as well. You can also go through other given .java files (TestStringMethods.java, TestMath.java,AddArrayElements.java)




public class Q5
{
	public static void main(String[] args)
	{
		// length of argument
		int len = args.length;
		int[] arr = new int[len];
		for(int i = 0; i < len; i++)//array of arrgument
		{
			int value = Integer.parseInt(args[i]);
			arr[i] = value; //storing value to arr
		}

		long result = add(arr);
		System.out.println(result);
	}

	// test method
	public static long add(int[] arr)
	{
		long sum = 0;
		for(int i = 0; i < arr.length; i++)
		{
			sum += arr[i];
		}
		return sum;
	}

}
//if we will pass string value argument we will get exception in above code


6) Write a main() program to test methods of string to perform the 

following (directly create a string in main() like String str = “abcdef”):

a) check its length

b) print all the chars in string one at a time

c) convert string to an array of chars and print chars

d) convert string to uppercase and lowercase and print

e) take 2 strings and check if they are equal (create 2 strings directly in main())

f) take 2 strings and check which is bigger or lesser (alphabetical comparison)

g) take 2 strings and find out if one string occurs in another. Print the first occurring index




public class Q6
{
	public static void main(String[] args)
	{
		String str = "abcdef"; // String letral will create string in string pool
		System.out.println("str String: "+str);//readability
		int len = str.length(); //a. getting length
		System.out.println("length of string is: "+len); // its length

		for(int i = 0; i < len; i++ ) //b. print all the chars in string one at a time
		{
			System.out.println(i+" itteration "+str.charAt(i)+"  ");
		}
		//c. convert string to array of chars
		char[] c = str.toCharArray();
		System.out.println("string to array of chars: ");
		for(int i = 0; i < len; i++ )
		{
			System.out.println(c[i]);
		}
		//d. string to uppercase and lowercase
		String uppercase = str.toUpperCase();
		String lowercase = str.toLowerCase();
		//print it
		System.out.println("uppercase: "+uppercase+"\nlowercase: "+lowercase);

		//e. take 2 strings and check if they are equal
		String str1 = "abcdef";
		String str2 = "abcdefg";

		System.out.println("is string equal: "+str1.equals(str)); //true
		System.out.println("is string equal: "+str1.equals(str2)); //false

		//f. take 2 strings and check which is bigger or lesser
		System.out.println("Compare string str and uppercase: "+str.compareTo(uppercase)); //32
		System.out.println("Compare string uppercase and str: "+uppercase.compareTo(str)); //-32
		System.out.println("Compare string lowercase and str: "+lowercase.compareTo(str)); //0

		//g. take 2 strings and find out if one string occurs in other. Print the first occurring index
		String str3 = "bc";
		int index = str.indexOf(str3);
		if(index != -1)
		System.out.println("index of first occurance is: "+index);
		else
		System.out.println("no occurance");


	}
}


7) Basic String programs(all main() based programs): 

a) Create a String object using a new operator and using a string literal 

and print out its value using SOP to the console 

b) Create a String and print out its length to the console using SOP 

c) Take the input of a string from the command line (arg[0]) and print 

"You have a good name, <name concatenated>!" if the length of the string is < 12 chars and "You have a very long name, <name concatenated>!" if the length of the name is >=12 chars. If no input has been given, show an appropriate error message. 

d) Take a string input from arg[0]. Print the chars one at a time to the console. 

e) Take a string input from arg[0]. Print the even chars only. 

f) Take a string input from arg[0]. Print the alternate chars in one line and the remaining in another. 

g) Take string inputs from arg[0], arg[1]. Print "equal" if they have the same contents or "not equal" if they are not. 

h) Take string inputs from arg[0], arg[1]. Print whichever string is bigger then the other alphabetically 

i) Take string inputs from arg[0], arg[1]. Find out if arg[1] is present in arg[0] string and print if the search succeeds. 

j) Take string inputs from arg[0], arg[1]. Convert their cases and print them to the console. 




public class Q7
{
	public static void main(String[] args)
	{
		//a. Create a String object using new operator and using a string literal and print out its value using SOP to the console
		String str = new String("abc");
		String str1 = "def";
		System.out.println("new oprator string: "+str+"\nString literal: "+str1);
		//b. String Length
		System.out.println("string length of str String is: "+str.length());
		//c. input from command line
		if(args.length == 0)// if no argument
		{
			System.out.println("argument required");
		}
		else
		{
			String name = "";
			for(int i = 0; i < args.length; i++)//if name contains space
			{
				name = name+" "+args[i];//concatinate first name lastname middle name sirname etc.
				//space used to seprate all name in name string
			}
			if(name.length() < 12)
			System.out.println("You have a good name, "+name);
			else
			System.out.println("You have a very long name,"+name);
		}
		//d) Take a string input from arg[0]. Print the chars one at a time
		String input = args[0];
		for(int i = 0; i < input.length(); i++ )
		{
			System.out.println(i+" itteration "+input.charAt(i)+"  ");
		}
		//e) Take a string input from arg[0]. Print the even chars only
		for(int i = 1; i < input.length(); i += 2 )
		{
			System.out.println((1+i)+" char at even pos "+input.charAt(i)+"  ");
		}
		//f) g input from arg[0]. Print the alternate chars in one line and the remaining in another.
		for(int i = 0; i < input.length(); i += 2 )
		{
			System.out.print(input.charAt(i)+"  ");
		}
		System.out.println();//to print emptyline
		for(int i = 1; i < input.length(); i += 2 )
		{
			System.out.print(input.charAt(i)+"  ");
		}
		System.out.println();
		//g) Take string inputs from arg[0], arg[1]. Print "equal" if they have the same contents or "not equal" if they are not.
		String input1 = args[1];
		if(input.equals(input1))
		System.out.println(input+" is equal to "+input1);
		else
		System.out.println(input+" is not equal to "+input1);
		//h) alphabaticall bigger string in arg[0] and arg[1]
		if(input.compareTo(input1) > 0)
		System.out.println("bigger String alphabatically is: "+input);
		else
		System.out.println("bigger String alphabatically is: "+input1);
		//i) Take string inputs from arg[0], arg[1]. Find out if arg[1] is present in arg[0] string and print if the search succeeds
		if(input.contains(input1))
		System.out.println("arg[1] is present in arg[0]");
		else
		System.out.println("arg[1] is not present in arg[0]");
		//j) Take string inputs from arg[0], arg[1]. Convert their cases and print them to the console.
		for(int i = 0; i < input.length(); i++ ) //  for arg[0]
		{
			if(input.charAt(i) >= 'a' && input.charAt(i) <= 'z')
			System.out.print(Character.toUpperCase(input.charAt(i)));
			else
			System.out.print(Character.toLowerCase(input.charAt(i)));
		}
		System.out.print(" ");
		for(int i = 0; i < input1.length(); i++ ) // for arg[1]
		{
			if(input1.charAt(i) >= 'a' && input1.charAt(i) <= 'z')
			System.out.print(Character.toUpperCase(input1.charAt(i)));
			else
			System.out.print(Character.toLowerCase(input1.charAt(i)));
		}
	}
}



8) WAP in main() to test Math.sqrt(), Math.cbrt(), Math.random(), 


public class Q8
{
	public static void main(String[] args)
	{
		System.out.println(Math.sqrt(4));//2.0
		System.out.println(Math.cbrt(27));//3.0
		System.out.println(Math.random());//random value 0<value<1
		System.out.println(Math.pow(2,4));// 16.0
	}
}




9) WAP (directly in main()) to create an array of strings with 5 colors as values. Use Math.random() to randomly print out 5 values from the array.



public class Q9
{
	public static void main(String[] args)
	{
		String[] colors = {"Red","green","blue","Black","white"};
		int i = (int) (5.0 * Math.random());
		System.out.println(colors[i]);
	}
}



10) WAM to pass 2 arrays of ints to a method. The method should return the max value present across both the array elements.



public class Q10
{
	public static void main(String[] args)
	{
		int[] arr = {1,8,7,87,34};
		int[] arr1 = {67,65,23,45,56,21,19};
		int biggestNo = maxValueInTwoArray(arr, arr1);
		System.out.println("max value present across both the array element: "+biggestNo);

	}

	//method for max value in two array
	public static int maxValueInTwoArray(int[] arr1, int[] arr2)
	{
		int max = 0, max1 = 0;
		for(int i = 0; i < arr1.length-1; i++)
		{
			if(arr1[i]>arr1[i+1])
			max = arr1[i];
			else
			max = arr1[i+1];
		}
		for(int i = 0; i < arr2.length-1; i++)
		{
			if(arr2[i]>arr2[i+1])
			max1 = arr2[i];
			else
			max1 = arr2[i+1];
		}
		if(max>max1)
		return max;
		else
		return max1;
	}
}



11) WAM to pass 2 arrays of ints to a method. The method should return the average of the values across the 2 arrays. The avg returned should be exact and not an approximation.


public class Q11
{
	public static void main(String[] args)
	{
		int[] arr = {1,8,7,87,34};
		int[] arr1 = {67,65,23,45,56,21,19};
		double average = averageOfTwoArray(arr, arr1);
		System.out.println(" average of the values across the 2 arrays: "+average);

	}

	//method for  average of the values across the 2 arrays
	public static double averageOfTwoArray(int[] arr1, int[] arr2)
	{
		int sum = 0, sum1 = 0;
		for(int i = 0; i < arr1.length; i++)
		{
			sum += arr1[i];
		}
		for(int i = 0; i < arr2.length; i++)
		{
			sum1 += arr2[i];
		}
		return (double)(sum + sum1)/(arr1.length + arr2.length);
	}
}




12) WAM to pass 2 arrays of ints to a method. The method should return the second highest of the values across the 2 arrays.


import java.util.Arrays;
public class Q12
{
	public static void main(String[] args)
	{
		int[] arr = {1,8,7,87,34};
		int[] arr1 = {67,65,23,45,56,21,19};
		int secondHighest = secondHighestInTwoArray(arr, arr1);
		System.out.println(secondHighest);

	}
	//method to return  second highest of the values across the 2 arrays.
	public static int secondHighestInTwoArray(int[] arr, int[] arr1)
	{
		int len = arr.length + arr1.length;
		int[] res  = new int[len];
		int i = 0;
		for(int x : arr)
		{
			res[i] = x;
			i++;
		}
		for(int x : arr1)
		{
			res[i] = x;
			i++;
		}
		Arrays.sort(res);
		return res[len-2];
	}
}




13) WAM to pass 2 arrays of ints to a method. The method should return the max value present across both the array elements


public class Q13
{
	public static void main(String[] args)
	{
		int[] arr = {1,8,7,87,34};
		int[] arr1 = {67,65,23,45,56,21,19};
		int biggestNo = maxValueInTwoArray(arr, arr1);
		System.out.println("max value present across both the array element: "+biggestNo);

	}

	//method for max value in two array
	public static int maxValueInTwoArray(int[] arr1, int[] arr2)
	{
		int max = 0, max1 = 0;
		for(int i = 0; i < arr1.length-1; i++)
		{
			if(arr1[i]>arr1[i+1])
			max = arr1[i];
			else
			max = arr1[i+1];
		}
		for(int i = 0; i < arr2.length-1; i++)
		{
			if(arr2[i]>arr2[i+1])
			max1 = arr2[i];
			else
			max1 = arr2[i+1];
		}
		if(max>max1)
		return max;
		else
		return max1;
	}
}



14) WAM to pass 2 arrays of ints to a method. The method should return the average of the values across the 2 arrays. The avg returned should be exact and not an approximation.




public class Q14
{
	public static void main(String[] args)
	{
		int[] arr = {1,8,7,87,34};
		int[] arr1 = {67,65,23,45,56,21,19};
		double average = averageOfTwoArray(arr, arr1);
		System.out.println(" average of the values across the 2 arrays: "+average);

	}

	//method for  average of the values across the 2 arrays
	public static double averageOfTwoArray(int[] arr1, int[] arr2)
	{
		int sum = 0, sum1 = 0;
		for(int i = 0; i < arr1.length; i++)
		{
			sum += arr1[i];
		}
		for(int i = 0; i < arr2.length; i++)
		{
			sum1 += arr2[i];
		}
		return (double)(sum + sum1)/(arr1.length + arr2.length);
	}
}


15) WAM to swap the first and last chars of a passed string and return it.

 char at length-1 + substring from 1, length-1 + char at 0

str.charAt(str.length()-1) + str.substr(1,str.length()-1) +str.charAt(0)



public class Q17
{
	public static void main(String[] args)
	{
		String s = "Hero";
		String s1 = swapFirstLastChar(s);
		System.out.println(s1);
	}
	//method to swap first and last chars of a passed string and return it.char at length-1 + substring from 1, length-1 + char at 0
	public static String swapFirstLastChar(String s)
	{
		return s.charAt(s.length()-1)+s.substring(1,s.length()-1)+s.charAt(0);
	}
}



16) WAM to test whether a given string is a palindrome.



public class Q18
{
	//main method
	public static void main(String[] args)
	{
		String s = "madam";
		String s1 = "Hero";
		System.out.println("is the string "+s+" palindrome? "+isPalindrome(s) );
		System.out.println("is the string "+s1+" palindrome? "+isPalindrome(s1) );
	}
	//method to test whether a given string is a palindrome
	public static boolean isPalindrome(String s)
	{
		StringBuilder sb = new StringBuilder(s);
		if(s.equals(sb.reverse().toString())) //stringbuilder is not a string we have to convert it to sring
			return true;
		return false;
	}
}


Learn Array Concepts in Java from Scratch:



Learn String Concepts in Java from Scratch:






No comments:

For Query and doubts!

Powered by Blogger.