1 : HOW TO CREATE SINGLETONE CLASS ?
==================================
Note:=>There are two forms of singleton design pattern
Early Instantiation: creation of instance at load time.
ex: private static A obj=new A(); //Early, instance will be created at load time
Lazy Instantiation: creation of instance when required.
ex: if (obj == null){
obj = new Singleton();//instance will be created at request time
}
Ex:How to create Singleton design pattern?
Note:-(below bracket mean mandatory)
1- private (static) memberes
2- (private) constructor
3- (static) factory method to return class object
Static member: It gets memory only once because of static, it contains the instance
of the Singleton class.
Private constructor: It will prevent to instantiate the Singleton class from
outside the class.
Static factory method: This provides the global point of access to the Singleton
object and returns the instance to the caller.
package com.intellect;
public class SingleToneClass {
private static SingleToneClass obj;
private SingleToneClass()
{
// constructor
}
public static SingleToneClass getInstance()
{
if(obj==null)
{
obj = new SingleToneClass();
}
return obj;
public void MyFunction()
{
System.out.println("this is my function called");
}
public static void main(String[] args)
{
SingleToneClass obj = SingleToneClass.getInstance();
obj.MyFunction();
System.out.println("HashCode 1 : "+obj.hashCode());
System.out.println("_____________________________");
SingleToneClass obj2 = SingleToneClass.getInstance();
obj2.MyFunction();
System.out.println("HashCode 2 : "+obj2.hashCode());
System.out.println("_____________________________");
SingleToneClass obj3 = SingleToneClass.getInstance();
obj3.MyFunction();
System.out.println("HashCode 3 : "+obj3.hashCode());
System.out.println("_____________________________");
OP:
---
this is my function called
HashCode 1 : 705927765
_____________________________
this is my function called
HashCode 2 : 705927765
_____________________________
this is my function called
HashCode 3 : 705927765
_____________________________
2 :HOW TO WRITE OUR OWN IMUTAIBLE STRING CLASS:
===============================================
1-class (final),
2-var private (final), or they�re initialized only once inside the constructor
3-(Don�t) provide setter methods.
4-Methods which if modify the state of the class, you must always return a new
instance of the class.
package com.intellect;
public final class ImutableString {
private final int Id;
private final String Name;
public ImutableString(int i, String name)
{
this.Id=i;
this.Name=name;
public ImutableString modify(int j, String empname)
{
if(this.Id==j && this.Name==empname)
{
return this;
}
else
{
return new ImutableString(102,"Badri lal");
}
public static void main(String[] args)
{
ImutableString obj = new ImutableString(101,"vivek ramteke");
System.out.println(obj.hashCode());
System.out.println("Id : "+obj.Id +"Name :"+obj.Name);
ImutableString obj2=obj.modify(102,"badri lal");
System.out.println(obj2.hashCode());
System.out.println("Id : "+obj2.Id +"Name :"+obj2.Name);
ImutableString obj3=obj.modify(101,"vivek ramteke");
System.out.println(obj3.hashCode());
System.out.println("Id : "+obj3.Id +"Name :"+obj3.Name);
OP:
---
366712642
Id : 102Name :Badri lal
Old Object return
705927765
Id : 101Name :vivek ramteke
3 : HOW TO OVERRIDE hashCode() , equals(), toString(), ? or how to provide our
own hashcode ?
===================================================================================
============
package com.app;
package com.app;
public class Employee {
int id;
String name;
public Employee(int id, String name) {
this.id=id;
this.name=name;
}
// hashCode overriding
public int hashCode(){
return id;
}
// equals overriding
@override
public boolean equals(Object obj)
{
if(obj==this)
return true;
if(!(obj instanceof Employee))
{
return false;
}
Employee ob = (Employee)obj;
return ob.id==id && ob.name.equals(name);
}
// toString() overriding
public String toString()
{
return "id : "+id +" Name : "+name;
}
public static void main(String[] args) {
Employee obj= new Employee(123,"BL");
Employee obj2= new Employee(123,"BL");
System.out.println("HC : "+obj.hashCode());
System.out.println(obj);
System.out.println("Equals : "+ obj.equals(obj2));
System.out.println("HC : "+obj2.hashCode());
System.out.println(obj2);
System.out.println("Equals : "+obj2.equals(obj));
}
}
Q: WRITE CUSTOM EXCEPTION HANDLING CODE:
=========================================
ex:1:
class MyException extends Exception
{
public MyException(String s)
{
super(s);
}
}
public class HandlingClass
{
public static void main(String args[])
{
try
{
throw new MyException("Exception occured !");
}
catch (MyException ex)
{
System.out.println("Exception Caught");
System.out.println(ex.getMessage());
}
}
}
ex:2
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
}
}
class TestCustomException1{
static void validate(int age) throws InvalidAgeException
{
if(age<18)
throw new InvalidAgeException("not valid age");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
{
try{
validate(13);
}
catch(Exception m)
{
System.out.println("Exception occured: "+m.getMessage());
}
System.out.println("rest of the code...");
}
}
ex3:
class MyException extends Exception
{
public MyException(String msg)
{
super(msg);
}
}
public class CustomException {
public static void pin(int pin) throws MyException
{
if(pin !==12345 )
{
throw new MyException("Wrong pin entered ! Please enter correct
pin .");
}
else
{
System.out.println("Welcome user : "+pin);
}
}
public static void main(String[] args)
{
try{
pin(1234);
}
catch(MyException ex)
{
System.out.println("Exception catched :-"+ex.getMessage());
}
}
ex4 :
package com.intellect;
class Employee
{
}
class EmpNotFoundException extends Exception
{
EmpNotFoundException(String msg)
{
super(msg);
}
}
class EmpManager
{
public Employee find(String EmpId) throws EmpNotFoundException
{
if(EmpId.equals("12345"))
{
System.out.println("Employee object is created with id "+EmpId);
return new Employee();
}
else
{
throw new EmpNotFoundException("Emp id not found : "+EmpId);
}
}
}
public class CustomExceptionCode {
public static void main(String[] args) {
EmpManager obj = new EmpManager();
try{
Employee emp = obj.find("12345");
}
catch(EmpNotFoundException e){
System.err.print(e);
}
OP:
---
Employee object is created with id 12345
Q : HOW MANY WAYS ARE TO ITERATE HASHMAP ?
------------------------------------------
WAYS TO ITERATE HASHMAP ?
========================
1 : using methods keySet() and values() :
------------------------------------------
only for key :-
---------------
for(String str : hsmp1.keySet())
{
System.out.println(str);
}
or
for(Integer stno : hsmp2.keySet())
{
System.out.println(stno);
}
only for values :-
------------------
for(String strnm : hsmp1.values())
{
System.out.println(strnm);
}
or
for(String city : hsmp2.values())
{
System.out.println(city);
}
2 :Map.entrySet() using For-Each loop :
---------------------------------------
for(Entry<String, String> entry: hsmp1.entrySet())
{
System.out.println(entry.getKey()+" "+entry.getValue());
}
or
for(Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
3 : using iterators over Map.Entry<K, V> :
=====================================
Iterator<Map.Entry<String, String>> itr= hsmp1.entrySet().iterator();
while(itr.hasNext())
{
Map.Entry<String, String> entry=itr.next();
System.out.println(entry.getKey()+" "+entry.getValue());
}
or
Iterator<Map.Entry<Integer, String>> itr2 =
hsmp2.entrySet().iterator();
while(itr2.hasNext())
{
Map.Entry<Integer, String> entry = itr2.next();
System.out.println(entry.getKey() +" "+entry.getValue());
}
4: forEach(action) method :
-----------------------------
hsmp2.forEach((k,v) -> System.out.println(k +" "+v));
5: iterating through key and searching values using get() :
-----------------------------------------------------------
for(Integer k: hsmp.keySet())
{
String v = hsmp.get(k);
System.out.println(v);
}
***********************COLLECTION**********
Q-How to remove duplicate/Repeated elements from ArrayList ?
==============================================================
1 : whithout using collection
-------------------------------
package com.intellect;
import java.util.ArrayList;
public class MyHashMap {
public static void main(String[] args) {
ArrayList<Object> al = new ArrayList<Object>();
al.add("BADRI LAL");
al.add("Monika");
al.add("Nagendra");
al.add("BADRI LAL");
al.add("101");
al.add("JAVA");
al.add("101");
al.add(101);
System.out.println("Befor duplicate :"+al);
for(int i=0; i<al.size(); i++){
for(int j=i+1; j<al.size(); j++)
{
if(al.get(i).equals(al.get(j)))
{
al.remove(j);
j--;
}
}
}
System.out.println("after removed duplicate :"+al);
}
Remove using collection object HashSet :
========================================
package com.intellect;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
public class MyHashMap {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("BADRI LAL");
al.add("BK");
al.add("Nagendra");
al.add("BADRI LAL");
al.add("101");
al.add("JAVA");
al.add("101");
System.out.println("al :"+al);
HashSet<String> hashset = new HashSet<String>(al);
System.out.println("hashset"+hashset);
al.clear();
al.addAll(hashset);
System.out.println("al"+al);
EXAMPLE 1: [sorts the list elements Student the basis of age]
==========
package com.intellect;
import java.util.ArrayList;
import java.util.Collections;
class Student implements Comparable<Student>
{
int rollno;
String name;
int age;
public int getRollno() {
return rollno;
}
public void setRollno(int rollno) {
this.rollno = rollno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student(int rollno, String name, int age) {
super();
this.rollno = rollno;
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student [rollno=" + rollno + ", name=" + name + ", age=" + age
+ "]";
}
@Override
public int compareTo(Student o) {
//Acending
return this.age-o.age;
//Descending
//return -this.age-o.age
[Note:- for name use compareTo() : return -
this.getName().compareTo(o.getName());]
}
}
public class ComparableSorting {
public static void main(String[] args) {
ArrayList<Student> al = new ArrayList<Student>();
al.add(new Student(101,"Badri lal",29));
al.add(new Student(105,"Nagendra",27));
al.add(new Student(111,"Monu",30));
Collections.sort(al);
for(Student st:al)
{
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
op:
===
111 Monu 30
101 Badri lal 29
105 Nagendra 27
EXAMPLE 2:
==========
package com.intellect;
import java.util.ArrayList;
import java.util.Collections;
class Employee implements Comparable<Employee>
{
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return Salary;
}
public void setSalary(int salary) {
Salary = salary;
}
int Salary;
public Employee(String name, int salary) {
super();
this.name = name;
Salary = salary;
}
@Override
public int compareTo(Employee o)
{
//Ascending
//return this.Salary-o.Salary;
//Descending
return -this.Salary-o.Salary;
//on name : return -this.getName().compareTo(o.getName());
}
public class ComparableSoring {
public static void main(String[] args) {
ArrayList<Employee> e = new ArrayList<Employee>();
e.add(new Employee("Badri",101));
e.add(new Employee("Nagendra",102));
e.add(new Employee("Dinesh",104));
Collections.sort(e);
for(Employee e1: e)
{
System.out.println(e1.name+" "+e1.Salary);
}
/*package com.intellect;
import java.util.ArrayList;
import java.util.Collections;
class Employee1 implements Comparable<Employee>
{
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return Salary;
}
public void setSalary(int salary) {
Salary = salary;
}
int Salary;
public Employee1(String name, int salary) {
super();
this.name = name;
Salary = salary;
}
@Override
public int compareTo(Employee o)
{
return -this.getName().compareTo(o.getName());
}
public class ComparableSoring {
public static void main(String[] args) {
ArrayList<Employee> e = new ArrayList<Employee>();
e.add(new Employee("Badri",101));
e.add(new Employee("Nagendra",102));
e.add(new Employee("Dinesh",104));
Collections.sort(e);
for(Employee e1: e)
{
System.out.println(e1.name+" "+e1.Salary);
}
EXAMPLE 1: COMPARATOR SORTING ACCORDING TO DEPT , SALARY
==========================================================
package com.intellect;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
//Employee class with setter/getter/toStirng
class Employee
{
int id;
String name;
String Dept;
int salary;
public Employee(int id, String name, String dept, int salary) {
super();
this.id = id;
this.name = name;
Dept = dept;
this.salary = salary;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", Dept=" + Dept + ",
salary=" + salary + "]";
}
}
//salary comparator class
class salaryComparator implements Comparator<Employee>
{
@Override
public int compare(Employee e1, Employee e2) {
return e1.salary-e2.salary;
}
}
//Dept comparator class
class DeptComparator implements Comparator<Employee>
{
@Override
public int compare(Employee e1, Employee e2)
{
return e1.Dept.compareTo(e2.Dept);
}
}
public class ComparatorSorting {
public static void main(String[] args) {
ArrayList<Employee> obj = new ArrayList<Employee>();
obj.add(new Employee(101,"Badri","Developer",50000));
obj.add(new Employee(102,"Monu","HR",30000));
obj.add(new Employee(103,"Nagendra","Manager",33000));
//sorting by salary
Collections.sort(obj, new salaryComparator());
//sorting by dept
Collections.sort(obj, new DeptComparator());
for(Employee e1: obj)
{
System.out.println(e1.id+" "+e1.name+" "+e1.Dept+" "+e1.salary);
}
}
COMPARATOR
------------
COMPARATOR
package com.intellect;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
//Employee class with setter/getter/toStirng
class Employee
{
int id;
String name;
String Dept;
int salary;
public Employee(int id, String name, String dept, int salary) {
super();
this.id = id;
this.name = name;
Dept = dept;
this.salary = salary;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", Dept=" + Dept + ",
salary=" + salary + "]";
}
//salary comparator class
class salaryComparator implements Comparator<Employee>
{
@Override
public int compare(Employee e1, Employee e2) {
return e1.salary-e2.salary;
}
}
//Dept comparator class
class DeptComparator implements Comparator<Employee>
{
@Override
public int compare(Employee e1, Employee e2) {
// TODO Auto-generated method stub
return e1.Dept.compareTo(e2.Dept);
}
}
public class ComparatorSorting {
public static void main(String[] args) {
ArrayList<Employee> obj = new ArrayList<Employee>();
obj.add(new Employee(101,"Badri","Developer",50000));
obj.add(new Employee(102,"Monu","HR",30000));
obj.add(new Employee(103,"Nagendra","Manager",33000));
//sorting by salary
Collections.sort(obj, new salaryComparator());
//sorting by dept
//Collections.sort(obj, new DeptComparator());
for(Employee e1: obj)
{
System.out.println(e1.id+" "+e1.name+" "+e1.Dept+" "+e1.salary);
}
}
}
Q : TO FIND PALINDROME NO BW RANGE. ?
--------------------------------------
package com.intellect;
public class Palindrome {
public static int check(int num)
{
int result=0;
while(num>0)
{
result= result*10 + (num%10);
num=num/10;
}
return result;
}
public static void main(String[] args) {
for(int i=1; i<1000; i++ )
{
if(i==check(i))
{
System.out.println(i);
}
}
}
Q:-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.
package com.java2novice.algos;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class OrderByValue {
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
1: DUPLICATE CHARACTER IN WORD OR STRING ?
------------------------------------------
ex: WELCOME
sol:
C : 1
E : 2
W : 1
L : 1
M : 1
SOL:
public class Duplicate_Char {
static void findDuplicate(String str)
{
char[] arr = str.toCharArray();
HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
for(Character ch : arr)
{
if(hm.containsKey(ch))
{
hm.put(ch, hm.get(ch)+1);
}
else
{
hm.put(ch, 1);
}
//set
Set<Character> set =hm.keySet();
for(Character ch : set)
{ //TO PRINT ONLY DUPLICATE USE IF
CONDITION
// if(hm.get(ch)>1)
System.out.println(ch +" : "+hm.get(ch)); <-// this print all char
with accurance
}
}
public static void main(String[] args) {
findDuplicate("WELCOME");
2: REPEATED/DUPLICATE WORDS IN STRING ?
=======================================
EX: java , php , java , parl"
SOL:
java: 2
php : 1
, : 3
parl: 1
PROG:
package com.app;
import java.util.HashMap;
import java.util.Set;
public class Duplicate_Words {
static void Duplicate_word(String str)
{
String[] arr =str.split(" ");
HashMap<String, Integer> hm = new HashMap<String, Integer>();
for(String s : arr)
{
if(hm.containsKey(s))
{
hm.put(s, hm.get(s)+1);
}
else
{
hm.put(s, 1);
}
}
Set<String> set = hm.keySet();
for(String s: set)
{
System.out.println( s +" : "+hm.get(s));
}
}
public static void main(String[] args) {
Duplicate_word("java , php , java , parl");
or
==
Set<Map.Entry<Character, Integer>> entrySet = hm.entrySet();
for (Map.Entry<Character, Integer> entry : entrySet)
{
if (entry.getValue() > 1)
{
System.out.printf( entry.getKey() + + entry.getValue());
}
}
Q Java program to count occurrences of a perticular word in String ?
--------------------------------------------------------------
Ex:- "Today is Monday"; -> count number of "a" on this String.
public class CountCharacters
{
public static void main(String args[])
{
String input = "Today is Monday"; //count number of "a" on this String.
1 : //counting occurrence of character with loop
int charCount = 0;
for(int i =0 ; i<input.length(); i++)
{
if(input.charAt(i) == 'a')
{
charCount++;
}
}
System.out.println("count of character 'a' on String: 'Today is Monday'
using for loop " + charCount);
or
2: //
charCount = 0;
for(char ch: input.toCharArray())
{
if(ch == 'a')
{
charCount++;
}
}
System.out.println("count of character 'a' on String: 'Today is Monday'
using for each loop " + charCount);
3 : //Using Spring framework StringUtils class
int count = StringUtils.countOccurrencesOf(input, "a");
System.out.println("count of occurrence of character 'a' on String: " +"
Today is Monday' using Spring StringUtils " + count);
Q :count number of words in given string ?
-----------------------------------------------------------
EX: Number of words in a string = 5
public class WordCount
{
public static void main(String args[])
{
String s = "welcome to java tutorial";
int count = 1;
for (int i = 0; i < s.length() - 1; i++)
{
if ((s.charAt(i) == ' ') && (s.charAt(i + 1) != ' '))
{
count++;
}
}
System.out.println("Number of words in a string = " + count);
}
}
Q : Java program to remove duplicate words in given string ?
-------------------------------------------------------------
public class RemoveDuplicate
{
public static void main(String[] args)
{
String input="Welcome to Java Session Java Session Session Java";
//Input String
String[] words=input.split(" "); //Split the word from String
for(int i=0;i<words.length;i++) //Outer loop for Comparison
{
if(words[i]!=null)
{
for(int j=i+1;j<words.length;j++) //Inner loop for Comparison
{
if(words[i].equals(words[j])) //Checking for both strings are
equal
{
words[j]=null; //Delete the duplicate
words
}
}
}
}
for(int k=0;k<words.length;k++) //Displaying the String
without duplicate words
{
if(words[k]!=null)
{
System.out.println(words[k]);
}
}
}
}
Q: HOW TO REMOVE DUPLICATE WORD IN STRING ?
--------------------------------------------
SOL:
Enter word string :
java badri java
badri java
import java.util.Scanner;
public class DuplicateWordRemove {
public static void main(String[] args) {
System.out.println("Enter string : ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
removeDeplicate(str);
}
static void removeDeplicate(String str) {
String[] word = str.split("\\s");
for(int i=0; i<word.length; i++)
{
for(int j=0; j<word.length; j++)
{
if(word[i].equals(word[j]))
{
if(i!=j)
word[i]="";
}
}
}
for(int i=0; i<word.length; i++)
{
System.out.print(word[i]+" ");
}
}
Q: HOW TO REMOVE DUPLICATE CHAR IN STRING ?
--------------------------------------------
SOL :
Enter string :
java php
j v a h p
------------------
import java.util.Scanner;
public class DuplicateCharRemove {
public static void main(String[] args) {
System.out.println("Enter string : ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
removeDeplicate(str);
}
static void removeDeplicate(String str) {
char[] word = str.toCharArray();
for(int i=0; i<word.length; i++)
{
for(int j=0; j<word.length; j++)
{
if(word[i]==(word[j]))
{
if(i!=j)
word[i]=' ';
}
}
}
for(int i=0; i<word.length; i++)
{
System.out.print(word[i]+" ");
}
}
Q: How to Reverse String in Java with or without StringBuffer Example
---------------------------------------------------------------------
// BL
WELCOME JAVA LANGUAGE
EGAUGNAL AVAJ EMOCLEW
public class StringReverse {
public static void main(String[] args) {
String str="Hi, java is programming language.";
String reverse="";
for(int i=str.length()-1; i>=0; i--)
{
reverse = reverse + str.charAt(i);
}
System.out.println(str);
System.out.println(reverse);
}
}
or
public static String reverse(String source)
{
if(source==null || source.isEmpty())
{
return source;
}
String reverse = " ";
for(int i=source.lentgh() -1; i>=0 ; i--)
{
reverse = reverse + reverse.charAt(i);
}
ruturn reverse ;
}
Q : REVERSE WORDS IN STRING ?
---------------------------
EX: REVERSE WORD SIMPLE
BADRI LAL
LAL IRDAB
public class WordReverse {
public static void main(String[] args) {
System.out.println("Entet String");
Scanner sc = new Scanner(System.in);
String text =sc.nextLine();
wordReverse(text);
}
static void wordReverse(String text)
{
String reverseword="";
for(int i=text.length()-1; i>=0 ; i--)
{
reverseword=reverseword+text.charAt(i);
}
System.out.println(text);
System.out.println(reverseword);
}
}
EX: REVERSE WORD IN SAME PLACE
BADRI LAL GOCHER
IRDAB LAL REHCOG
public class WordReverse {
public static void main(String[] args) {
System.out.println("Entet String");
Scanner sc = new Scanner(System.in);
String text =sc.nextLine();
wordReverse(text);
}
static void wordReverse(String text) {
String[] words = text.split(" ");
String revstring="";
for(int i=0; i<words.length; i++)
{
String word=words[i];
String revword="";
for(int j=word.length()-1; j>=0 ; j--)
{
revword = revword+ word.charAt(j);
}
revstring = revstring + revword +" ";
}
System.out.println("Entered text :"+text);
System.out.println("Reverse :"+revstring);
}
}
Q : Java Program To Find Duplicate Elements In An String Array
public class DuplicatesInArray
{
public static void main(String[] args)
{
String[] strArray = {"abc", "def", "mno", "xyz", "pqr", "xyz", "def"};
for (int i = 0; i < strArray.length-1; i++)
{
for (int j = i+1; j < strArray.length; j++)
{
if( (strArray[i].equals(strArray[j])) && (i != j) )
{
System.out.println("Duplicate Element is : "+strArray[j]);
}
}
}
}
}
Output :
Duplicate Element is : def
Duplicate Element is : xyz
Q: Java Program To Find Common Elements Between Two Arrays ?
class CommonElements
{
public static void main(String[] args)
{
String[] s1 = {"ONE", "TWO", "THREE", "FOUR", "FIVE", "FOUR"};
String[] s2 = {"THREE", "FOUR", "FIVE", "SIX", "SEVEN", "FOUR"};
HashSet<String> set = new HashSet<String>();
for (int i = 0; i < s1.length; i++)
{
for (int j = 0; j < s2.length; j++)
{
if(s1[i].equals(s2[j]))
{
set.add(s1[i]);
}
}
}
System.out.println(set); //OUTPUT : [THREE, FOUR, FIVE]
}
}
or
class CommonElements
{
public static void main(String[] args)
{
Integer[] i1 = {1, 2, 3, 4, 5, 4};
Integer[] i2 = {3, 4, 5, 6, 7, 4};
HashSet<Integer> set1 = new HashSet<>(Arrays.asList(i1));
HashSet<Integer> set2 = new HashSet<>(Arrays.asList(i2));
set1.retainAll(set2);
System.out.println(set1); //Output : [3, 4, 5]
}
}
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));
}
}