Java

Java: indexOf to find string occurrences

Posted on

String str = “tejuhelloreddytejuhello”;
String findStr = “teju”;
int lastIndex = 0;
int count = 0;

while (lastIndex != -1) {

       lastIndex = str.indexOf(findStr, lastIndex);

if (lastIndex != -1) {
count++;
        lastIndex += findStr.length();
}

}

System.out.println(count);

Advertisements

Java : How to find duplicate characters in String

Posted on Updated on

 

This program would find out the duplicate characters in a String and would display the count of them.

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
 
public class Details {
 
  public void countDupChars(String str){
 
    //Create a HashMap 
    Map<Character, Integer> map = new HashMap<Character, Integer>(); 
 
    //Convert the String to char array
    char[] chars = str.toCharArray();
 
    /* logic: char are inserted as keys and their count
     * as values. If map contains the char already then
     * increase the value by 1
     */
    for(Character ch:chars){
      if(map.containsKey(ch)){
         map.put(ch, map.get(ch)+1);
      } else {
         map.put(ch, 1);
        }
    }
 
    //Obtaining set of keys
    Set<Character> keys = map.keySet();
 
    /* Display count of chars if it is
     * greater than 1. All duplicate chars would be 
     * having value greater than 1.
     */
    for(Character ch:keys){
      if(map.get(ch) > 1){
        System.out.println("Char "+ch+" "+map.get(ch));
      }
    }
  }
 
  public static void main(String a[]){
    Details obj = new Details();
    System.out.println("\nString: #@$@!#$%!!%@");
    System.out.println("-------------------------");
    obj.countDupChars("#@$@!#$%!!%@");
  }
}

Output:

String: #@$@!#$%!!%@
-------------------------
Char # 2
Char ! 3
Char @ 3
Char $ 2
Char % 2

Java : Checked Exceptions and Unchecked Exceptions

Posted on Updated on

Checked are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.

//CheckedException
public class CheckedException {

public void method1()throws Exception{

}

public void method2() {

try {
method1();    // If no try catch block here , compiler will throw error
}catch(Exception e) {

}

}
}

//UnCheckedException
public class UnCheckedException {

public void method1()  throws NullPointerException{

}

public void method2() {
method1();   // No need to have try and catch block here , as it is runtime exception (or)  unchecked exception , JVM will take care .
}

}

Java : Serialization and De-serialization of a Java object

Posted on Updated on

Below is example for how to Serialize and DeSerialize java objects

// Java code for serialization and deserialization of a Java object

import java.io.*;

class Demo implements java.io.Serializable
{

public int a;
public String b;

// Default constructor
public Demo(int a, String b)
{
this.a = a;
this.b = b;
}

}

class Test
{

public static void main(String[] args)
{
Demo object = new Demo(1, “geeksforgeeks”);
String filename = “file.ser”;

// Serialization
try
{
//Saving of object in a file
FileOutputStream file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);

// Method for serialization of object
out.writeObject(object);

out.close();
file.close();

System.out.println(“Object has been serialized”);

}

catch(IOException ex)
{
System.out.println(“IOException is caught”);
}

Demo object1 = null;

// Deserialization
try
{
// Reading the object from a file
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);

// Method for deserialization of object
object1 = (Demo)in.readObject();

in.close();
file.close();

System.out.println(“Object has been deserialized “);
System.out.println(“a = ” + object1.a);
System.out.println(“b = ” + object1.b);

}

catch(IOException ex)
{
System.out.println(“IOException is caught”);
}

catch(ClassNotFoundException ex)
{
System.out.println(“ClassNotFoundException is caught”);
}

}

}

Auto boxing and Unboxing in Java

Posted on Updated on

int a = 56;
Integer i = a; // Auto Boxing
Integer s = 45;
int a = s;// auto UnBoxing

Java :How to compare elements in two arrays

Posted on Updated on

Without java collections:

public class CompareArrays {
public static void main(String[] args) {

Integer[] arr1 = {4,7,3,9,2};
Integer[] arr2 = {3,2,12,9,40,32,4};
for(int i=0;i<arr1.length;i++){
for(int j=0;j<arr2.length;j++){
if(arr1[i]==arr2[j]){
        System.out.println(arr1[i]);
}
}
}

      }
}

With java collections : 

 import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class CompareArrays {
public static void main(String[] args) {

Integer[] arr1 = {4,7,3,9,2};
Integer[] arr2 = {3,2,12,9,40,32,4};
Set set1 = new HashSet(Arrays.asList(arr1));
Set set2 = new HashSet(Arrays.asList(arr2));
set1.retainAll(set2);    // Intersection method 
Iterator it = set1.iterator();
while(it.hasNext()){
System.out.println(it.next());
}

}
}

Spring REST :How to export data to CSV file

Posted on Updated on

Spring REST Service Code for exporting to CSV file :

@RequestMapping(“/exportLogsToCSV.do”)
public void exportLogsToCSV(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String filename = “logs.csv”;
String filename = “logs.csv”;
String from = request.getParameter(“from”);
 List logsList = new ArrayList();
StringBuffer sb = new StringBuffer();
if (from.equalsIgnoreCase(“SubLogs”)) { // from is the hidden value of input element we defined in our UI
filename = “subscription_management.csv”; // name you are giving to your csv file
String emailAddress = request.getParameter(“emailAddress”);
String productName = request.getParameter(“productName”);
logsList=subscriptionMgmtService.getSubscribedUsersByProductnameAndEmail(productName, emailAddress);  // we inject the service in the controller and call the method defined in the service to get the search results
sb.append(“Email Address” + “,” + “Product Name” + “,” + “Solution Type” + “,” + “Status”); sb.append(“\n”);
// you are appending the headings which you want in the dispaly to the string buffer in the above code
if (logsList.size() > 0) {
Iterator it = logsList.iterator();
String status=”active”;
while (it.hasNext()) {
UserSubscription userSubscription = (UserSubscription) it.next(); sb.append(safeString(userSubscription.getEmailAddress()) + “,” + safeString(userSubscription.getProductNames()) + “,” + safeString(userSubscription.getSolutionTypes()) + “,” + status);
sb.append(“\n”);
// here you are appending the values you get from the database for that particular input search to the string buffer.
}
}
}
response.setContentType(“application/csv”);
response.setHeader(“content-disposition”, “attachment; filename=\”” + filename + “\””); PrintWriter write = response.getWriter();
write.write(sb.toString());
response.setStatus(response.SC_OK);
}
public static String safeString(String value) {
return (value == null) ? “” : “\””+value+”\””;
}