This document contains descriptions and code snippets for various programming problems and questions. Some of the problems addressed include:
- Writing a program to find duplicate characters in a string
- Finding a duplicate number between 1 to N numbers
- Reversing a number and a string using different approaches
- Finding the middle index where the sum of elements before and after are equal
- Other problems involve prime numbers, sorting, arrays, recursion, and more.
The document also contains questions about Java concepts like default variable values, the Runtime class, cloning, immutable classes, finally blocks, and differences between interfaces like Servlet vs Filter. Code solutions are provided for most problems.
Download as DOCX, PDF, TXT or read online on Scribd
100%(1)100% found this document useful (1 vote)
1K views
Java Programming Questions
This document contains descriptions and code snippets for various programming problems and questions. Some of the problems addressed include:
- Writing a program to find duplicate characters in a string
- Finding a duplicate number between 1 to N numbers
- Reversing a number and a string using different approaches
- Finding the middle index where the sum of elements before and after are equal
- Other problems involve prime numbers, sorting, arrays, recursion, and more.
The document also contains questions about Java concepts like default variable values, the Runtime class, cloning, immutable classes, finally blocks, and differences between interfaces like Servlet vs Filter. Code solutions are provided for most problems.
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 50
Contents
Program: Write a program to find out duplicate characters in a string. ...................................................... 3
Program: Find out duplicate number between 1 to N numbers. ................................................................. 4 Program: Write a program to reverse a number. ......................................................................................... 5 Program: Write a program to reverse a string using recursive algorithm. ................................................... 6 Program: Find out middle index where sum of both ends are equal. .......................................................... 7 Program: Write a singleton class. ................................................................................................................. 8 Program: Write a program to create deadlock between two threads. ........................................................ 9 Program: Write a program to reverse a string using recursive algorithm. ................................................. 10 Program: Write a program to reverse a number. ....................................................................................... 11 Program: Write a program to convert decimal number to binary format. ................................................ 12 Program: Write a program to find perfect number or not. ........................................................................ 13 Program: Write a program to implement ArrayList. ................................................................................... 14 Program: Write a program to find maximum repeated words from a file. ................................................ 16 Program: Write a program to find top two maximum numbers in a array. ............................................... 18 Program: Write a program to sort a map by value. .................................................................................... 19 Program: Write a program to find common elements between two arrays. ............................................. 20 Program: How to swap two numbers without using temporary variable? ................................................ 21 Program: Write a program to print fibonacci series. .................................................................................. 22 Program: Write a program to find sum of each digit in the given number using recursion. ..................... 23 Program: Write a program to check the given number is a prime number or not?................................... 24 Program: Write a program to find the given number is Armstrong number or not? ................................. 25 Program: Write a program to convert binary to decimal number. ............................................................ 26 Program: Write a program to check the given number is binary number or not? ..................................... 27 Program: Write a program for Insertion Sort in java. ................................................................................. 29 Program: Write a program to implement hashcode and equals. ............................................................... 30 Program: Write a program to get distinct word list from the given file. .................................................... 34 Program: Write a program to get a line with max word count from the given file. ................................... 36 Program: Write a program to find two lines with max characters in descending order. ........................... 37 Program: Write a program to find the sum of the first 1000 prime numbers. .......................................... 39 Program: Find longest substring without repeating characters. ................................................................ 40 Program: Write a program to remove duplicates from sorted array. ........................................................ 42 Question: Does system.exit() in try block executes code in finally block? ................................................. 45 Question: What is default value of a local variables? ................................................................................. 46 Question: What is the purpose of Runtime and System class? .................................................................. 46 Question: Difference between shallow cloning and deep cloning of objects? .......................................... 46 Question: How can you create an immutable class in java? ...................................................................... 47 Question: Can we have finally block without catch block? ........................................................................ 48 What is difference between Lambda Expression and Anonymous class? .................................................. 48 What is functional interface in java? .......................................................................................................... 48 What is difference between CountDownLatch and CyclicBarrier in Java? ................................................. 49 Can Enum extend any class in Java? ........................................................................................................... 49 Can Enum extend any class in Java? ........................................................................................................... 49 What is the difference between Servlet and Filter? ................................................................................... 49
Program: Write a program to find out duplicate characters in a string. Description: Write a program to find out duplicate or repeated characters in a string, and calculate the count of repeatation.
Code: Program: Find out duplicate number between 1 to N numbers. Description: You have got a range of numbers between 1 to N, where one of the number is repeated. You need to write a program to find out the duplicate number.
package com.java2novice.algos; import java.util.ArrayList; import java.util.List; public class DuplicateNumber { public int findDuplicateNumber(List<Integer> numbers){ int highestNumber = numbers.size() - 1; int total = getSum(numbers); int duplicate = total - (highestNumber*(highestNumber+1)/2); return duplicate; } public int getSum(List<Integer> numbers){ int sum = 0; for(int num:numbers){ sum += num; } return sum; } public static void main(String a[]){ List<Integer> numbers = new ArrayList<Integer>(); for(int i=1;i<30;i++){ numbers.add(i); } //add duplicate number into the list numbers.add(22); DuplicateNumber dn = new DuplicateNumber(); System.out.println("Duplicate Number: "+dn.findDuplicateNumber(numbers)); } }
Output: Duplicate Number: 22
Program: Write a program to reverse a number. Description: Write a program to reverse a number using numeric operations. Below example shows how to reverse a number using numeric operations.
Code: package com.java2novice.algos;
public class NumberReverse {
public int reverseNumber(int number){
int reverse = 0; while(number != 0){ reverse = (reverse*10)+(number%10); number = number/10; } return reverse; }
public static void main(String a[]){ NumberReverse nr = new NumberReverse(); System.out.println("Result: "+nr.reverseNumber(17868)); } }
Output: Result: 86871
Program: Write a program to reverse a string using recursive algorithm. Description: Write a program to reverse a string using recursive methods. You should not use any string reverse methods to do this.
Code:
package com.java2novice.algos; public class StringRecursiveReversal { String reverse = ""; public String reverseString(String str){ if(str.length() == 1){ return str; } else { reverse += str.charAt(str.length()-1) +reverseString(str.substring(0,str.length()-1)); return reverse; } } public static void main(String a[]){ StringRecursiveReversal srr = new StringRecursiveReversal(); System.out.println("Result: "+srr.reverseString("Java2novice")); } }
Output: Result: ecivon2avaJ
Program: Find out middle index where sum of both ends are equal. Description: You are given an array of numbers. Find out the array index or position where sum of numbers preceeding the index is equals to sum of numbers succeeding the index.
Code: package com.java2novice.algos;
public class FindMiddleIndex {
public static int findMiddleIndex(int[] numbers) throws Exception {
int endIndex = numbers.length - 1; int startIndex = 0; int sumLeft = 0; int sumRight = 0; while (true) { if (sumLeft > sumRight) { sumRight += numbers[endIndex--]; } else { sumLeft += numbers[startIndex++]; } if (startIndex > endIndex) { if (sumLeft == sumRight) { break; } else { throw new Exception( "Please pass proper array to match the requirement"); } } } return endIndex; }
public static void main(String a[]) { int[] num = { 2, 4, 4, 5, 4, 1 }; try { System.out.println("Starting from index 0, adding numbers till index " + findMiddleIndex(num) + " and"); System.out.println("adding rest of the numbers can be equal"); } catch (Exception ex) { System.out.println(ex.getMessage()); }}}
Output: Starting from index 0, adding numbers till index 2 and adding rest of the numbers can be equal
Program: Write a singleton class. Description: Singleton class means you can create only one object for the given class. You can create a singleton class by making its constructor as private, so that you can restrict the creation of the object. Provide a static method to get instance of the object, wherein you can handle the object creation inside the class only. In this example we are creating object by using static block.
Code: package com.java2novice.algos;
public class MySingleton {
private static MySingleton myObj;
static{ myObj = new MySingleton(); }
private MySingleton(){
}
public static MySingleton getInstance(){ return myObj; }
public void testMe(){ System.out.println("Hey.... it is working!!!"); }
public static void main(String a[]){ MySingleton ms = getInstance(); ms.testMe(); } }
Program: Write a program to create deadlock between two threads. Description: Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Deadlocks can occur in Java when the synchronized keyword causes the executing thread to block while waiting to get the lock, associated with the specified object. Since the thread might already hold locks associated with other objects, two threads could each be waiting for the other to release a lock. In such case, they will end up waiting forever.
public static void main(String a[]){ StringRecursiveReversal srr = new StringRecursiveReversal(); System.out.println("Result: "+srr.reverseString("Java2novice")); } } Output: Result: ecivon2avaJ
Program: Write a program to reverse a number. Description: Write a program to reverse a number using numeric operations. Below example shows how to reverse a number using numeric operations.
Code: package com.java2novice.algos;
public class NumberReverse {
public int reverseNumber(int number){
int reverse = 0; while(number != 0){ reverse = (reverse*10)+(number%10); number = number/10; } return reverse; }
public static void main(String a[]){ NumberReverse nr = new NumberReverse(); System.out.println("Result: "+nr.reverseNumber(17868)); } }
Output: Result: 86871
Program: Write a program to convert decimal number to binary format.
Description: Write a program to convert decimal number to binary format using numeric operations. Below example shows how to convert decimal number to binary format using numeric operations.
Code: package com.java2novice.algos;
public class DecimalToBinary {
public void printBinaryFormat(int number){ int binary[] = new int[25]; int index = 0; while(number > 0){ binary[index++] = number%2; number = number/2; } for(int i = index-1;i >= 0;i--){ System.out.print(binary[i]); } }
public static void main(String a[]){ DecimalToBinary dtb = new DecimalToBinary(); dtb.printBinaryFormat(25); } }
Output: 11001
Program: Write a program to find perfect number or not.
Description: A perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors. The first perfect number is 6, because 1, 2 and 3 are its proper positive divisors, and 1 + 2 + 3 = 6. Equivalently, the number 6 is equal to half the sum of all its positive divisors: ( 1 + 2 + 3 + 6 ) / 2 = 6.
Code: package com.java2novice.algos;
public class IsPerfectNumber {
public boolean isPerfectNumber(int number){
int temp = 0; for(int i=1;i<=number/2;i++){ if(number%i == 0){ temp += i; } } if(temp == number){ System.out.println("It is a perfect number"); return true; } else { System.out.println("It is not a perfect number"); return false; } }
public static void main(String a[]){ IsPerfectNumber ipn = new IsPerfectNumber(); System.out.println("Is perfect number: "+ipn.isPerfectNumber(28)); } }
Output: 28 It is a perfect number Is perfect number: true
Program: Write a program to implement ArrayList. Description: Write a program to implement your own ArrayList class. It should contain add(), get(), remove(), size() methods. Use dynamic array logic. It should increase its size when it reaches threshold.
Code:
package com.java2novice.algos; import java.util.Arrays; public class MyArrayList { private Object[] myStore; private int actSize = 0; public MyArrayList(){ myStore = new Object[10]; } public Object get(int index){ if(index < actSize){ return myStore[index]; } else { throw new ArrayIndexOutOfBoundsException(); } } public void add(Object obj){ if(myStore.length-actSize <= 5){ increaseListSize(); } myStore[actSize++] = obj; } public Object remove(int index){ if(index < actSize){ Object obj = myStore[index]; myStore[index] = null; int tmp = index; while(tmp < actSize){ myStore[tmp] = myStore[tmp+1]; myStore[tmp+1] = null; tmp++; } actSize--; return obj; } else { throw new ArrayIndexOutOfBoundsException(); } } public int size(){ return actSize; } private void increaseListSize(){ myStore = Arrays.copyOf(myStore, myStore.length*2); System.out.println("\nNew length: "+myStore.length); } public static void main(String a[]){ MyArrayList mal = new MyArrayList(); mal.add(new Integer(2)); mal.add(new Integer(5)); mal.add(new Integer(1)); mal.add(new Integer(23)); mal.add(new Integer(14)); for(int i=0;i<mal.size();i++){ System.out.print(mal.get(i)+" "); } mal.add(new Integer(29)); System.out.println("Element at Index 5:"+mal.get(5)); System.out.println("List size: "+mal.size()); System.out.println("Removing element at index 2: "+mal.remove(2)); for(int i=0;i<mal.size();i++){ System.out.print(mal.get(i)+" "); } } }
Output: 2 5 1 23 14 New length: 20 Element at Index 5:29 List size: 6 Removing element at index 2: 1 2 5 23 14 29
Program: Write a program to find maximum repeated words from a file.
Description: Write a program to read words from a file. Count the repeated or duplicated words. Sort it by maximum repeated or duplicated word count.
public List<Entry<String, Integer>> sortByValue(Map<String, Integer> wordMap){
Set<Entry<String, Integer>> set = wordMap.entrySet(); List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set); Collections.sort( list, new Comparator<Map.Entry<String, Integer>>() { public int compare( Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 ) { return (o2.getValue()).compareTo( o1.getValue() ); } } ); return list; }
public static void main(String a[]){ MaxDuplicateWordCount mdc = new MaxDuplicateWordCount(); Map<String, Integer> wordMap = mdc.getWordCount("C:/MyTestFile.txt"); List<Entry<String, Integer>> list = mdc.sortByValue(wordMap); for(Map.Entry<String, Integer> entry:list){ System.out.println(entry.getKey()+" ==== "+entry.getValue()); } } }
Output: one ==== 3 the ==== 3 that ==== 3 of ==== 2 in ==== 2 some ==== 2 to ==== 1 summary ==== 1 but ==== 1 have ==== 1 common ==== 1 least ==== 1 simplest ==== 1
Program: Write a program to find top two maximum numbers in a array.
Description: Write a program to find top two maximum numbers in the given array. You should not use any sorting functions. You should iterate the array only once. You should not use any kind of collections in java.
Code: package com.java2novice.algos;
public class TwoMaxNumbers {
public void printTwoMaxNumbers(int[] nums){ int maxOne = 0; int maxTwo = 0; for(int n:nums){ if(maxOne < n){ maxTwo = maxOne; maxOne =n; } else if(maxTwo < n){ maxTwo = n; } } System.out.println("First Max Number: "+maxOne); System.out.println("Second Max Number: "+maxTwo); }
public static void main(String a[]){ int num[] = {5,34,78,2,45,1,99,23}; TwoMaxNumbers tmn = new TwoMaxNumbers(); tmn.printTwoMaxNumbers(num); } }
Output: First Max Number: 99 Second Max Number: 78
Program: Write a program to sort a map by value.
Description: Sort or order a HashMap or TreeSet or any map item by value. Write a comparator which compares by value, not by key. Entry class might hleps you here.
public static void main(String a[]){ Map<String, Integer> map = new HashMap<String, Integer>(); map.put("java", 20); map.put("C++", 45); map.put("Java2Novice", 2); map.put("Unix", 67); map.put("MAC", 26); map.put("Why this kolavari", 93); Set<Entry<String, Integer>> set = map.entrySet(); List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set); Collections.sort( list, new Comparator<Map.Entry<String, Integer>>() { public int compare( Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 ) { return (o2.getValue()).compareTo( o1.getValue() ); } } ); for(Map.Entry<String, Integer> entry:list){ System.out.println(entry.getKey()+" ==== "+entry.getValue()); } } }
Output: Why this kolavari ==== 93 Unix ==== 67 C++ ==== 45 MAC ==== 26 java ==== 20 Java2Novice ==== 2
Program: Write a program to find common elements between two arrays. Description: Write a program to identify common elements or numbers between two given arrays. You should not use any inbuilt methods are list to find common values.
Program: How to swap two numbers without using temporary variable?
Description: Write a program to swap or exchange two numbers. You should not use any temporary or third variable to swap.
Code: package com.java2novice.algos;
public class MySwapingTwoNumbers {
public static void main(String a[]){ int x = 10; int y = 20; System.out.println("Before swap:"); System.out.println("x value: "+x); System.out.println("y value: "+y); x = x+y; y=x-y; x=x-y; System.out.println("After swap:"); System.out.println("x value: "+x); System.out.println("y value: "+y); } }
Output: Before swap: x value: 10 y value: 20 After swap: x value: 20 y value: 10
Program: Write a program to print fibonacci series. Code: package com.java2novice.algos;
Description: In mathematics, the Fibonacci numbers or Fibonacci series or Fibonacci sequence are the numbers in the following integer sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144... By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two. Below example shows how to create fibonacci series. public class MyFibonacci {
public static void main(String a[]){
int febCount = 15; int[] feb = new int[febCount]; feb[0] = 0; feb[1] = 1; for(int i=2; i < febCount; i++){ feb[i] = feb[i-1] + feb[i-2]; }
Program: Write a program to find sum of each digit in the given number using recursion.
Description: Below example shows how to find out sum of each digit in the given number using recursion logic. For example, if the number is 259, then the sum should be 2+5+9 = 16.
public static void main(String a[]){ MyNumberSumRec mns = new MyNumberSumRec(); System.out.println("Sum is: "+mns.getNumberSum(223)); } }
Output: Sum is: 7
Program: Write a program to check the given number is a prime number or not?
Description: A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. A natural number greater than 1 that is not a prime number is called a composite number. For example, 5 is prime, as only 1 and 5 divide it, whereas 6 is composite, since it has the divisors 2 and 3 in addition to 1 and 6. The fundamental theorem of arithmetic establishes the central role of primes in number theory: any integer greater than 1 can be expressed as a product of primes that is unique up to ordering. This theorem requires excluding 1 as a prime.
public static void main(String a[]){ MyPrimeNumCheck mpc = new MyPrimeNumCheck(); System.out.println("Is 17 prime number? "+mpc.isPrimeNumber(17)); System.out.println("Is 19 prime number? "+mpc.isPrimeNumber(19)); System.out.println("Is 15 prime number? "+mpc.isPrimeNumber(15)); } }
Output: Is 17 prime number? true Is 19 prime number? true Is 15 prime number? false
Program: Write a program to find the given number is Armstrong number or not?
Description: Armstrong numbers are the sum of their own digits to the power of the number of digits. It is also known as narcissistic numbers.
Code: package com.java2novice.algos;
public class MyArmstrongNumber {
public boolean isArmstrongNumber(int number){
int tmp = number; int noOfDigits = String.valueOf(number).length(); int sum = 0; int div = 0; while(tmp > 0) { div = tmp % 10; int temp = 1; for(int i=0;i<noOfDigits;i++){ temp *= div; } sum += temp; tmp = tmp/10; } if(number == sum) { return true; } else { return false; } }
public static void main(String a[]){ MyArmstrongNumber man = new MyArmstrongNumber(); System.out.println("Is 371 Armstrong number? "+man.isArmstrongNumber(371)); System.out.println("Is 523 Armstrong number? "+man.isArmstrongNumber(523)); System.out.println("Is 153 Armstrong number? "+man.isArmstrongNumber(153)); } }
Output: Is 371 Armstrong number? true Is 523 Armstrong number? false Is 153 Armstrong number? true
Program: Write a program to convert binary to decimal number.
Description: Write a program to convert binary format to decimal number using numeric operations. Below example shows how to convert binary to decimal format using numeric operations.
Code: package com.java2novice.algos;
public class BinaryToDecimal {
public int getDecimalFromBinary(int binary){
int decimal = 0; int power = 0; while(true){ if(binary == 0){ break; } else { int tmp = binary%10; decimal += tmp*Math.pow(2, power); binary = binary/10; power++; } } return decimal; }
Program: Write a program to check the given number is binary number or not?
Description: The binary numeral system, or base-2 number system, represents numeric values using two symbols: 0 and 1. More specifically, the usual base-2 system is a positional notation with a radix of 2. Because of its straightforward implementation in digital electronic circuitry using logic gates, the binary system is used internally by almost all modern computers.
public static void main(String a[]){ MyBinaryCheck mbc = new MyBinaryCheck(); System.out.println("Is 1000111 binary? :"+mbc.isBinaryNumber(1000111)); System.out.println("Is 10300111 binary? :"+mbc.isBinaryNumber(10300111)); } }
Output: Is 1000111 binary? :true Is 10300111 binary? :false
Program: Write a program for Bubble Sort in java Description: Bubble sort is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements bubble to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort. You can see the code implementation below:
Code: package com.java2novice.algos;
public class MyBubbleSort {
// logic to sort the elements public static void bubble_srt(int array[]) { int n = array.length; int k; for (int m = n; m >= 0; m--) { for (int i = 0; i < n - 1; i++) { k = i + 1; if (array[i] > array[k]) { swapNumbers(i, k, array); } } printNumbers(array); } }
private static void swapNumbers(int i, int j, int[] array) {
Program: Write a program for Insertion Sort in java. Description: Insertion sort is a simple sorting algorithm that builds the final sorted array one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. Every repetition of insertion sort removes an element from the input data, inserting it into the correct position in the already-sorted list, until no input elements remain. The choice of which element to remove from the input is arbitrary, and can be made using almost any choice algorithm. You can see the code implementation below:
for (int i = 0; i < input.length; i++) { System.out.print(input[i] + ", "); } System.out.println("\n"); }
public static void insertionSort(int array[]) { int n = array.length; for (int j = 1; j < n; j++) { int key = array[j]; int i = j-1; while ( (i > -1) && ( array [i] > key ) ) { array [i+1] = array [i]; i--; } array[i+1] = key; printNumbers(array); } } }
Output: 2, 4, 9, 6, 23, 12, 34, 0, 1,
2, 4, 9, 6, 23, 12, 34, 0, 1,
2, 4, 6, 9, 23, 12, 34, 0, 1,
2, 4, 6, 9, 23, 12, 34, 0, 1,
2, 4, 6, 9, 12, 23, 34, 0, 1,
2, 4, 6, 9, 12, 23, 34, 0, 1,
0, 2, 4, 6, 9, 12, 23, 34, 1,
0, 1, 2, 4, 6, 9, 12, 23, 34,
Program: Write a program to implement hashcode and equals. Description: The hashcode of a Java Object is simply a number, it is 32-bit signed int, that allows an object to be managed by a hash-based data structure. We know that hash code is an unique id number allocated to an object by JVM. But actually speaking, Hash code is not an unique number for an object. If two objects are equals then these two objects should return same hash code. So we have to implement hashcode() method of a class in such way that if two objects are equals, ie compared by equal() method of that class, then those two objects must return same hash code. If you are overriding hashCode you need to override equals method also.
The below example shows how to override equals and hashcode methods. The class Price overrides equals and hashcode. If you notice the hashcode implementation, it always generates unique hashcode for each object based on their state, ie if the object state is same, then you will get same hashcode. A HashMap is used in the example to store Price objects as keys. It shows though we generate different objects, but if state is same, still we can use this as key.
Code: package com.java2novice.algos;
import java.util.HashMap;
public class MyHashcodeImpl {
public static void main(String a[]){
HashMap<Price, String> hm = new HashMap<Price, String>(); hm.put(new Price("Banana", 20), "Banana"); hm.put(new Price("Apple", 40), "Apple"); hm.put(new Price("Orange", 30), "Orange"); //creating new object to use as key to get value Price key = new Price("Banana", 20); System.out.println("Hashcode of the key: "+key.hashCode()); System.out.println("Value from map: "+hm.get(key)); } }
class Price{
private String item; private int price;
public Price(String itm, int pr){ this.item = itm; this.price = pr; }
public int hashCode(){ System.out.println("In hashcode"); int hashcode = 0; hashcode = price*20; hashcode += item.hashCode(); return hashcode; }
public String getItem() { return item; } public void setItem(String item) { this.item = item; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; }
public String toString(){ return "item: "+item+" price: "+price; } } Output: In hashcode In hashcode In hashcode In hashcode Hashcode of the key: 1982479637 In hashcode In equals Value from map: Banana
Program: How to get distinct elements from an array by avoiding duplicate elements?
Description: The below example shows how to avoid duplicate elements from an array and disply only distinct elements. Please use only arrays to process it.
Output: the while statement verifies condition before entering into loop to see whether next iteration should occur or not do-while executes first without checking it after finishing each will always execute body of a at least once
Program: Write a program to get a line with max word count from the given file.
Description: Below example shows how to find out the line with maximum number of word count in the given file. In case if it has multiple lines with max number of words, then it has to list all those lines.
Code:
package com.java2novice.algos; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class MaxWordCountInLine { private int currentMaxCount = 0; private List<String> lines = new ArrayList<String>(); public void readMaxLineCount(String fileName){ FileInputStream fis = null; DataInputStream dis = null; BufferedReader br = null; try { fis = new FileInputStream(fileName); dis = new DataInputStream(fis); br = new BufferedReader(new InputStreamReader(dis)); String line = null; while((line = br.readLine()) != null){ int count = (line.split("\\s+")).length; if(count > currentMaxCount){ lines.clear(); lines.add(line); currentMaxCount = count; } else if(count == currentMaxCount){ lines.add(line); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ try{ if(br != null) br.close(); }catch(Exception ex){} } } public int getCurrentMaxCount() { return currentMaxCount; } public void setCurrentMaxCount(int currentMaxCount) { this.currentMaxCount = currentMaxCount; } public List<String> getLines() { return lines; } public void setLines(List<String> lines) { this.lines = lines; } public static void main(String a[]){ MaxWordCountInLine mdc = new MaxWordCountInLine(); mdc.readMaxLineCount("/Users/ngootooru/MyTestFile.txt"); System.out.println("Max number of words in a line is: "+mdc.getCurrentMaxCount()); System.out.println("Line with max word count:"); List<String> lines = mdc.getLines(); for(String l:lines){ System.out.println(l); } } }
MyTestFile.txt: true, false, and null might seem like keywords, but they are actually literals. You cannot use them as identifiers in your programs. The servlet context is an interface which helps to communicate with other servlets. It contains information about the Web application and container. It is kind of application environment. Using the context, a servlet can obtain URL references to resources, and store attributes that other servlets in the context can use.
Output: Max number of words in a line is: 13 Line with max word count: true, false, and null might seem like keywords, but they are actually literals.
Program: Write a program to find two lines with max characters in descending order.
Description: Write a program to read a multiple line text file and write the 'N' longest lines to the output console, where the file to be read is specified as command line aruguments. The program should read an input file. The first line should contain the value of the number 'N' followed by multiple lines. 'N' should be a valid positive integer.
public static class Entries{ Integer length; String line; public Entries(Integer l,String line){ length = l; this.line = line; } }
public static class MyComp implements Comparator<Entries>{
@Override public int compare(Entries e1, Entries e2) { if(e2.length > e1.length){ return 1; } else { return -1; } }
} }
Sample input file: 3 Java2novice My Test line 123
Java world I know java language
This is a test program java is simple
Output: This is a test program I know java language My Test line 123
Program: Write a program to find the sum of the first 1000 prime numbers. Description: Write a program to find the sum of the first 1000 prime numbers.
Code: package com.primesum;
public class Main {
public static void main(String args[]){
int number = 2; int count = 0; long sum = 0; while(count < 1000){ if(isPrimeNumber(number)){ sum += number; count++; } number++; } System.out.println(sum); }
Program: Find longest substring without repeating characters.
Description: Given a string, find the longest substrings without repeating characters. Iterate through the given string, find the longest maximum substrings.
Code:
package com.java2novice.algos; import java.util.HashSet; import java.util.Set; public class MyLongestSubstr { private Set<String> subStrList = new HashSet<String>(); private int finalSubStrSize = 0; public Set<String> getLongestSubstr(String input){ //reset instance variables subStrList.clear(); finalSubStrSize = 0; // have a boolean flag on each character ascii value boolean[] flag = new boolean[256]; int j = 0; char[] inputCharArr = input.toCharArray(); for (int i = 0; i < inputCharArr.length; i++) { char c = inputCharArr[i]; if (flag[c]) { extractSubString(inputCharArr,j,i); for (int k = j; k < i; k++) { if (inputCharArr[k] == c) { j = k + 1; break; } flag[inputCharArr[k]] = false; } } else { flag[c] = true; } } extractSubString(inputCharArr,j,inputCharArr.length); return subStrList; } private String extractSubString(char[] inputArr, int start, int end){ StringBuilder sb = new StringBuilder(); for(int i=start;i<end;i++){ sb.append(inputArr[i]); } String subStr = sb.toString(); if(subStr.length() > finalSubStrSize){ finalSubStrSize = subStr.length(); subStrList.clear(); subStrList.add(subStr); } else if(subStr.length() == finalSubStrSize){ subStrList.add(subStr); } return sb.toString(); } public static void main(String a[]){ MyLongestSubstr mls = new MyLongestSubstr(); System.out.println(mls.getLongestSubstr("java2novice")); System.out.println(mls.getLongestSubstr("java_language_is_sweet")); System.out.println(mls.getLongestSubstr("java_java_java_java")); System.out.println(mls.getLongestSubstr("abcabcbb")); } }
Program: Write a program to remove duplicates from sorted array.
Description: Given array is already sorted, and it has duplicate elements. Write a program to remove duplicate elements and return new array without any duplicate elements. The array should contain only unique elements.
Code: package com.java2novice.algos;
public class MyDuplicateElements {
public static int[] removeDuplicates(int[] input){
int j = 0; int i = 1; //return if the array length is less than 2 if(input.length < 2){ return input; } while(i < input.length){ if(input[i] == input[j]){ i++; }else{ input[++j] = input[i++]; } } int[] output = new int[j+1]; for(int k=0; k<output.length; k++){ output[k] = input[k]; }
What is System.out in Java In System.out, out is an instance of PrintStream. It is a static member variable in System class. This is called standard output stream, connected to console.
Pass by value Vs Pass by reference Pass by value: Passing a copy of the value, not the original reference.
Pass by reference: Passsing the address of the object, so that you can access the original object.
Question: How can you convert Map to List?
Answer: We know that Map contains key-value pairs, whereas a list contains only objects. Since Entry class contains both key-value pair, Entry class will helps us to convert from Map (HashMap) to List (ArrayList). By using Map.entrySet() you will get Set object, which intern you can use it to convert to list object.
Code: public static void main(String a[]){ Map<String, String> wordMap = new HashMap<String, String>(); Set<Entry<String, String>> set = wordMap.entrySet(); List<Entry<String, String>> list = new ArrayList<Entry<String, String>>(set); }
Question: What is difference between ServletOuptputStream and PrintWriter?
Answer: ServletOutputStream: ServletResponse.getOutputStream() returns a ServletOutputStream suitable for writing binary data in the response. The servlet container does not encode the binary data, it sends the raw data as it is.
PrintWriter: ServletResponse.getWriter() returns PrintWriter object which sends character text to the client. The PrintWriter uses the character encoding returned by getCharacterEncoding(). If the response's character encoding has not been specified then it does default character encoding
Question: What is java static import?
Answer: By using static imports, we can import the static members from a class rather than the classes from a given package. For example, Thread class has static sleep method, below example gives an idea:
import static java.lang.Thread; public class MyStaticImportTest { public static void main(String[] a) { try{ sleep(100); } catch(Exception ex){
} } }
Question: Does system.exit() in try block executes code in finally block? Code: try{ System.out.println("I am in try block"); System.exit(1); } catch(Exception ex){ ex.printStackTrace(); } finally { System.out.println("I am in finally block!!!"); }
Answer: It will not execute finally block. The program will be terminated after System.exit() statement.
Question: What is default value of a local variables?
Answer: The local variables are not initialized to any default values. We should not use local variables with out initialization. Even the java compiler throws error.
Question: What is the purpose of Runtime and System class?
Answer: The purpose of the Runtime class is to provide access to the Java runtime system. The runtime information like memory availability, invoking the garbage collector, etc.
The purpose of the System class is to provide access to system resources. It contains accessibility to standard input, standart output, error output streams, current time in millis, terminating the application, etc.
Question: Difference between shallow cloning and deep cloning of objects?
Answer: The default behavior of an objects clone() method automatically yields a shallow copy. So to achieve a deep copy the classes must be edited or adjusted. Shallow copy:Generally clone method of an object, creates a new instance of the same class and copies all the fields to the new instance and returns it. This is called shallow copy. Object class provides a clone method and provides support for the shallow copy. It returns Object as type and you need to explicitly cast back to your original object. Since the Object class has the clone method, you cannot use it in all your classes. The class which you want to be cloned should implement clone method and overwrite it. It should provide its own meaning for copy or to the least it should invoke the super.clone(). Also you have to implement Cloneable marker interface or else you will get CloneNotSupportedException. When you invoke the super.clone() then you are dependent on the Object classs implementation and what you get is a shallow copy. Deep copy:When you need a deep copy then you need to implement it yourself. When the copied object contains some other object its references are copied recursively in deep copy. When you implement deep copy be careful as you might fall for cyclic dependencies. If you dont want to implement deep copy yourselves then you can go for serialization. It does implements deep copy implicitly and gracefully handling cyclic dependencies.
Question: How can you create an immutable class in java?
Answer: Here are the steps to create immutable class: Declare the class as final, we can not extend the final class. public final class MyTestImmutable { ... } Declare all fields as final. Final fields can not be changed once its assigned. private final int salary; Do not provide any method which can change the state of the object, for example the setter methods which changes the values of the instance variables. The this reference is not allowed to escape during construction from the immutable class and the immutable class should have exclusive access to fields that contain references to mutable objects like arrays, collections and mutable classes like Date etc by: Declaring the mutable references as private. Not returning or exposing the mutable references to the caller.
Question: What are the restrictions when overriding a method? Overriding methods must have the same name, parameter list, and same return type. i.e., they must have the exact signature of the method we are going to override, including return type. The overriding method cannot be less visible than the method it overrides. i.e., a public method cannot be override to private. The overriding method may not throw any exceptions that may not be thrown by the overridden method 1) Overriding methods must have the same name, parameter list 2) Overriding methods must have either same or co-variant return types 3) Overriding methods mustn't have more restrictive access modifier. i.e. if base class method is public, overriden method can't have private access modifier 4) Overriding methods mustn't throw any broader checked exception than base class method.
Question: Can we have finally block without catch block?
Answer: Yes, we can have finally block without catch block.
What is difference between Lambda Expression and Anonymous class?
Answer: The key difference between Anonymous class and Lambda expression is the usage of 'this' keyword. In the anonymous classes, this keyword resolves to anonymous class itself, whereas for lambda expression this keyword resolves to enclosing class where lambda expression is written. Another difference between lambda expression and anonymous class is in the way these two are compiled. Java compiler compiles lambda expressions and convert them into private method of the class. It uses invokedynamic instruction that was added in Java 7 to bind this method dynamically.
What is functional interface in java?
Answer: In Java, a Marker interface is an interface without any methods or fields declaration, means it is an empty interface. Similarly, a Functional Interface is an interface with just one abstract method declared in it. Runnable interface is an example of a Functional Interface. It has only run() method declared in it. Lambda expression works on functional interfaces to replace anonymous classes. @FunctionalInterface is a new annotation added in Java 8 to indicate that an interface declaration is intended to be a functional interface as defined by the Java Language Specification. @FunctionalInterface can be used for compiler level errors when the interface you have annotated is not a valid Functional Interface.
What is difference between CountDownLatch and CyclicBarrier in Java?
Answer: Both CyclicBarrier and CountDownLatch are used to implement a scenario where one Thread waits for one or more Thread to complete their job before starts processing. The differences are: 1) CyclicBarrier is resulable, CountDownLatch is not. 2) Both CyclicBarrier and CountDownLatch wait for fixed number of threads. 3) CountDownLatch is advanceable but CyclicBarrier is not.
Can Enum extend any class in Java?
Answer: Enum can not extend any class in java, the reason is by default, Enum extends abstract base class java.lang.Enum. Since java does not support multiple inheritance for classes, Enum can not extend another class.
Can Enum extend any class in Java?
Answer: Enum can not extend any class in java, the reason is by default, Enum extends abstract base class java.lang.Enum. Since java does not support multiple inheritance for classes, Enum can not extend another class.
What is the difference between Servlet and Filter?
Answer: A filter is an object that can transform the header and content (or both) of a request or response. Filters differ from web components in that filters usually do not themselves create a response. Instead, a filter provides functionality that can be attached to any kind of web resource. Consequently, a filter should not have any dependencies on a web resource for which it is acting as a filter; this way it can be composed with more than one type of web resource. The main tasks that a filter can perform are as follows: 1) Query the request and act accordingly. 2) Block the request-and-response pair from passing any further. 3) Modify the request headers and data. You do this by providing a customized version of the request. 4) Modify the response headers and data. You do this by providing a customized version of the response. 5) Interact with external resources. Servlet is used for performing the action which needs to be taken for particular request like user login, get the response based on user role, interacts with database for getting the data, business logic execution, etc.