Top 20 Java Coding Challenge

How do you Reverse String in java

public class StringPrograms {

public static void main(String[] args) {

String str = "123";

System.out.println(reverse(str));

}

public static String reverse(String in) {

if (in == null)

throw new IllegalArgumentException("Null is not valid input");

StringBuilder out = new StringBuilder();

char[] chars = in.toCharArray();

for (int i = chars.length - 1; i >= 0; i--)

out.append(chars[i]);

return out.toString();

}

}

—----------------Swap 2 number without using 3 variable

public class SwapNumbers {

public static void main(String[] args) {

int a = 10;

int b = 20;

    System.out.println("a is " + a + " and b is " + b);

a = a + b;

b = a - b;

a = a - b;

    System.out.println("After swapping, a is " + a + " and b is " + b);

    }

}

—-------------------check if vowel is present in string

public class StringContainsVowels {

public static void main(String[] args) {

System.out.println(stringContainsVowels("Hello")); // true

System.out.println(stringContainsVowels("TV")); // false

}

public static boolean stringContainsVowels(String input) {

return input.toLowerCase().matches(".*[aeiou].*");

}

}

—----------------------check if number is prime number

public class PrimeNumberCheck {

public static void main(String[] args) {

System.out.println(isPrime(19)); // true

System.out.println(isPrime(49)); // false

}

public static boolean isPrime(int n) {

if (n == 0 || n == 1) {

return false;

}

if (n == 2) {

return true;

}

for (int i = 2; i <= n / 2; i++) {

if (n % i == 0) {

return false;

}

}

return true;

}

}

—-----------------Fibonacci sequence using recursion

public class PrintFibonacci {

public static void printFibonacciSequence(int count) {

int a = 0;

int b = 1;

int c = 1;

for (int i = 1; i <= count; i++) {

System.out.print(a + ", ");

            a = b;

b = c;

c = a + b;

}

}

public static void main(String[] args) {

     printFibonacciSequence(10);

}

}

—---------------------Fibonacci recursive

public class PrintFibonacciRecursive {

    public static int fibonacci(int count) {

if (count <= 1)

return count;

return fibonacci(count - 1) + fibonacci(count - 2);

}

public static void main(String args[]) {

     int seqLength = 10;

     System.out.print("A Fibonacci sequence of " + seqLength + " numbers: ");

     for (int i = 0; i < seqLength; i++) {

           System.out.print(fibonacci(i) + " ");

     }

   }

}

—--------------------Only odd numbers

public static boolean onlyOddNumbers(List<Integer> list) {

for (int i : list) {

if (i % 2 == 0)

return false;

}

return true;

}

—----------------

public static boolean onlyOddNumbers(List<Integer> list) {

return list

.parallelStream() // parallel stream for faster processing

.anyMatch(x -> x % 2 != 0); // return as soon as any elements match the condition

}

—-----------------check palindrome forward and backward string is same

boolean checkPalindromeString(String input) {

boolean result = true;

int length = input.length();

for (int i = 0; i < length/2; i++) {

if (input.charAt(i) != input.charAt(length - i - 1)) {

result = false;

break;

}

}

return result;

}

—---------------------------sort an array

int[] array = {1, 2, 3, -1, -2, 4};

Arrays.sort(array);

System.out.println(Arrays.toString(array));

—----------------reverse linked list

LinkedList<Integer> ll = new LinkedList<>();

ll.add(1);

ll.add(2);

ll.add(3);

System.out.println(ll);


LinkedList<Integer> ll1 = new LinkedList<>();

ll.descendingIterator().forEachRemaining(ll1::add);

System.out.println(ll1);

—-----------------------implement binary search

public static int binarySearch(int arr[], int low, int high, int key) {

int mid = (low + high) / 2;

while (low <= high) {

if (arr[mid] < key) {

low = mid + 1;

} else if (arr[mid] == key) {

return mid;

} else {

high = mid - 1;

}

mid = (low + high) / 2;

}

if (low > high) {

return -1;

}

return -1;

}

—---------------merge sort

public class MergeSort {

public static void main(String[] args) {

int[] arr = { 70, 50, 30, 10, 20, 40, 60 };

int[] merged = mergeSort(arr, 0, arr.length - 1);

for (int val : merged) {

System.out.print(val + " ");

}

}

public static int[] mergeTwoSortedArrays(int[] one, int[] two) {

int[] sorted = new int[one.length + two.length];

int i = 0;

int j = 0;

int k = 0;

while (i < one.length && j < two.length) {

if (one[i] < two[j]) {

sorted[k] = one[i];

k++;

i++;

} else {

sorted[k] = two[j];

k++;

j++;

}

}

if (i == one.length) {

while (j < two.length) {

sorted[k] = two[j];

k++;

j++;

}

}

if (j == two.length) {

while (i < one.length) {

sorted[k] = one[i];

k++;

i++;

}

}

return sorted;

}

public static int[] mergeSort(int[] arr, int lo, int hi) {

if (lo == hi) {

int[] br = new int[1];

br[0] = arr[lo];

return br;

}

int mid = (lo + hi) / 2;

int[] fh = mergeSort(arr, lo, mid);

int[] sh = mergeSort(arr, mid + 1, hi);

int[] merged = mergeTwoSortedArrays(fh, sh);

return merged;

}

}

—------------check if 2 array contain same element

import java.util.Arrays;

import java.util.HashSet;

import java.util.Set;

public class ArraySameElements {

public static void main(String[] args) {

Integer[] a1 = {1,2,3,2,1};

Integer[] a2 = {1,2,3};

Integer[] a3 = {1,2,3,4};

System.out.println(sameElements(a1, a2));

System.out.println(sameElements(a1, a3));

}

static boolean sameElements(Object[] array1, Object[] array2) {

Set<Object> uniqueElements1 = new HashSet<>(Arrays.asList(array1));

Set<Object> uniqueElements2 = new HashSet<>(Arrays.asList(array2));

// if size is different, means there will be a mismatch

if (uniqueElements1.size() != uniqueElements2.size()) return false;

for (Object obj : uniqueElements1) {

// element not present in both?

if (!uniqueElements2.contains(obj)) return false;

}

return true;

}

}

—--------------------------sum of all elements integer array

int[] array = { 1, 2, 3, 4, 5 };

int sum = 0;

for (int i : array)

sum += i;

System.out.println(sum);

—---------------------find second largest number

private static int findSecondHighest(int[] array) {

int highest = Integer.MIN_VALUE;

int secondHighest = Integer.MIN_VALUE;

for (int i : array) {

if (i > highest) {

secondHighest = highest;

highest = i;

} else if (i > secondHighest) {

secondHighest = i;

}

}

return secondHighest;

}

—------------------------sort hash map by value

import java.util.ArrayList;

import java.util.HashMap;

import java.util.LinkedHashMap;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import java.util.Set;

public class SortHashMapByValue {


public static void main(String[] args) {

Map<String, Integer> scores = new HashMap<>();

scores.put("David", 95);

scores.put("Jane", 80);

scores.put("Mary", 97);

scores.put("Lisa", 78);

scores.put("Dino", 65);

System.out.println(scores);

scores = sortByValue(scores);

System.out.println(scores);

}

private static Map<String, Integer> sortByValue(Map<String, Integer> scores) {

Map<String, Integer> sortedByValue = new LinkedHashMap<>();

// get the entry set

Set<Entry<String, Integer>> entrySet = scores.entrySet();

System.out.println(entrySet);

// create a list since the set is unordered

List<Entry<String, Integer>> entryList = new ArrayList<>(entrySet);

System.out.println(entryList);

// sort the list by value

entryList.sort((x, y) -> x.getValue().compareTo(y.getValue()));

System.out.println(entryList);

// populate the new hash map

for (Entry<String, Integer> e : entryList)

sortedByValue.put(e.getKey(), e.getValue());

return sortedByValue;

}

}

—-----------------ForEach() method

List<String> list = new ArrayList<>();

Iterator<String> it = list.iterator();

while (it.hasNext()) {

System.out.println(it.next());

}

—--------------Reverse String without using string inbuilt

public class FinalReverseWithoutUsingStringMethods {

       public static void main(String[] args) {

          // TODO Auto-generated method stub

          String str = "Automation";

          StringBuilder str2 = new StringBuilder();

          str2.append(str);

          str2 = str2.reverse(); // used string builder to reverse

         System.out.println(str2);

         }

  }

—---------iterate hash map using while for loop


import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

 

public class HashMapIteration {

 

    public static void main(String[] args) {

        // TODO Auto-generated method stub

        HashMap&lt;Integer,String&gt; map = new HashMap&lt;Integer,String&gt;();

        map.put(2, "Saket");

        map.put(25, "Saurav");

        map.put(12, "HashMap");

        System.out.println(map.size());

        System.out.println("While Loop:");

        Iterator itr = map.entrySet().iterator();

        while(itr.hasNext()) {

            Map.Entry me = (Map.Entry) itr.next();

            System.out.println("Key is " + me.getKey() + " Value is " + me.getValue());

        }

        System.out.println("For Loop:");

        for(Map.Entry me2: map.entrySet()) {

            System.out.println("Key is: " + me2.getKey() + " Value is: " + me2.getValue());

        }

    }

 

}

Output:

3
While Loop:
Key is 2 Value is Saket
Key is 25 Value is Saurav
Key is 12 Value is HashMap
For Loop:
Key is: 2 Value is: Saket
Key is: 25 Value is: Saurav
Key is: 12 Value is: HashMap

—-----------------number is prime or not


2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

import java.util.Scanner;

 

public class Prime {

 

    public static void main(String[] args) {

        // TODO Auto-generated method stub

        int temp, num;

        boolean isPrime = true;

        Scanner in = new Scanner(System.in);

        num = in.nextInt();

        in.close();

        for (int i = 2; i&lt;= num/2; i++) {

            temp = num%i;

            if (temp == 0) {

                isPrime = false;

                break;

            }

        }

        if(isPrime)

            System.out.println(num + "number is prime");

            else

                System.out.println(num + "number is not a prime");

           

         

    }

 

}

—------------check duplicate character


public class DuplicateCharacters {

          

          public static void main(String[] args) {

                   // TODO Auto-generated method stub

                  String str = new String("Sakkett");

                  int count = 0;

                  char[] chars = str.toCharArray();

                  System.out.println("Duplicate characters are:");

                  for (int i=0; i&lt;str.length();i++) {

                              for(int j=i+1; j&lt;str.length();j++) {

                                         if (chars[i] == chars[j]) {

                                                    System.out.println(chars[j]);

                                                    count++;

                                                    break;

                                          }

                               }

                   }

           }

 

}

—--find 2nd highest number

package codes;

public class SecondHighestNumberInArray {

public static void main(String[] args)

    {

        int arr[] = { 100,14, 46, 47, 94, 94, 52, 86, 36, 94, 89 };

        int largest = 0;

        int secondLargest = 0;

        System.out.println("The given array is:");

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

        {

            System.out.print(arr[i] + "\t");

        }

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

        {

            if (arr[i] > largest)

            {

                secondLargest = largest;

                largest = arr[i];

            }

            else if (arr[i] > secondLargest)

            {

                secondLargest = arr[i];

            }

        }

        System.out.println("\nSecond largest number is:" + secondLargest);

        System.out.println("Largest Number is: "  +largest);

    }

}

—---------------check armstrong number

class Armstrong{ 

 public static void main(String[] args)  { 

   int c=0,a,temp; 

   int n=153;//It is the number to check Armstrong 

   temp=n; 

   while(n&gt;0) 

   { 

   a=n%10; 

   n=n/10; 

    c=c+(a*a*a); 

    } 

    if(temp==c) 

    System.out.println("armstrong number");  

    else 

        System.out.println("Not armstrong number");  

   } 

}

—-------------remove all spaces using replace()

class RemoveWhiteSpaces

{

    public static void main(String[] args)

    {

        String str1 = "Saket Saurav    is a QualityAna list";

  

        //1. Using replaceAll() Method

  

        String str2 = str1.replaceAll("\\s", "");

  

        System.out.println(str2);

  

           }

}

}

—------------remove all space without using replace

class RemoveWhiteSpaces

{

    public static void main(String[] args)

    {

        String str1 = "Saket Saurav    is an Autom ation Engi ne  er";

  

        char[] chars = str1.toCharArray();

  

        StringBuffer sb = new StringBuffer();

  

        for (int i = 0; i &lt; chars.length; i++)

        {

            if( (chars[i] != ' ') &amp;&amp; (chars[i] != '\t') )

            {

                sb.append(chars[i]);

            }

        }

        System.out.println(sb);       //Output : CoreJavajspservletsjdbcstrutshibernatespring

    }

}

—-------------------to read excel


@Test

 public void ReadData() throws IOException

 {

     // Import excel sheet from a webdriver directory which is inside c drive.

     //DataSource is the name of the excel

     File src=new File("C:\\webdriver\\DataSource.xls");

      

     //This step is for loading the file. We have used FileInputStream as

     //we are reading the excel. In case you want to write into the file,

     //you need to use FileOutputStream. The path of the file is passed as an argument to FileInputStream

     FileInputStream finput = new FileInputStream(src);

      

     //This step is to load the workbook of the excel which is done by global HSSFWorkbook in which we have

     //passed finput as an argument.

    workbook = new HSSFWorkbook(finput);

      

     //This step is to load the sheet in which data is stored.

     sheet= workbook.getSheetAt(0);

      

     for(int i=1; i&lt;=sheet.getLastRowNum(); i++)

     {

         // Import data for Email.

         cell = sheet.getRow(i).getCell(1);

         cell.setCellType(Cell.CELL_TYPE_STRING);

         driver.findElement(By.id("email")).sendKeys(cell.getStringCellValue());

          

         // Import data for the password.

         cell = sheet.getRow(i).getCell(2);

         cell.setCellType(Cell.CELL_TYPE_STRING);

         driver.findElement(By.id("password")).sendKeys(cell.getStringCellValue());

                    

        }

  }













—--------------------

Enumerations

Java allows us to define data types, including the values that the type can hold (its domain), by using an enumeration. An enumeration is a way to define both a data type and all the possible values it can hold. Its name is often shortened to enum, which is the keyword used to define it.

A common use of enumerations is for types that have small domains, and a common example is the days of the week. I can set up an enumeration like this:

public enum Day {

     SUNDAY, MONDAY, TUESDAY, WEDNESDAY,

     THURSDAY, FRIDAY, SATURDAY  

}

Once an enumeration is declared, I can use it and its values like this:

Day dayOfTheWeek;

   . . .

dayOfTheWeek = Day.MONDAY;

   . . .

if (dayOfTheWeek == Day.SUNDAY)

   . . .



—----------------------------

Java Virtual Machine:

JVM allows Java to run on platforms without being recompiled.

JDK & JRE:

JDK & JRE allow you to create and run Java programs.

JRE contains Java Virtual machine, as well as browser plugins for executing Java applets.

JDK is full featured software development kit for Java, including JRE, as well as compilers, debuggers and tools to create programs.

Class Vs Instance:

Class:

Attributes: string breed, int age, string color

Methods: bark(), 

Instance: is key. Ex: golden breed

Static Vs Nonstatic methods:

Static method:

  • Class method

  • Belongs to class itself

  • Do not need instance in order to use static method

  • Method depend on class

Nonstatic method:

  • Instance method 

  • Belongs to each object generated from the class

  • Need an instance to use

  • Method depends on individual characteristics of the object

  • Ex: breed, age color

When to use static methods

  • If you want to use a method without creating an instance of the class, static methods are the way to go

  • Static methods can only access class variables

When to use Nonstatic methods

  • Nonstatic methods can access nonstatic and static variables

  • If your method is related to objects attributes, it should be nonstatic

Ex:

Local variable(Scope):

Local variables live inside methods, meaning the method that they are created in is the only method that will have access to them.

Access Modifiers:

Private variables and methods are only visible in the class they live in.

Members without a modifier are visible to the package they live in.

Protected variables and methods are visible to the package in all subclasses 

Public members are accessible everywhere

String: Strings are immutable.

-Is data type used to represent text rather than numbers.

String is comprised of a set of characters, including letters, numbers and spaces

2 way to create String:

String literals: String A = “abc”; //live in string constant pool. String A and B reference the same object and value.

String Objects: String A = new String(“abc”);// live in the heap. String A and B reference 2 separate objects.

Nice to store string in 1 place  rather than multiple

Classes like StringBuilder & StringBuffer allow you to make string-like objects that are mutable.

Instead of creating a bunch of Strings, Create String Builder 

StringBuffer is thread-safe because it has synchronized methods.

In java 9 Strings are stored as byte arrays instead of char arrays.we call them compact strings because char itself takes up two bytes.

Array:

Is a collection of objects of the same data type. It’s size cannot be changed after its allocated since its items are stored at contiguous locations and memory. Each object in the array accessed by index, starting at zero. There are specific ways to declare, allocate, initialize, retrieve, add & remove objects to an array.

Int[] nums; // declare an array  

Double[] otherNums = new double[5];// declare and allocate an array

String[] availablePets = {“cat”, “dog”, “fish”};// declaring, allocating, and initializing  an array

We can print out with using Arrays.toString(availablePets)

Swapping and retrieving:

int indexOfAvailablePet =2;//index of fish

int indexOfUnavailablePet =0;// index of bird

String availablePet = availablePets[indexOfAvailablePet];// fish

String unavailablePet= unavailablePets[indexOfUnavailablePet];// bird

// to add the bird to available pets array and delete the fish. Simply access availablepets

availablePets[indexOfAvailablePet]= unavailablePet;

// search any item in array

Adv of Arrays

-to implement other data structures

-act as container object for multiple items

-less memory overhead

Disadv of Arrays:

-Takes a longer to search for an item in an array

-Must copy all items to a new array if the current array is full.

Linked list: linear data structure where elements containing data of the same type are linked using pointers.

Each item in the linked list is called a node

A node contains data, as well as a pointer pointing to next element in the linked list

If a next pointer is null, then it is the last item in the list

Since elements are connected by pointers, they do not need to be stored next to each other.

Singly linked lists: contain a pointer pointing to the next node.

Doubly linked lists: contain a pointer pointing to the next node, and a pointer pointing to the previous node.

Queue:

-An Ordered lists of objects where elements are inserted(enqueued) at the end of the queue and removed(dequeued) from the beginning of the queue.

-FIFO


Stack:LILOI

Hash map:

-Use key-value pairs and a hashing function to store and organize their data

-Hashing function maps a key or object to a specific hash 

-This hash determines where the object is stored.

-As long as you have key, retrieving object is fast

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

wordToNum.put(“one”, 1);// insert key and value 

wordToNum.put(“two”, 2);

wordToNum.get(“one”)//get the value of key

wordToNum.values()// print all values

wordToNum.keySet()// print all keys

OOPS 

Abstraction: hides implementation complexity(design, system) so we can achieve generalize certain features of our program.

public abstract class Shape {

   String color;


   public Shape(String color){

       this.color = color;

   }

   abstract double getArea();

   abstract String draw();


}

public class Circle extends Shape {

    double radius;

   public Circle(String color, double radius){

       super(color);

       this.radius = radius;

   }

   public double getArea(){

       return Math.PI*Math.pow(radius,2);

   }

   public  String draw(){

       return "A" + color + "circle with a " + radius + "inch radius is drawn";

   }

}

public class Main {

   public static void  main(String[] args){


       Rectangle r = new Rectangle("purple", 5, 2);

       Circle c= new Circle("blue", 4);

       //abstraction, we dont need to know that shape is rectangle

       Shape s = new Rectangle("red", 9, 8);

       System.out.println("Shape Area:"+ s.getArea());// abstraction i dont need to know, how i get the area

       System.out.println(s.draw());// abstraction i dont need  to know, how i draw, dont care about process, how it generate

       System.out.println("Rectangle Area:"+r.getArea());

       System.out.println("Circle Area:"+c.getArea());

       System.out.println(r.draw());

       System.out.println(c.draw());

Why use Abstraction?

-allows only essentials details to be displayed to the user so that the feature can be used in more ways rather than in one super specific way


Encapsulation(data hiding):

-Binding an object’s state and behaviors together

-A way of wrapping data and code acting on the data into a single unit

-keeps classes separated & prevent coupling

- with encapsulation, a class data is hidden from other classes and can only be accessed through specific methods of its own class.

- we achieve encapsulation by declaring all the fields in a class as private and writing public methods in the class to set and get the values of variables

-We use encapsulation so that the user has no idea of the inner implementation of a given class and the data it contains.

-it allows you to hide how values are stored within a given class.

public class Employee {

   private String name;//private access

   private int age;

   private int id;


   public Employee(String name, int age, int id){

       this.name = name;

       this.age = age;

       this.id = id;

   }

   public String getName(){

       return this.name;

   }

   public int getAge(){

       return this.age;

   }

   public int getId(){

       return this.id;

   }

}

public class Main {

   public static void  main(String[] args){


       Employee employee = new Employee("Elizabeth", 29, 13);

       System.out.println(employee.getId());

       System.out.println(employee.getAge());

       System.out.println(employee.getName());

Inheritance:

  • Is the process where one class acquires the fields and methods of another

  • With inheritance, we can write the common properties and functionality in one class and have other classes with unique features all extend this one class, making code more reusable.

  • Instead of writing the same common implementation multiple times, we can write it once and then have whatever class needs this functionality extend this class

  • Main advantage of inheritance is minimizing the amount of duplicate code.

  • Allows data hiding, where the super base class can keep some data private, and this data cannot be accessed by the subclass.

  • Main disadvantage of inheritance is that the superclass and subclass can become tightly coupled, meaning they can not be used independently of each other

public class Teacher {

   int numberOfStudents;

   String school;

   public Teacher(int numberOfStudents, String school){

       this.numberOfStudents = numberOfStudents;

       this.school = school;

   }

   public String getRole(){

       return "this teacher teaches at" + this.school + "and has" + this.numberOfStudents + "students";

   }

}

public class MathTeacher extends Teacher {

   int favoriteNumber;

   public MathTeacher(int numberOfStudents, String school, int favoriteNumber){

       super(numberOfStudents,school);

       this.favoriteNumber=favoriteNumber;

   }

}

public class Main {

   public static void  main(String[] args){

       //inheritance

   MathTeacher mathTeacher = new MathTeacher(30, "school", 6);

       System.out.println( mathTeacher.numberOfStudents);

       System.out.println(mathTeacher.school);

       System.out.println(mathTeacher.favoriteNumber);

       System.out.println(mathTeacher.getRole());


Polymorphism(generics):

Is the ability for an object or function to take many forms.

Runtime polymorphism is achieved through method overriding

public class Animal {

   // generic method

   public String sound(){

       return "An animal is making sound";

   }

}

public class Pig extends Animal {

   @Override

   public  String sound()

   {

       return  "oink";

   }

}

public class Main {

   public static void  main(String[] args){

       Animal a = new Animal();

       Pig p = new Pig();

       Cow c = new Cow();


       System.out.println(a.sound());

       System.out.println(p.sound());

       System.out.println(c.sound());

   }

}

Compile time polymorphism is achieved through method overloading.

Method overloading is a feature that allows a class to have more than one method having some name, if their argument lists are different.

public class Operation {

   public  int add(int x, int y){

       return x+y;

   }

   public  int add(int x, int y, int z){

       return x+y +z;

   }

   public  int add(int x, int y, int z, int a){

       return x+y+z+a;

   }

}

main{

Operation o = new Operation();

System.out.println(o.add(2,3));

System.out.println(o.add(2,3,4));

System.out.println(o.add(2,3,5,6));

------------

REST(Representational State Transfer):combines the use of URLs and HTTP verbs, such as post and get, to represent and transfer resources(serialization of POZO represented as JSON string). Implement REST server and client. 

JAX-RS API provides annotations and interfaces that when used with plain old Java objects exposes them as web resources.  




Java 10:

Local variable type inference:

Declare variables without having to specify associated type.

Var list = new ArrayList<String>();

Var myFavoriteNumber = 12;

You must initialize them, not declare only

Garbage Collection:


Q. Palindrome or not

A palindrome is those String whose reverse is equal to the original. This can be done by using either StringBuffer reverse() method

  1. Reverse the given String

2) Check if reverse of String is equal to itself, if yes then given String is palindrome.

public class PalindromeTest {

 public static void main(String args[]) { 

System.out.println("Is aaa palindrom?: " + isPalindromString("aaa")); 

System.out.println("Is abc palindrom?: " + isPalindromString("abc")); 

/** Java method to check if given String is Palindrome

public static boolean isPalindromString(String text){ 

String reverse = reverse(text); 

if(text.equals(reverse)){ return true; } return false; } 

/** * Java method to reverse String using recursion 

public static String reverse(String input){

 if(input == null || input.isEmpty()){ return input; } return input.charAt(input.length()- 1) + reverse(input.substring(0, input.length() - 1)); } } 

Q. method which will remove any given character from a String?-Recursion

indexOf() and substring() method of Java's String class, indexOf() method returns index of a given character if its present in the String on which this method is called, otherwise -1. So first step, we will try to find the index of given character, if its present then we will remove it using substring() method, if not present then it become our base case 

public class RemoveCharFromString { private static final Logger logger = LoggerFactory.getLogger(RemoveCharFromString.class); public static String remove(String word, char unwanted){ StringBuilder sb = new StringBuilder(); 

//iterate over String by converting into character array and check if current character is same as given character to remove or not, if it is then ignore it otherwise add character into 

char[] letters = word.toCharArray(); for(char c : letters){ if(c != unwanted ){ sb.append(c); } } return sb.toString(); } public static String removeRecursive(Stringword, char ch){ int index = word.indexOf(ch); if(index == -1){ return word; } return removeRecursive(word.substring(0, index) + word.substring(index +1, word.length()), ch); } }

//first method, remove(String word, char unwanted) deletes the given character using iteration while second method removeRecursive(String word, char ch), uses recursion to accomplish this task.

---------permutation of string-recursion

public class StringPermutations { public static void main(String args[]) { permutation("123"); } /* * A method exposed to client to calculate permutation of String in Java. */ public static void permutation(String input){ permutation("", input); } /* * Recursive method which actually prints all permutations * of given String, but since we are passing an empty String * as current permutation to start with, * I have made this method private and didn't exposed it to client. */ private static void permutation(String perm, String word) { if (word.isEmpty()) { System.err.println(perm + word); } else { for (int i = 0; i &lt; word.length(); i++) { permutation(perm + word.charAt(i), word.substring(0, i) + word.substring(i + 1, word.length())); } } } } 

-----------


How to read and parse csv file in java

Review a simple CSV file

/Users/mkyong/csv/country.csv

"1.0.0.0","1.0.0.255","16777216","16777471","AU","Australia"
"1.0.1.0","1.0.3.255","16777472","16778239","CN","China"
"1.0.4.0","1.0.7.255","16778240","16779263","AU","Australia"
"1.0.8.0","1.0.15.255","16779264","16781311","CN","China"
"1.0.16.0","1.0.31.255","16781312","16785407","JP","Japan"

1.3 For JDK 7 and above, uses try-resources.

CSVReader.csv

package com.mkyong.csv;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class CSVReader {

    public static void main(String[] args) {

        String csvFile = "/Users/mkyong/csv/country.csv";
        String line = "";
        String cvsSplitBy = ",";

        try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {

            while ((line = br.readLine()) != null) {

                // use comma as separator
                String[] country = line.split(cvsSplitBy);

                System.out.println("Country [code= " + country[4] + " , name=" + country[5] + "]");

            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

Copy

Output

Country [code= "AU" , name="Australia"]
Country [code= "CN" , name="China"]

Comments

Popular posts from this blog

Building an AI-Powered App with Next.js, Tailwind CSS, and OpenAI API

๐ŸŒ Build & Deploy a Website with Node.js and Express

✨ Build & Deploy a Stunning ReactJS UI Step by Step (Full Tutorial + Free Hosting)