Remove duplicates from array


// simple java program to remove
// duplicates

class Main
{
// Function to remove duplicate elements
// This function returns new size of modified
// array.
static int removeDuplicates(int arr[], int n)
{
// Return, if array is empty
// or contains a single element
if (n==0 || n==1)
return n;

int[] temp = new int[n];

// Start traversing elements
int j = 0;
for (int i=0; i<n-1; i++)
// If current element is not equal
// to next element then store that
// current element
if (arr[i] != arr[i+1])
temp[j++] = arr[i];

// Store the last element as whether
// it is unique or repeated, it hasn't
// stored previously
temp[j++] = arr[n-1];

// Modify original array
for (int i=0; i<j; i++)
arr[i] = temp[i];

return j;
}

public static void main (String[] args)
{
int arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5};
int n = arr.length;

n = removeDuplicates(arr, n);

// Print updated array
for (int i=0; i<n; i++)
System.out.print(arr[i]+" ");
}
}

Prime Number

A prime number is a whole number greater than 1 whose only factors are 1 and itself. A factor is a whole numbers that can be divided evenly into another number. The first few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29. Numbersthat have more than two factors are called composite numbers.
int n = 15, f=0;

for (int i = 2; i < n; i++)
{
                if (n % i == 0)
                    f = 1;
}

            if (f == 0)
            {
                System.out.println( "Given Number is Prime Number");
            }else{
                System.out.println( "Given Number is Not Prime Number");
            }

Android Lint

Android Studio provides a code scanning tool called lint that can help you to identify and correct problems with the structural quality of your code without your having to execute the app or write test cases. Each problem detected by the tool is reported with a description message and a severity level, so that you can quickly prioritize the critical improvements that need to be made. Also, you can lower the severity level of a problem to ignore issues that are not relevant to your project, or raise the severity level to highlight specific problems.

The lint tool checks your Android project source files for potential bugs and optimization improvements for correctness, security, performance, usability, accessibility, and internationalization. When using Android Studio, configured lint and IDE inspections run whenever you build your app. However, you can manually run inspections or run lint from the command line.



Longest Palindrome Substring in a String

Longest Palindrome Substring in a String Algorithm

The key point here is that from the mid of any palindrome string if we go to the right and left by 1 place, it’s always the same character.

For example 12321, here mid is 3 and if we keep moving one position on both sides, we get 2 and then 1. We will use the same logic in our java program to find out the longest palindrome.

However, if the palindrome length is even, the mid-size is also even. So we need to make sure in our program that this is also checked. For example, 12333321, here mid is 33 and if we keep moving one position in both sides, we get 3, 2 and 1.


package com.journaldev.util;

public class LongestPalindromeFinder {

public static void main(String[] args) {
System.out.println(longestPalindromeString("1234"));
System.out.println(longestPalindromeString("12321"));
System.out.println(longestPalindromeString("9912321456"));
System.out.println(longestPalindromeString("9912333321456"));
System.out.println(longestPalindromeString("12145445499"));
System.out.println(longestPalindromeString("1223213"));
System.out.println(longestPalindromeString("abb"));
}

static public String intermediatePalindrome(String s, int left, int right) {
if (left > right) return null;
while (left >= 0 && right < s.length()
&& s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
return s.substring(left + 1, right);
}

// O(n^2)
public static String longestPalindromeString(String s) {
if (s == null) return null;
String longest = s.substring(0, 1);
for (int i = 0; i < s.length() - 1; i++) {
//odd cases like 121
String palindrome = intermediatePalindrome(s, i, i);
if (palindrome.length() > longest.length()) {
longest = palindrome;
}
//even cases like 1221
palindrome = intermediatePalindrome(s, i, i + 1);
if (palindrome.length() > longest.length()) {
longest = palindrome;
}
}
return longest;
}

}

Android Device Monitor

Android Device Monitor is a stand-alone tool that provides a graphical user interface for several Android application debugging and analysis tools. The Monitor tool does not require installation of a integrated development environment, such as Eclipse, and encapsulates the following tools:

  1. DDMS
  2. Tracer for OpenGL ES
  3. Hierarchy Viewer
  4. Traceview
  5. Pixel Perfect magnification viewer
Android ships with a debugging tool called the Dalvik Debug Monitor Server (DDMS), which provides port-forwarding services, screen capture on the device, thread and heap information on the device, logcat, process, and radio state information, incoming call and SMS spoofing, location data spoofing, and more.

Traceview is a graphical viewer for execution logs saved by your application. Traceview can help you debug your application and profile its performance.

Hierarchy Viewer allows you to debug and optimize your user interface. It provides a visual representation of the layout's View hierarchy (the Layout View) and a magnified inspector of the display (the Pixel Perfect View).

Traceview
Traceview is a graphical viewer for execution logs saved by your application. Traceview can help you debug your application and profile its performance.

Pixel Perfect magnification viewer

For Android Studio Tools Click Here

Demo Code

/******************************************************************************

*******************************************************************************/

public class Main
{
    void palindrome(String w)
{
    StringBuilder s2 = new StringBuilder(w);
        s2.reverse();
     
        String s = s2.toString();
        System.out.print("The String is "+s+" and is");
       
        if(w.equals(s))
          System.out.println(" a Palindrome");
         else
           System.out.println(" not a Palindrome");
}

int fibonacci (int i){
 
   if(i==0)
        return 0;
   else if(i==1 || i==2)
       return 1;
 
    return fibonacci(i-1)+fibonacci(i-2);
 
}

int factorial (int factorial_number){
 
    if(factorial_number==0)
        return 1;
    else
        return factorial_number*factorial(factorial_number-1);
}

void countFrequency(String str, char ch, int count){
 
    int occ = 0, i;

  // If given count is 0
  // print the given string and return
  if (count == 0) {
   System.out.println(str);
   return;
  }

  // Start traversing the string
  for (i = 0; i < str.length(); i++) {

   // Increment occ if current char is equal
   // to given character
   if (str.charAt(i) == ch)
    occ++;

   // Break the loop if given character has
   // been occurred given no. of times
   if (occ == count)
    break;
  }

  // Print the string after the occurrence
  // of given character given no. of times
  if (i < str.length() - 1)
   System.out.println(str.substring(i + 1));

  // Otherwise string is empty
  else
   System.out.println("Empty string");
 
}

public static void main(String[] args) {
 
    Main demo = new Main();
    demo.palindrome("atata");
 
    int number=5;
    System.out.println("Entered Number is "+number);
    System.out.println("The "+number+"th fibonacci number is: "+demo.fibonacci(number));
 
    System.out.print("Fibonacci Series: ");
    for (int i=0;i<number;i++)
            System.out.print(demo.fibonacci(i)+", ");
     
System.out.println("\nFactorial of "+number+" is "+demo.factorial(number));
 
        //Find Duplicate Items in Array List
    int [] arr = new int [] {1,2,3,4,3,5,6,6,8,9};
    System.out.print("Duplicate elements in given array: ");
    for(int i=0;i<arr.length;i++)
    {
        for(int j=i+1;j<arr.length;j++)
        {
            if(arr[i]==arr[j])
            System.out.print(arr[j]+" ");
        }
    }

    System.out.println(" ");
    demo.countFrequency("geeksforgeeks",'e',3);
 
}
}

Print the string after the specified character has occurred given no. of times

Given a string, a character, and a count, the task is to print the string after the specified character has occurred count number of times.Print “Empty string” in case of any unsatisfying conditions.(Given character is not present, or present but less than given count, or given count completes on last index). If given count is 0, then given character doesn’t matter, just print the whole string.

// Java program for above implementation 

public class GFG 
// Method to print the string 
static void printString(String str, char ch, int count) 
int occ = 0, i; 
// If given count is 0 
// print the given string and return 
if (count == 0) { 
System.out.println(str); 
return; 
// Start traversing the string 
for (i = 0; i < str.length(); i++) { 
// Increment occ if current char is equal 
// to given character 
if (str.charAt(i) == ch) 
occ++; 
// Break the loop if given character has 
// been occurred given no. of times 
if (occ == count) 
break; 
// Print the string after the occurrence 
// of given character given no. of times 
if (i < str.length() - 1) 
System.out.println(str.substring(i + 1)); 
// Otherwise string is empty 
else
System.out.println("Empty string"); 
// Driver Method 
public static void main(String[] args) 
String str = "geeks for geeks"; 
printString(str, 'e', 2); 


Examples:

Input  :  str = "This is demo string" 
          char = i,    
          count = 3
Output :  ng

Input :  str = "geeksforgeeks"
         char = e, 
         count = 2
Output : ksforgeeks

Count frequency of characters in a string

Use a java Map and map a char to an int. You can then iterate over the characters in the string and check if they have been added to the map, if they have, you can then increment its value.

HashMap<Character, Integer> map = new HashMap<Character, Integer>();
String s = "aasjjikkk"; 

for (int i = 0; i < s.length(); i++)
 {
        char c = s.charAt(i);
        Integer val = map.get(c);
       
        if (val != null) { 
                                  map.put(c, new Integer(val + 1));
                                } else { 
                                              map.put(c, 1);
                                            }
                                }
}

Reverse a String

There are many ways of reversing a String in Java for whatever reason you may have. Today, we will look at a few simple ways of reversing a String in Java.

Method 1:
import java.util.Scanner;

public class ReverseString
{
public static void main(String[] args)
{
System.out.println("Enter string to reverse:");

Scanner read = new Scanner(System.in);
String str = read.nextLine();
String reverse = "";

for(int i = str.length() - 1; i >= 0; i--)
{
reverse = reverse + str.charAt(i);
}

System.out.println("Reversed string is:");
System.out.println(reverse);
}
}

Method 2:
import java.util.Scanner;

public class ReverseString
{
public static void main(String[] args)
{
System.out.println("Enter string to reverse:");

Scanner read = new Scanner(System.in);
String str = read.nextLine();

StringBuilder sb = new StringBuilder();

for(int i = str.length() - 1; i >= 0; i--)
{
sb.append(str.charAt(i));
}

System.out.println("Reversed string is:");
System.out.println(sb.toString());
}
}

Method 3:
import java.util.Scanner;

public class ReverseString
{
public static void main(String[] args)
{
System.out.println("Enter string to reverse:");

Scanner read = new Scanner(System.in);
String str = read.nextLine();

StringBuilder sb = new StringBuilder(str);

System.out.println("Reversed string is:");
System.out.println(sb.reverse().toString());
}
}

Print the duplicate elements of an array

In this program, we need to print the duplicate elements present in the array. This can be done through two loops. The first loop will select an element and the second loop will iteration through the array by comparing the selected element with other elements. If a match is found, print the duplicate element.



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

//Initialize example array
int [] arr = new int [] {1, 2, 3, 4, 2, 7, 8, 8, 3};

System.out.println("Duplicate elements in given array: ");

//Searches for duplicate element
for(int i = 0; i < arr.length; i++) {
    for(int j = i + 1; j < arr.length; j++) {
                            if(arr[i] == arr[j])
                             System.out.println(arr[j]);
}}}}

OR

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

Set<Integer> set = new HashSet<Integer>();

for(int i = 0; i < array.length ; i++)
{
//If same integer is already present then add method will return FALSE
if(set.add(array[i]) == false)
{
          System.out.println("Duplicate element found : " + array[i]);
}

}

Removing white spaces

Method 1:
String s = "This is a sentence";
String s2 = s.trim();


Method 2:
String s = "This is a sentence";
String s2 = s.replaceAll("\\s", "");

Find Factorial of a number

public static int factorial(int number){
//base case
if(number == 0){
return 1;
}
return number*factorial(number -1);
}

(OR)

public static int factorial(int number){
int result = 1;
while(number != 0){
result = result*number;
number--;
}

return result;
}
}

Print Fibonacci Series

public static int fibonacci2(int number)
{
 if(number == 1 || number == 2)
{ return 1; }

 int fibo1=1, fibo2=1, fibonacci=1; 

for(int i= 3; i<= number; i++)
 fibonacci = fibo1 + fibo2;  //Fibonacci number is sum of previous two Fibonacci number 
 fibo1 = fibo2;
 fibo2 = fibonacci; 
}

 return fibonacci; //Fibonacci number 
}
}

(OR)

public static int fibonacci(int number)
{
 if(number == 1 || number == 2)
{ return 1; } 
return fibonacci(number-1) + fibonacci(number -2); //tail recursion 
}

Check if String Palindrome

We can check palindrome string by reversing string and checking whether it is equal to the original string or not.

checkIfPalindrome(String s)
{

StringBuilder s2 = new StringBuilder(s);
s2.reverse();

String rev_s2 = s2.toString();

if(s.equals(rev_s2))
{ return true; }
else
{ return false; }


}

(OR)

public class Palindrome {
public static void main(String[] args) {
String str = "OOLOO";
StringBuffer newStr =new StringBuffer();
for(int i = str.length()-1; i >= 0 ; i--) {
newStr = newStr.append(str.charAt(i));
}
if(str.equalsIgnoreCase(newStr.toString())) {
System.out.println("String is palindrome");
} else {
System.out.println("String is not palindrome");
}
}

}