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 [Link];
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()
{
[Link]("this is my function called");
}
public static void main(String[] args)
{
SingleToneClass obj = [Link]();
[Link]();
[Link]("HashCode 1 : "+[Link]());
[Link]("_____________________________");
SingleToneClass obj2 = [Link]();
[Link]();
[Link]("HashCode 2 : "+[Link]());
[Link]("_____________________________");
SingleToneClass obj3 = [Link]();
[Link]();
[Link]("HashCode 3 : "+[Link]());
[Link]("_____________________________");
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 [Link];
public final class ImutableString {
private final int Id;
private final String Name;
public ImutableString(int i, String name)
{
[Link]=i;
[Link]=name;
public ImutableString modify(int j, String empname)
{
if([Link]==j && [Link]==empname)
{
return this;
}
else
{
return new ImutableString(102,"Badri lal");
}
public static void main(String[] args)
{
ImutableString obj = new ImutableString(101,"vivek ramteke");
[Link]([Link]());
[Link]("Id : "+[Link] +"Name :"+[Link]);
ImutableString obj2=[Link](102,"badri lal");
[Link]([Link]());
[Link]("Id : "+[Link] +"Name :"+[Link]);
ImutableString obj3=[Link](101,"vivek ramteke");
[Link]([Link]());
[Link]("Id : "+[Link] +"Name :"+[Link]);
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 [Link];
package [Link];
public class Employee {
int id;
String name;
public Employee(int id, String name) {
[Link]=id;
[Link]=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 [Link]==id && [Link](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");
[Link]("HC : "+[Link]());
[Link](obj);
[Link]("Equals : "+ [Link](obj2));
[Link]("HC : "+[Link]());
[Link](obj2);
[Link]("Equals : "+[Link](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)
{
[Link]("Exception Caught");
[Link]([Link]());
}
}
}
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
[Link]("welcome to vote");
}
public static void main(String args[])
{
try{
validate(13);
}
catch(Exception m)
{
[Link]("Exception occured: "+[Link]());
}
[Link]("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
{
[Link]("Welcome user : "+pin);
}
}
public static void main(String[] args)
{
try{
pin(1234);
}
catch(MyException ex)
{
[Link]("Exception catched :-"+[Link]());
}
}
ex4 :
package [Link];
class Employee
{
}
class EmpNotFoundException extends Exception
{
EmpNotFoundException(String msg)
{
super(msg);
}
}
class EmpManager
{
public Employee find(String EmpId) throws EmpNotFoundException
{
if([Link]("12345"))
{
[Link]("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 = [Link]("12345");
}
catch(EmpNotFoundException e){
[Link](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 : [Link]())
{
[Link](str);
}
or
for(Integer stno : [Link]())
{
[Link](stno);
}
only for values :-
------------------
for(String strnm : [Link]())
{
[Link](strnm);
}
or
for(String city : [Link]())
{
[Link](city);
}
2 :[Link]() using For-Each loop :
---------------------------------------
for(Entry<String, String> entry: [Link]())
{
[Link]([Link]()+" "+[Link]());
}
or
for([Link]<String, Object> entry : [Link]()) {
String key = [Link]();
Object value = [Link]();
3 : using iterators over [Link]<K, V> :
=====================================
Iterator<[Link]<String, String>> itr= [Link]().iterator();
while([Link]())
{
[Link]<String, String> entry=[Link]();
[Link]([Link]()+" "+[Link]());
}
or
Iterator<[Link]<Integer, String>> itr2 =
[Link]().iterator();
while([Link]())
{
[Link]<Integer, String> entry = [Link]();
[Link]([Link]() +" "+[Link]());
}
4: forEach(action) method :
-----------------------------
[Link]((k,v) -> [Link](k +" "+v));
5: iterating through key and searching values using get() :
-----------------------------------------------------------
for(Integer k: [Link]())
{
String v = [Link](k);
[Link](v);
}
***********************COLLECTION**********
Q-How to remove duplicate/Repeated elements from ArrayList ?
==============================================================
1 : whithout using collection
-------------------------------
package [Link];
import [Link];
public class MyHashMap {
public static void main(String[] args) {
ArrayList<Object> al = new ArrayList<Object>();
[Link]("BADRI LAL");
[Link]("Monika");
[Link]("Nagendra");
[Link]("BADRI LAL");
[Link]("101");
[Link]("JAVA");
[Link]("101");
[Link](101);
[Link]("Befor duplicate :"+al);
for(int i=0; i<[Link](); i++){
for(int j=i+1; j<[Link](); j++)
{
if([Link](i).equals([Link](j)))
{
[Link](j);
j--;
}
}
}
[Link]("after removed duplicate :"+al);
}
Remove using collection object HashSet :
========================================
package [Link];
import [Link];
import [Link];
import [Link];
public class MyHashMap {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
[Link]("BADRI LAL");
[Link]("BK");
[Link]("Nagendra");
[Link]("BADRI LAL");
[Link]("101");
[Link]("JAVA");
[Link]("101");
[Link]("al :"+al);
HashSet<String> hashset = new HashSet<String>(al);
[Link]("hashset"+hashset);
[Link]();
[Link](hashset);
[Link]("al"+al);
EXAMPLE 1: [sorts the list elements Student the basis of age]
==========
package [Link];
import [Link];
import [Link];
class Student implements Comparable<Student>
{
int rollno;
String name;
int age;
public int getRollno() {
return rollno;
}
public void setRollno(int rollno) {
[Link] = rollno;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
[Link] = age;
}
public Student(int rollno, String name, int age) {
super();
[Link] = rollno;
[Link] = name;
[Link] = age;
}
@Override
public String toString() {
return "Student [rollno=" + rollno + ", name=" + name + ", age=" + age
+ "]";
}
@Override
public int compareTo(Student o) {
//Acending
return [Link];
//Descending
//return -[Link]
[Note:- for name use compareTo() : return -
[Link]().compareTo([Link]());]
}
}
public class ComparableSorting {
public static void main(String[] args) {
ArrayList<Student> al = new ArrayList<Student>();
[Link](new Student(101,"Badri lal",29));
[Link](new Student(105,"Nagendra",27));
[Link](new Student(111,"Monu",30));
[Link](al);
for(Student st:al)
{
[Link]([Link]+" "+[Link]+" "+[Link]);
}
op:
===
111 Monu 30
101 Badri lal 29
105 Nagendra 27
EXAMPLE 2:
==========
package [Link];
import [Link];
import [Link];
class Employee implements Comparable<Employee>
{
String name;
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public int getSalary() {
return Salary;
}
public void setSalary(int salary) {
Salary = salary;
}
int Salary;
public Employee(String name, int salary) {
super();
[Link] = name;
Salary = salary;
}
@Override
public int compareTo(Employee o)
{
//Ascending
//return [Link];
//Descending
return -[Link];
//on name : return -[Link]().compareTo([Link]());
}
public class ComparableSoring {
public static void main(String[] args) {
ArrayList<Employee> e = new ArrayList<Employee>();
[Link](new Employee("Badri",101));
[Link](new Employee("Nagendra",102));
[Link](new Employee("Dinesh",104));
[Link](e);
for(Employee e1: e)
{
[Link]([Link]+" "+[Link]);
}
/*package [Link];
import [Link];
import [Link];
class Employee1 implements Comparable<Employee>
{
String name;
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public int getSalary() {
return Salary;
}
public void setSalary(int salary) {
Salary = salary;
}
int Salary;
public Employee1(String name, int salary) {
super();
[Link] = name;
Salary = salary;
}
@Override
public int compareTo(Employee o)
{
return -[Link]().compareTo([Link]());
}
public class ComparableSoring {
public static void main(String[] args) {
ArrayList<Employee> e = new ArrayList<Employee>();
[Link](new Employee("Badri",101));
[Link](new Employee("Nagendra",102));
[Link](new Employee("Dinesh",104));
[Link](e);
for(Employee e1: e)
{
[Link]([Link]+" "+[Link]);
}
EXAMPLE 1: COMPARATOR SORTING ACCORDING TO DEPT , SALARY
==========================================================
package [Link];
import [Link];
import [Link];
import [Link];
//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();
[Link] = id;
[Link] = name;
Dept = dept;
[Link] = 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 [Link];
}
}
//Dept comparator class
class DeptComparator implements Comparator<Employee>
{
@Override
public int compare(Employee e1, Employee e2)
{
return [Link]([Link]);
}
}
public class ComparatorSorting {
public static void main(String[] args) {
ArrayList<Employee> obj = new ArrayList<Employee>();
[Link](new Employee(101,"Badri","Developer",50000));
[Link](new Employee(102,"Monu","HR",30000));
[Link](new Employee(103,"Nagendra","Manager",33000));
//sorting by salary
[Link](obj, new salaryComparator());
//sorting by dept
[Link](obj, new DeptComparator());
for(Employee e1: obj)
{
[Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]);
}
}
COMPARATOR
------------
COMPARATOR
package [Link];
import [Link];
import [Link];
import [Link];
//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();
[Link] = id;
[Link] = name;
Dept = dept;
[Link] = 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 [Link];
}
}
//Dept comparator class
class DeptComparator implements Comparator<Employee>
{
@Override
public int compare(Employee e1, Employee e2) {
// TODO Auto-generated method stub
return [Link]([Link]);
}
}
public class ComparatorSorting {
public static void main(String[] args) {
ArrayList<Employee> obj = new ArrayList<Employee>();
[Link](new Employee(101,"Badri","Developer",50000));
[Link](new Employee(102,"Monu","HR",30000));
[Link](new Employee(103,"Nagendra","Manager",33000));
//sorting by salary
[Link](obj, new salaryComparator());
//sorting by dept
//[Link](obj, new DeptComparator());
for(Employee e1: obj)
{
[Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]);
}
}
}
Q : TO FIND PALINDROME NO BW RANGE. ?
--------------------------------------
package [Link];
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))
{
[Link](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 [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class OrderByValue {
public static void main(String a[]){
Map<String, Integer> map = new HashMap<String, Integer>();
[Link]("java", 20);
[Link]("C++", 45);
[Link]("Java2Novice", 2);
[Link]("Unix", 67);
[Link]("MAC", 26);
[Link]("Why this kolavari", 93);
Set<Entry<String, Integer>> set = [Link]();
List<Entry<String, Integer>> list = new ArrayList<Entry<String,
Integer>>(set);
[Link]( list, new Comparator<[Link]<String, Integer>>()
{
public int compare( [Link]<String, Integer> o1, [Link]<String,
Integer> o2 )
{
return ([Link]()).compareTo( [Link]() );
}
} );
for([Link]<String, Integer> entry:list){
[Link]([Link]()+" ==== "+[Link]());
}
}
}
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 = [Link]();
HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
for(Character ch : arr)
{
if([Link](ch))
{
[Link](ch, [Link](ch)+1);
}
else
{
[Link](ch, 1);
}
//set
Set<Character> set =[Link]();
for(Character ch : set)
{ //TO PRINT ONLY DUPLICATE USE IF
CONDITION
// if([Link](ch)>1)
[Link](ch +" : "+[Link](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 [Link];
import [Link];
import [Link];
public class Duplicate_Words {
static void Duplicate_word(String str)
{
String[] arr =[Link](" ");
HashMap<String, Integer> hm = new HashMap<String, Integer>();
for(String s : arr)
{
if([Link](s))
{
[Link](s, [Link](s)+1);
}
else
{
[Link](s, 1);
}
}
Set<String> set = [Link]();
for(String s: set)
{
[Link]( s +" : "+[Link](s));
}
}
public static void main(String[] args) {
Duplicate_word("java , php , java , parl");
or
==
Set<[Link]<Character, Integer>> entrySet = [Link]();
for ([Link]<Character, Integer> entry : entrySet)
{
if ([Link]() > 1)
{
[Link]( [Link]() + + [Link]());
}
}
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<[Link](); i++)
{
if([Link](i) == 'a')
{
charCount++;
}
}
[Link]("count of character 'a' on String: 'Today is Monday'
using for loop " + charCount);
or
2: //
charCount = 0;
for(char ch: [Link]())
{
if(ch == 'a')
{
charCount++;
}
}
[Link]("count of character 'a' on String: 'Today is Monday'
using for each loop " + charCount);
3 : //Using Spring framework StringUtils class
int count = [Link](input, "a");
[Link]("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 < [Link]() - 1; i++)
{
if (([Link](i) == ' ') && ([Link](i + 1) != ' '))
{
count++;
}
}
[Link]("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=[Link](" "); //Split the word from String
for(int i=0;i<[Link];i++) //Outer loop for Comparison
{
if(words[i]!=null)
{
for(int j=i+1;j<[Link];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<[Link];k++) //Displaying the String
without duplicate words
{
if(words[k]!=null)
{
[Link](words[k]);
}
}
}
}
Q: HOW TO REMOVE DUPLICATE WORD IN STRING ?
--------------------------------------------
SOL:
Enter word string :
java badri java
badri java
import [Link];
public class DuplicateWordRemove {
public static void main(String[] args) {
[Link]("Enter string : ");
Scanner sc = new Scanner([Link]);
String str = [Link]();
removeDeplicate(str);
}
static void removeDeplicate(String str) {
String[] word = [Link]("\\s");
for(int i=0; i<[Link]; i++)
{
for(int j=0; j<[Link]; j++)
{
if(word[i].equals(word[j]))
{
if(i!=j)
word[i]="";
}
}
}
for(int i=0; i<[Link]; i++)
{
[Link](word[i]+" ");
}
}
Q: HOW TO REMOVE DUPLICATE CHAR IN STRING ?
--------------------------------------------
SOL :
Enter string :
java php
j v a h p
------------------
import [Link];
public class DuplicateCharRemove {
public static void main(String[] args) {
[Link]("Enter string : ");
Scanner sc = new Scanner([Link]);
String str = [Link]();
removeDeplicate(str);
}
static void removeDeplicate(String str) {
char[] word = [Link]();
for(int i=0; i<[Link]; i++)
{
for(int j=0; j<[Link]; j++)
{
if(word[i]==(word[j]))
{
if(i!=j)
word[i]=' ';
}
}
}
for(int i=0; i<[Link]; i++)
{
[Link](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=[Link]()-1; i>=0; i--)
{
reverse = reverse + [Link](i);
}
[Link](str);
[Link](reverse);
}
}
or
public static String reverse(String source)
{
if(source==null || [Link]())
{
return source;
}
String reverse = " ";
for(int i=[Link]() -1; i>=0 ; i--)
{
reverse = reverse + [Link](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) {
[Link]("Entet String");
Scanner sc = new Scanner([Link]);
String text =[Link]();
wordReverse(text);
}
static void wordReverse(String text)
{
String reverseword="";
for(int i=[Link]()-1; i>=0 ; i--)
{
reverseword=reverseword+[Link](i);
}
[Link](text);
[Link](reverseword);
}
}
EX: REVERSE WORD IN SAME PLACE
BADRI LAL GOCHER
IRDAB LAL REHCOG
public class WordReverse {
public static void main(String[] args) {
[Link]("Entet String");
Scanner sc = new Scanner([Link]);
String text =[Link]();
wordReverse(text);
}
static void wordReverse(String text) {
String[] words = [Link](" ");
String revstring="";
for(int i=0; i<[Link]; i++)
{
String word=words[i];
String revword="";
for(int j=[Link]()-1; j>=0 ; j--)
{
revword = revword+ [Link](j);
}
revstring = revstring + revword +" ";
}
[Link]("Entered text :"+text);
[Link]("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 < [Link]-1; i++)
{
for (int j = i+1; j < [Link]; j++)
{
if( (strArray[i].equals(strArray[j])) && (i != j) )
{
[Link]("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 < [Link]; i++)
{
for (int j = 0; j < [Link]; j++)
{
if(s1[i].equals(s2[j]))
{
[Link](s1[i]);
}
}
}
[Link](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<>([Link](i1));
HashSet<Integer> set2 = new HashSet<>([Link](i2));
[Link](set2);
[Link](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 [Link];
import [Link];
import [Link];
public class DuplicateNumber {
public int findDuplicateNumber(List<Integer> numbers){
int highestNumber = [Link]() - 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++){
[Link](i);
}
//add duplicate number into the list
[Link](22);
DuplicateNumber dn = new DuplicateNumber();
[Link]("Duplicate Number: "+[Link](numbers));
}
}