CoreJava PracticeLab
CoreJava PracticeLab
Note: Hints, Logic and algorithm WILL NOT be provided in the actual assessment. Only the problem statement will be given.
Exercise 1: Create a class with a method which can calculate the sum of first n natural numbers which are divisible by 3 or 5. Method Name Method Description Argument Return Type Logic calculateSum Calculate Sum int n int-sum Calculate the sum of first n natural numbers which are divisible by 3 or 5.
Exercise 2: Create a class with a method to find the difference between the sum of the squares and
the square of the sum of the first n natural numbers. Method Name Method Description Argument Return Type Logic calculateDifference Calculate the difference int n int - Sum Find the difference between the sum of the squares of the first n natural numbers and the square of their sum. For Example if n is 10,you have to find (1^2+2^2+3^2+.9^2+10^2)(1+2+3+4+5+9+10)^2
Exercise 3: Create a class containing a method to create the mirror image of a String. The method should return the two Strings separated with a pipe(|) symbol . Method Name Method Description Argument Return Type Logic getImage Generate the mirror image of a String and add it to the existing string. String String Accepts One String Find the mirror image of the String Add the two Strings together separated by a pipe(|) symbol. For Example Input : EARTH Output : EARTH|HTRAE Hint: Use StringBuffer API (Ex: For this problem reverse method in Stringbuffer can be used) Note: Learn the other APIs in StringBuffer
Exercise 4: Create a method to check if a number is an increasing number Method Name Method Description Argument Return Type Logic checkNumber Check if a number is an increasing number int number boolean A number is said to be an increasing number if no digit is exceeded by the digit to its left. For Example : 134468 is an increasing number
Example 5: Create a method to check if a number is a power of two or not Method Name Method Description Argument Return Type Logic checkNumber Checks if the entered number is a power of two or not int n boolean Check if the input is a power of two. Ex: 8 is a power of 2
Example 6: A school offers medals to the students of tenth based on the following criteria If(Marks>=90) : Gold If(Marks between 80 and 90) : Silver If(Marks between 70 and 80) : Bronze Note: Marks between 80 and 90 means marks>=80 and marks<90 Write a function which accepts the marks of students as a Hashmap and return the details of the students eligible for the medals along with type of medal. The input hashmap contains the student registration number as key and mark as value. The output hashmap should contain the student registration number as key and the medal type as value. Method Name Method Description Argument Return Type Logic getStudents Generate the list of students eligible for scholarship Hashmap Hashmap The method should return the details of the students eligible for the medals along with the medal type.
Example 7: Create a method which accepts a String and replaces all the consonants in the String with the next alphabet. Note: Consonant refers to all alphabets excluding vowels Method Name Method Description Argument Return Type Logic alterString Replace consonants String String Return the String replacing all the consonants with the next character. For Example :JAVA should be changed as KAWA
Example 9: Create a method which can perform the following operations on two String objects S1 and S2. The output of each operation should be added to an arraylist and the arraylist should be returned.(Assume S2 is of smaller size) Examples for below statements are shown in the Logic part 1. Character in each alternate index of S1 should be replaced with S2 2. If S2 appears more than once in S1, replace the last occurrence of S2 in S1 with the reverse of S2, else return S1+S2 3. If S2 appears more than once in S1, delete the first occurrence of S2 in S1, else return S1 4. Divide S2 into two halves and add the first half to the beginning of the S1 and second half to the end of S1. Note: If there are odd number of letters in S2, then add (n/2)+1 letters to the beginning and the remaining letters to the end. (n is the number of letters in S2) 5. If S1 contains characters that is in S2 change all such characters to *
modifyStrings Perform the above mentioned actions on a String String,String Arraylist Do the above mentioned actions on the entered String. For Example S1=JAVAJAVA S2=VA 1. VAAVAAVAAVAA (J replaced with VA,
Example 10: Create a method that accepts a number and modifies it such that the each of the digit in the newly formed number is equal to the difference between two consecutive digits in the original number. The digit in the units place can be left as it is. Note: Take the absolute value of the difference. Ex: 6-8 = 2 Method Name Method Description Argument Return Type Logic modifyNumber Accepts a number and modify it as per the requirement int number1 int Accept a number and modify it such that the each of the digit in the newly formed number is equal to the difference between two consecutive digits in the original number. For example. Input: 45862 Output:13242 Algorithm: Convert number into String Extract each char using charAt method Convert char to int and find the difference Create new StringBuffer object and keep adding the difference Finally convert StringBuffer to int
Example 12: You are asked to create an application for registering the details of jobseeker. The requirement is: Username should always end with _job and there should be atleast minimum of 8 characters to the left of _job. Write a function to validate the same. Return true in case the validation is passed. In case of validation failure return false. Method Name Method Description Argument Return Type Logic validateUserName Checks if the username is valid String userName boolean Checks if the username ends with _job and contains at least 8 characters to the left of _job. If valid return true. Else return false.
Example 13: Create a method that can accept an array of String objects and sort in alphabetical order. The elements in the left half should be completely in uppercase and the elements in the right half should be completely in lower case. Return the resulting array. Note: If there are odd number of String objects, then (n/2)+1 elements should be in UPPPERCASE Method Name Method Description Argument Return Type Logic getArrayList Converts the String array to ArrayList and sorts it String []elements String [] modifiedArray Load the elements in to an ArrayList ,sort it, convert the left half element to uppercase and right half elements to lower case . Hint : 1. Use Collection 2. Use String API
Example 14: Create a method which can remove a List from another List Method Name Method Description Argument Return Type Logic removeElements Removes the elements in one list that is present in the second list also. List<String> list1, List<String> list2; List- ArrayList contains the resulting List after the removal process. Accept two List objects list1 and list2 and remove the elements from list1 that are present in list2. This should be done in single step process without using loop. Hint: Use the List API which removes all the items in List1 which are contained in List2
10
Example 16: Create a method which accepts an array of numbers and returns the numbers and their squares in an HashMap Method Name Method Description Argument Return Type Logic getSquares Accepts a list of numbers and return their squares int[] Map Iterate through the list, find the square of each number and add the elements to a map object with the number as the key and the square as the value.
Example 17: Create a method which accepts the id and the age of people as a Map and decide if they are eligible for vote. A person is eligible for vote if his age is greater than 18. Add the IDs of all the eligible persons to list and return the list. (Assume date is in DD/MM/yyyy format) Method Name Method Description Argument Return Type Logic votersList Generate the list of voters based on the ages of the people Map List Accept a map with ID as key and Date of Birth as value and check if the person is eligible to vote. A person is eligible for vote for if his age is greater than 18. If the person is eligible add his ID to the list. Hint: Use Calendar API and SimpleDateFormat
11
Example 19: Create a method which accepts an integer array and removes all the duplicates in the array. Return the resulting array in descending order Method Name Method Description Argument Return Type Logic modifyArray Remove duplicates int [] int [] Remove the duplicate elements in the array and sort it in descending order Hint: 1. Use Collection API (TreeSet) to remove duplicates and sort the result in ascending order 2. Create a new array, iterate through elements in TreeSet and add it in the reverse order
12
Example 21: A String contains a list of states and capitals. Write a method which can parse the string and return the states and capitals as map with state as key and capital as value. The String is in the below format. The state and capital is separated by a delimiter (del1). There will be multiple state-capital pairs and each state capital pair is separated by another delimiter (del2). Ex: Input will be tamilnadu||chennai-karanataka||bengaluru. Here, || will be provided as del1 and - will be provided as del2. Method Name Method Description Argument Return Type Logic getStates Accepts the states and capitals as a String and return a map String data, char del1,char del l2 Map Parse the string based on the delimiters and load it to a map with the state name as key and capital as value. Hint: Use Stringtokenizer or split method in String class. Try both the above ways to get familiarized with both APIs
13
Example 23: Create a method which can perform a particular String operation based on the users choice. The method should accept the String object and the users choice and return the output of the operation. Options are A: Add the String to itself B: Replace alternate positions with * C: Remove duplicate characters in the String D: Change alternate characters to upper case Method Name Method Description Argument Return Type Logic changeString Modify the string based on user choice String string, char ch String Perform the required operation based on the user choice and return the resulting string
14
Example 25: Create a method which accepts two Arraylist containing characters. Merge both arrays lists, sort the elements in the resulting list and return the resulting array. Method Name Method Description Argument Return Type Logic mergeData Merge two arraylist , sort it and return the result as an integer array. List, List char[] Merge both arrays lists, sort the elements in the resulting list and return it as a char array.
Example 26: Create a method that searches for a particular String in a List. If found, the element should be replaced with a string having only half of the characters in the actual string Method Name Method Description Argument Return Type modifyElement Search for an element in the arraylist and modifies it. List<String> arrayList , String element List
15
Example 27: Create a method to find the sum of the first n even numbers that are divisible by 3 and 8 Method Name Method Description Argument Return Type Logic findSum Find the sum of first n even numbers that are divisible by 3 and 8 Int Int Sum of the multiples of first n even numbers that are divisible by 3 and 8
Example 28: Create a method to find the sum of the cubes of the digits of an n digit number Method Name Method Description Argument Return Type Logic findSum Find the sum cubes of the digits of an n digit number Int Int Return the sum of cubes of the digits of an n digit number Example Input : 123 Output : 1^3+2^3+3^3= 1+8+27=36 Hint: Use %(mod) operator to separate each digit
16
Example 30: A company requires each employee to maintain a secret code. The secret code needs to pass certain validation for getting accepted. The validation rules are as given 1. 2. 3. 4. 5. 6. The secret code should be six characters long The first three characters should be cod (Use .startsWith method) There should be at least one digit in the code (Use .isDigit) The first character should always be an upper case letter(Use isUpperCase) The code should contain only alphabets and digits. The number of upper case letters should be greater than lower case letters. Return true if the above validation is passed. Method Name Method Description Argument Return Type Logic validateCode Validate the entered code as per the given validation rules String code boolean Validate the entered code Hint: Use the String API methods to extract each character
17
sumOfFactorial Calculate sum int n int 1. Generate the first n elements in the Fibonacci series 2. Find the factorial of each element 3. Find the sum of the factorial
Example 32: A company transmits its String data over the network as encrypted data. The encryption logic is as shown given below. For a String ad the logic is as given a a+9=j dd+9=m So the encrypted word would be jm. If on addition of 9 results in a char greater than z (ASCII value 122) do the encryption in a cyclic manner starting from a. So if any character is z it should be (z+9) which is equal to 127>122. In this case the character would be 9 character starting from a which i so for adz the encrypted value should be adi
encryptString Encrypt the entered string String String 1. Perform the arithmetic operation of char data. 2. For example Assume char a=b; a++; Now the value of a will be c. This is
18
Example 33: A sales company keeps track of the product purchased and sold. The company needs to make sure that the sale date is always after the purchase date. Write a method to verify this Method Name Method Description Argument Return Type Logic compareDates Comparing the purchase date and selling date String purchaseDate, String sellingDate boolean 1. Convert the string to Date objects 2. Return true if the selling date comes after the purchase date
Example 34: A company used to keep the record of the employees in two different branches separately. There are some employees who work in both the location. The company needs to keep track of the employee working in both the branches. Write a method to accept the two lists containing the names of the employees working in the two branches. The method should find out the names of employees present in both the list and return the names as a sorted array Method Name Method Description Argument Return Type Logic getEmployees Get the names of employees working two different branches List branch1, List branch2 String [] Find the common names of the employees in both the lists
Example 35: In a school there are some teachers who handle two subjects (Maths and English). When the feedback was taken their feedback was present in both Maths Feedback as well as English Feedback. Write a method to create a consolidated feedback for the teachers for English and Maths. For those taking both the subjects the highest feedback is taken. Write a method to accept two maps and return a Map object containing the feedbacks of all teachers in maths and English. Note: HashMap contains Key - Teachers name of type String Value Feedback of type Integer
19
getConsolidateFeedback Get the consolidated feedback Map englishFeedback, Map mathsFeedBack Map consolidatedFeedBack Hint : 1. Extract the keys of both the maps 2. For the teachers handling both the subjects find their maximum feedback and add to the output map. 3. Add the feedbacks of other teachers into a new Map
Example 36: Write a method which can find the sum of the first n prime numbers. Prime numbers are numbers which have only 1 and the number itself as its factors. 2 is the only even prime number. 1 is neither prime nor composite. Ex: the 1st 5 prime numbers are 2,3,5,7,11 and sum is 28 Method Name Method Description Argument Return Type Logic getPrimeSum Get the sum of the first n prime numbers int n Int Hint : 1. Use for loop to iterate over numbers from 2 to n, say loop variable i. 2. Use an inner loop with loop variable j which loops from to 2 to i/2. If for any j the remainder on dividing i by j is zero, the number is non-prime. If it is prime add the number to the sum.
Example 37: Write a method which accepts a String and moves all the lower case a to the beginning of the String. Method Name Method Description Argument Return Type rearrangeCharacters Move the all the lower case a to the beginning of a String String String
20
Example 38: Write a method which can find the factors of a number. Factor is an integer which evenly divides a number without leaving a remainder. Return the factors as an arraylist object. For Example 1, 2 and 4 are the factor of 4 Method Name Method Description Argument Return Type Logic getFators Get the factors of a number n int n List Hint : 1. Create a loop starting from 1 to n with loop variable say i. 2. Check if for any i , dividing n by i gives zero as remainder. Then i is a factor of n . 3. Add i to the list object
Example 39: Write a method which can accept an integer and return the binary, hexadecimal and octal equivalents of the number in a String array Method Name Method Description Argument Return Type Logic getFormats Gets the binary,hexadecimal and octal formats of a number int String Hint : 1. Use Integer wrapper class methods
21
Example 41: Write a method to validate the age of a person. The person age is considered valid if it is above 21 years. Accept the date of birth of the person as String in date-month-year(Ex: 23-05-2012) format and return true if the age is greater than 21. Method Name Method Description Argument Return Type Logic validateAge Validates if the persons age is above 21 String Boolean Hint :Use Calendar, Date and DateFormat APIs
Example 42: Write a method which can return the current date in any of the following date formats based on the user choice Choice 1 : Month-date-year(Ex: 05-26-2012) Choice 2: Date-month-year(Ex: 26-MAY-12) Choice 3: Date/month/year(Ex: 26/05/2012) Choice 4: Month/date/year(Ex: 05/26/2012)
22
Example 43: Consider two Hashmaps .First one containing the product name and product category code as key and value respectively. Second HashMap contains the product name and the units sold. Write a java function which accepts the two hash maps and return the names of products in each category which is having the highest number of units sold. For example Input1 :{lux:soap,colgate:paste, pears:soap,sony:electronics,samsung:electronics} Input 2:{lux:1000,colgate:500,pears:2000,sony:100, samsung,600} Output: {pears,colgate,samsung} Method Name Method Description Argument Return Type Logic getMaxSold Find the product maximum sold in each category HashMap<String,String> productDetails, HashMap<String,Integer> salesDetails List Algorithm: 1. Get product names from the productDetails map using the getValues method(Say categoryName which will be of data type Collection. 2. Remove the duplicate category names by converting categoryName to a Set object which can be done using the constructor of HashSet which accepts Collection object as argument
23
Example 44: Write a method which accepts a number and return it in words. For Example 123 One Two Three
getNumber Get the number in words int String Use mod(%) operator, StringBuffer and switch case
24
25
Example 46: Write a method which can check whether an entered number is palindrome or not. Method Name Method Description Argument Return Type Logic checkPalindrome Check palindrome int boolean Hint 1: 1. Convert the number to String 2. Check if the String and reverse of the String are equal
26