Java Example Codes

Core Java Interview Questions

Java Example Codes


Reverse a String

import java.io.FileNotFoundException;

import java.io.IOException;
public class StringReverseCode {
public static void main(String args[]) throws FileNotFoundException, IOException {
//original string
String str = "This is some string which need to be reversed";
System.out.println("Original String: " + str);
//reversed string using Stringbuffer
String reverseStr = new StringBuffer(str).reverse().toString();
System.out.println("Reverse String in Java using StringBuffer: " + reverseStr);
//reverse String iteratively
reverseStr = reverse(str);
System.out.println("Reverse String in Java using Iteration: " + reverseStr);
//reverse String recursively
reverseStr = reverseRecursively(str);
System.out.println("Reverse String in Java using Recursion: " + reverseStr);
}
public static String reverse(String str) {
StringBuilder strBuilder = new StringBuilder();
char[] strChars = str.toCharArray();
for (int i = strChars.length - 1; i >= 0; i--) {
strBuilder.append(strChars[i]);
}
return strBuilder.toString();
}
}

Duplicate Chracters in a String

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
/* * This program finds duplicate charcters in a string and print them */ public class DuplicateCharacters{
public static void main(String args[]) {
printDuplicateCharacters("java");
printDuplicateCharacters("cplusplus");
printDuplicateCharacters("programme");
}
public static void printDuplicateCharacters(String word) {
char[] characters = word.toCharArray();
// build HashMap with character and number of times they appear in String
Map charMap = new HashMap();
for (Character ch : characters) {
if (charMap.containsKey(ch)) {
charMap.put(ch, charMap.get(ch) + 1);
} else {
charMap.put(ch, 1);
}
}
// Iterate through HashMap to print all duplicate characters of String
Set> entrySet = charMap.entrySet();
System.out.printf("List of duplicate characters in String '%s' %n", word);
for (Map.Entry entry : entrySet) {
if (entry.getValue() > 1) {
System.out.printf("%s : %d %n", entry.getKey(), entry.getValue());
}
}
}
}

Length of a String


/*

* This program find the length of a given string

*/

public class StringFromatExample {
public static void main(String[] args) {
String s = "this is given string";
int strLength = s.length();
System.out.println("The length of the given string is : "+strLength);
System.out.println("The length of the given string : ".length());
}
}


Copyright © by Zafar Yasin. All rights reserved.