Friday, April 27, 2018

Java sort single field using Comparator.


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class SortBySalary implements Comparator<Human> {
@Override
public int compare(Human o1, Human o2) {
if (o1.salary > o2.salary)
return 1;
if (o1.salary < o2.salary)
return -1;
return 0;
}

}

class Human {
String name;
int age;
double salary;

public Human(String n, int a, double s) {
this.name = n;
this.age = a;
this.salary = s;
}

public Human() {
}

public String toString() {
return this.name + " " + this.age + " " + this.salary;
}

}

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

List<Human> l = new ArrayList();
Human h1 = new Human("ritesh", 12, 6000);
Human h2 = new Human("raju", 18, 5000);
Human h3 = new Human("ishaan", 10, 7000);
Human h4 = new Human("yuyu", 15, 333);
Human h5 = new Human("yuyu", 17, 333);
Human h6 = new Human("yuyu", 13, 333);
l.add(h1);
l.add(h2);
l.add(h3);
l.add(h4);
l.add(h5);
l.add(h6);

System.out.println(l);

Collections.sort(l, new SortBySalary());
System.out.println(l);
}

}


Output:
[ritesh 12 6000.0, raju 18 5000.0, ishaan 10 7000.0, yuyu 15 333.0, yuyu 17 333.0, yuyu 13 333.0]
[yuyu 15 333.0, yuyu 17 333.0, yuyu 13 333.0, raju 18 5000.0, ritesh 12 6000.0, ishaan 10 7000.0]

Java sort multiple fields using Comparator.

Sort multiple fields using Comparator:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class SortByAnimalName implements Comparator<Animal> {

@Override
public int compare(Animal o1, Animal o2) {
return o1.name.compareTo(o2.name);
}
}

class SortByAnimalColor implements Comparator<Animal> {

@Override
public int compare(Animal o1, Animal o2) {
return o1.color.compareTo(o2.color);
}
}

class SortByAnimalWeight implements Comparator<Animal> {

@Override
public int compare(Animal o1, Animal o2) {
if (o1.weight > o2.weight) {
return 1;
}
if (o1.weight < o2.weight) {
return -1;
}
return 0;
}
}

class SortByAllAnimal implements Comparator<Animal> {

List<Comparator<Animal>> allFields;

@SafeVarargs
SortByAllAnimal(Comparator<Animal>... allSort) {
this.allFields = Arrays.asList(allSort);

}
@Override
public int compare(Animal o1, Animal o2) {
for (Comparator<Animal> x : allFields) {
int res = x.compare(o1, o2);
if (res != 0) {
return res;
}
}
return 0;
}
}

class Animal {
String color;
String name;
int weight;

Animal(String c, String n, int w) {
this.color = c;
this.name = n;
this.weight = w;
}
@Override
public String toString() {
return this.color + " " + this.name + " " + this.weight;
}
}

public class SortMultipleDataByComparator{
public static void main(String[] args) {
List<Animal> l = new ArrayList<Animal>();
Animal a1 = new Animal("black", "dog", 20);
Animal a2 = new Animal("white", "cat", 15);
Animal a3 = new Animal("black", "elephant", 120);
Animal a4 = new Animal("white", "horse", 80);
l.add(a1);
l.add(a2);
l.add(a3);
l.add(a4);
System.out.println(l);
System.out.println("------------------------------------");
Collections.sort(l,
new SortByAllAnimal(new SortByAnimalColor(), new SortByAnimalName(), new SortByAnimalWeight()));

System.out.println(l);
}
}


Output:

[black dog 20, white cat 15, black elephant 120, white horse 80]
------------------------------------
[black dog 20, black elephant 120, white cat 15, white horse 80]

Volatile in java

public class SharedObject {
// Changes made to SharedObject in one thread may not be
// immediately reflect in other thread
static int sharedVariable = 8;
}

/**
 * Suppose two threads are working on SharedObject. If two threads run on
 * different processes each thread may have its own local copy of
 * sharedVariable. If one thread modifies its value the changes might not
 * reflect in the original one in the main memory instantly.
 * 
 */

public class SharedObject {
// Changes made to SharedObject in one thread may not be
// immediately reflect in other thread
static volatile int sharedVariable = 8;
}

Explanation: here changes made by one thread to shared data are visible to other threads.

import java.util.logging.Level;
import java.util.logging.Logger;

public class VolatileExe {
private static final Logger LOGGER = Logger.getLogger(VolatileExe.class.getName());

private static volatile int MY_INT = 0;

public static void main(String[] args) {
new ChangeListener().start();
new ChangeMaker().start();
}

static class ChangeListener extends Thread {
@Override
public void run() {
int local_value = MY_INT;
while (local_value < 5) {
if (local_value != MY_INT) {
LOGGER.log(Level.INFO, "Got Change for MY_INT : {0}", MY_INT);
local_value = MY_INT;
}
}
}
}

static class ChangeMaker extends Thread {
@Override
public void run() {

int local_value = MY_INT;
while (MY_INT < 5) {
LOGGER.log(Level.INFO, "Incrementing MY_INT to {0}", local_value + 1);
MY_INT = ++local_value;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

Singleton class or singleton pattern in java ?

  • Singleton is a class which has only one instance in whole application and provide getInstance() method to access singleton instance. 
  • There are many classes in JDK which is implemented using Singleton pattern like java.lang.Runtime which provides getRuntime() method to get access of it and used to get free memory and total memory in Java.
Example:
[1] Singleton by private static field, static getInstance() method:
  1. public class SingletonExe {
  2. private static SingletonExe instance = null;
  3. private void SingeltonExe() {
  4. System.out.println("Private constructor");
  5. }
  6. public static SingletonExe getInstance() {
  7.   if (instance == null) {
  8.   synchronized (SingletonExe.class) {
  9. if (instance == null) {
  10. instance = new SingletonExe();
  11. }
  12.   }
  13.   }
  14. return instance;
  15. }
  16. }

[2] Singleton by synchronized getInstance() method [double checked locking in Singleton]

/**
 * Java program to demonstrate where to use Volatile keyword in Java. In this
 * example Singleton Instance is declared as volatile variable to ensure every
 * thread
 */
  1. public class SingletonExe {
  2. private static volatile SingletonExe instance = null; // volatile variables
  3. private void SingeltonExe() {
  4. System.out.println("Private constructor");
  5. }
  6. public static SingletonExe getInstance() {
  7. if (instance == null) {
  8. synchronized (SingletonExe.class) {
  9. if (instance == null) {
  10. instance = new SingletonExe();
  11. }
  12. }
  13. }
  14. return instance;
  15. }
  16. }

Thursday, April 26, 2018

Maven repository

What are maven plugins?

  • Maven plugin is an execution framework to execute specific set of goals like
Maven core plugins:
  1. clean : Clean up after the build.
  2. install : Install the built artifact into the local repository.
  3. deploy : Deploy the built artifact to the remote repository.
  4. compiler : Compiles Java sources.
  5. resources : Copy the resources to the output directory for including in the JAR.
  6. surefire : Run the JUnit unit tests in an isolated classloader.
Maven tools:
  1. jar - create jar file
  2. war- create war file
  3. ejb - create ejb from current project
  4. ear - create ear from current project 
  5. rar - create rar from current project
  6. archetype - generate a skeleton project structure from an archetype.
  7. dependency - dependency manipulation (copy, unpack) and analysis.
  • There are two type of maven plugins.
  1. Build plugins will be executed during the build and they should be configured in the <build/> element from the POM.
  2. Reporting plugins will be executed during the site generation and they should be configured in the <reporting/> element from the POM.

What is maven ?

  • Maven is a build automation tool used primarily for Java-based project. 
  • It can also be used to build and manage projects written in C#, Ruby, Scala, and other languages.
  • Maven addresses two aspects of building software: first, it describes how software is built, and second, it describes its dependencies.
  • An pom.xml file describes the software project being built.

Tuesday, April 24, 2018

Count the repeated character in a string !!

  1. public class CountOfCharacter {
  2. public static void main(String[] args) {
  3. String s = "abcabcabc";
  4. countOfRepeatedCharacter(s);
  5. }
  6. public static void countOfRepeatedCharacter(String s) {
  7. char c[] = s.toCharArray();
  8. Map<Character, Integer> map = new HashMap<Character, Integer>();
  9. for (int i = 0; i < c.length; i++) {
  10. if (map.containsKey(c[i])) {
  11. map.put(c[i], map.get(c[i]) + 1);
  12. } else {
  13. map.put(c[i], 1);
  14. }
  15. }
  16. System.out.println(map);
  17. }
  18. }
Output: 
{a=3, b=3, c=3}

What is the output of the program ? [based on exception]

  1. class SampleExe {
  2. void run() throws Exception {
  3. System.out.println("run before x");
  4. int x = 10 / 0;
  5. System.out.println("run after x");
  6. }
  7. }

  8. public class SmapleExe1 {
  9. public static void main(String[] args) {
  10. SampleExe exe = new SampleExe();
  11. exe.run();
  12. }
  13. }
Output: Unhandled type exception at compile time at line 12
--------------------------------------------------------------------
  1. class SampleExe {
  2. void run() throws Exception {
  3. System.out.println("run before x");
  4. int x = 10 / 0;
  5. System.out.println("run after x");
  6. }
  7. }

  8. public class SmapleExe1 {
  9. public static void main(String[] args) throws Exception {
  10. SampleExe exe = new SampleExe();
  11. exe.run();
  12. }
  13. }
Output: 
run before x
java.lang.ArithmeticException: / by zero at line 4

--------------------------------------------------------------------
  1. class SampleExe {
  2. void run() throws Exception {
  3. System.out.println("run before x");
  4. int x = 10 / 0;
  5. System.out.println("run after x");
  6. }
  7. }

  8. public class SmapleExe1 {
  9. public static void main(String[] args) {
  10. SampleExe exe = new SampleExe();
  11. try {
  12. exe.run();
  13. } catch (Exception e) {
  14. e.printStackTrace();
  15. }
  16. }
  17. }
Output: 
run before x
java.lang.ArithmeticException: / by zero at line 4

What is the output of the program ? [based on method overriding]

  1. class SampleExec1 {
  2. void run() {
  3. System.out.println("SampleExec1 run");
  4. }
  5. }
  6. class SampleExec2 extends SampleExec1 {
  7. void run() {
  8. System.out.println("SampleExec2 run");
  9. }
  10. }
  11. public class SampleExecution {
  12. public static void main(String[] args) {
  13. SampleExec2 ex = new SampleExec1();
  14. ex.run();
  15. }
  16. }
Output: compile time error at line 13. Type mismatch: cannot convert from SampleExec1 to SampleExec2

--------------------------------------------------------------------
  1. class SampleExec1 {
  2. void run() {
  3. System.out.println("SampleExec1 run");
  4. }
  5. }
  6. class SampleExec2 extends SampleExec1 {
  7. void run() {
  8. System.out.println("SampleExec2 run");
  9. }
  10. }
  11. public class SampleExecution {
  12. public static void main(String[] args) {
  13. SampleExec2 ex = (SampleExec2 )new SampleExec1();
  14. ex.run();
  15. }
  16. }
Output: 
Exception in thread "main" java.lang.ClassCastException: SampleExec1 cannot be cast to SampleExec2 at SampleExecution.main(SampleExecution .java:14)

--------------------------------------------------------------------
  1. class SampleExec1 {
  2. void run() {
  3. System.out.println("SampleExec1 run");
  4. }
  5. }
  6. class SampleExec2 extends SampleExec1 {
  7. void run() {
  8. System.out.println("SampleExec2 run");
  9. }
  10. }
  11. public class SampleExecution {
  12. public static void main(String[] args) {
  13. SampleExec1 ex = new SampleExec2();
  14. ex.run();
  15. }
  16. }
Output: SampleExec2 run

Monday, April 23, 2018

Can many classes implements same interface ?

  1. public class MultipleClass implements X{}
  2. class MultipleClass1 implements X{}
  3. class MultipleClass2 implements X{}
  4. class MultipleClass3 implements X{}
  5. interface X {}
Yes ! we can implements same interface in multiple classes.

Can a class implements multiple interface ?


  1. interface MultipleInterface {}
  2. interface MultipleInterface1 {}
  3. interface MultipleInterfac2 {}
  4. public class UserMain implements MultipleInterface, MultipleInterface1, MultipleInterfac2 {
  5. // code here
  6. }
Yes ! we can implements multiple interface in a class.

Can we have a constructor in an interface ?

  1. interface MyInterfaceExe {
  2. public void MyInterfaceExe (){
  3. // code here
  4. }
  5. }
No ! we cannot have a constructor in an interface. Compiler will give an error. 

  1. interface MyInterfaceExe {
  2. public static void MyInterfaceExe (){
  3. // code here
  4. };
  5. }
       ----------------------------------------------------
  1. interface MyInterfaceExe {
  2. public default void MyInterfaceExe (){
  3. // code here
  4. };
  5. }
In above case, Yes ! we can have a constructor only if we have either static or default keyword in constructor bodies ending with (;) semicolon.

Can we create an instance of an interface ?

  1. interface MyInterfaceExe {
  2. MyInterfaceExe exe = new MyInterfaceExe();
  3. }
No ! we cannot instantiate an interface. Compiler will give an error saying that cannot instantiate the type of  MyInterfaceExe.
  1. interface MyInterfaceExe {
  2. MyInterfaceExe exe = new MyInterfaceExe(){ };
  3. }
Yes ! we can create the object of an interface using anonymous class as above.

Can an interface have static keyword in method with bodies ?

  1. interface MyInterfaceExe {
  2. public static void run(){
  3. // code here
  4. }
  5. }
Yes ! we can have static keyword in method with bodies.

Can an interface have default keyword in method with bodies ?

  1. interface MyInterfaceExe {
  2. public default void run(){
  3. // code here
  4. }
  5. }
Yes ! we can have default keyword in method with bodies.

Can an interface have both default and static keyword in method with bodies ?

  1. interface MyInterfaceExe {
  2. public default static void run(){
  3. // code here
  4. }
  5. }
No ! we can not have both default and static keyword in method with body. Compiler will give an error saying that illegal combination of modifier at line 2.

What is the default nature of an interface method's ?

  1. interface MyInterfaceExe {
  2. // Any number of abstract method declarations
  3. void run();
  4. // is equivalent to public abstract void run();
  5. int test();
  6. // is equivalent to public abstract int test();
  7. }
 The default nature of an interface method's is both public & abstract.

What is the default modifier of field / variable in an interface ?

  1. interface MyInterfaceExe {
  2. // Any number of final, static fields / variables
  3. int x = 10;
  4. // is equivalent to final static int x  = 10;
  5. String s = "ishaan";
  6. // is equivalent to final static String s = "ishaan";
  7. }
Note: The default nature of an interface field's / variable's  is public final static.

Where is the byte code generated by an interface ?

  1. interface MyInterfaceExe {
  2. // Any number of final, static fields / variables
  3. // Any number of abstract method declarations
  4. }
Byte code generated by an interface appears in .class file.

What is the extension of the file to save an interface program ?

  1. interface MyInterfaceExe {
  2. // Any number of final, static fields / variables
  3. // Any number of abstract method declarations
  4. }
The extension is .java for interface written program.
Lets save as: MyInterfaceExe.java

How to declare an interface ?

  1. interface MyInterfaceExe {
  2. // Any number of final, static fields / variables
  3. // Any number of abstract method declarations
  4. }
we must use interface keyword to declare an interface followed by identifier name.

Is there any way to create the instance of an abstract class ?

  1. public class MyMain{
  2. public static void main(String[] args) { // start
  3. MyAbstractClass exe = new MyAbstractClass() {
  4. @Override
  5. void run() {
  6. System.out.println("run of abstract class");
  7. }
  8. };
  9. System.out.println(exe.x);
  10. exe.run();
  11. } // end
  12. }

  13. abstract class MyAbstractClass {
  14. int x = 10;
  15. abstract void run();
  16. }
Output: 
10
run of abstract class

Note: Yes ! using anonymous class we can create the instance of an abstract class.

Can we create the object of an abstract class ?

  1. abstract public class MyAbstractExe {
  2. MyAbstractExe exe = new MyAbstractExe();
  3. }

No ! we can not create the object / instance of an abstract class. Compiler will give an error at line 2 saying cannot instantiate the type MyAbstractExe 

Can a class inherit from one abstract class ?

  1. public class MyAbstractExe2 extends MyAbstractExe1
  2. {
  3. @Override
  4. void run() {
  5. System.out.println("run");
  6. }
  7. }

  8. abstract class MyAbstractExe3 {
  9. abstract void run();
  10. void test() {
  11. System.out.println("test of MyAbstractExe3 !!");
  12. }
  13. }

  14. abstract class MyAbstractExe1 {
  15. abstract void run();
  16. void test() {
  17. System.out.println("test of MyAbstractExe1 !!");
  18. }
  19. }
Yes! we can inherit a class from one abstract class. compiler will not give error.

Can a class inherit from multiple abstract class ?

  1. public class MyAbstractExe2 extends MyAbstractExe1, MyAbstractExe3
  2. {
  3. @Override
  4. void run() {
  5. System.out.println("run");
  6. }
  7. }

  8. abstract class MyAbstractExe3 {
  9. abstract void run();
  10. void test() {
  11. System.out.println("test of MyAbstractExe3 !!");
  12. }
  13. }

  14. abstract class MyAbstractExe1 {
  15. abstract void run();
  16. void test() {
  17. System.out.println("test of MyAbstractExe1 !!");
  18. }
  19. }
No ! we can not inherit a class from multiple abstract class. Syntax error by compiler at line 1

Can we have an abstract class with both abstract and concrete method ?

  1. abstract class MyAbstractExe {
  2. int x = 10;
  3. abstract void run();
  4. void test() {
  5. System.out.println("yes we can have an abstract class with concrete method !!");
  6. }
  7. }
Yes ! we can have an abstract class with both abstract & concrete method. there is no error.

Can we have an abstract class with concrete method ?

  1. abstract class MyAbstractExe {
  2. int x = 10;
  3. void test() {
  4. System.out.println("yes we can have an abstract class with concrete method !!");
  5. }
  6. }
Yes ! we can have an abstract class with concrete method !! There is no error.

Ca we have an abstract class without abstract method ?

  1. abstract class MyAbstractExe {
  2. int x = 10;
  3. }
Yes ! we can have an abstract class without abstract method. There will not be any error.

Can we have a constructor in an abstract class ?

  1. abstract class MyAbstractExe {
  2. MyAbstractExe() {
  3. System.out.println("yes we can have constructor in abstract class");
  4. }
  5. }
Yes ! we can have a constructor and there is no error.

Check palindrome using recursion


  1. public class PalindromeUsingRecursionAlgorithm {
  2. public static void main(String[] args) {
  3. String s = "ABCBAd";
  4. boolean flag = isPalindrome(s);
  5. if (flag) {
  6. System.out.println("Palindrome !!");
  7. } else {
  8. System.out.println("Not a palindrome !! ");
  9. }
  10. }

  11. public static boolean isPalindrome(String s) {
  12. int length = s.length();
  13. // An empty string is considered as palindrome
  14. if (length == 0) {
  15. return true;
  16. }
  17. int startIndex = 0;
  18. int endIndex = length - 1;
  19. return palindromeRecursion(s, startIndex, endIndex);
  20. }

  21. public static boolean palindromeRecursion(String str, int s, int e) {
  22. // if there is only character
  23. if (s == e) {
  24. return true;
  25. }
  26. // if first and last character do not match
  27. if (str.charAt(s) != str.charAt(e)) {
  28. return false;
  29. }

  30. // If there are more than two characters, check if middle substring is
  31. // also palindrome or not.

  32. if (s < e + 1) {
  33. return palindromeRecursion(str, s + 1, e - 1);
  34. }
  35. return true;
  36. }
  37. }
Output: Not a palindrome !! 

Friday, April 20, 2018

what is cyclic inheritance in java ?

Suppose class A extends class B and class B extends class A. then it will be known as cyclic inheritance.
e.g.

[1]
public class A extends B {
// some code
}
class B extends A {
// some code
}
[2]
public class A extends B {
// some code
}
public class B extends C {
// some code
}
public class C extends A {
// some code
}
[3]
public class A extends A {
// some code
}
error: cyclic inheritance involving.

Thursday, April 19, 2018

Write a program to print square grid pattern !!

// Method-I:
  1. /**
  2.  * 
  3.  * @author ishaan_sharma
  4.  *
  5.  */
  6. public class PrintGridPatternAlgorithm {
  7. public static void main(String[] args) {
  8. printPatten(10);
  9. }

  10. /**
  11.  * n accepts as an input argument to print rows and columns
  12.  * @param n
  13.  */
  14. public static void printPatten(int n) {
  15. for (int i = 0; i < n; i++) {
  16. for (int j = n; j > 0; j--) {
  17. System.out.print("* ");
  18. }
  19. System.out.println();
  20. }
  21. }
  22. }
Output
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 


// Method-II:
  1. /**
  2.  * 
  3.  * @author ishaan_sharma
  4.  *
  5.  */
  6. public class PrintPatternBy2DArrayAlgorithm {

  7. public static void main(String[] args) {
  8. int a[][] = new int[10][10];
  9. printPattern(a);
  10. }

  11. /**
  12.  * a takes 2D array value
  13.  * @param a
  14.  */
  15. public static void printPattern(int a[][]) {
  16. for (int i = 0; i < 10; i++) {
  17. for (int j = 0; j < 10; j++) {
  18. System.out.print(a[i][j] + " ");
  19. }
  20. System.out.println();
  21. }
  22. }
  23. }
Output: 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 

Write a program to sum values of an array !!

// Method-I:
  1. public class SumValueOfArrayAlgorithm {
  2. public static void main(String[] args) {
  3. int a[] = { 1, 3, 4, 5, 56, 4 };
  4. int sum = 0;
  5. for (int i : a) {
  6. sum = sum + i;
  7. }
  8. System.out.println(sum);
  9. }
  10. }
Output: 73


// Method-II:
  1. public class SumValueOfArrayAlgorithm {
  2. public static void main(String[] args) {
  3. int a[] = { 1, 3, 4, 5, 56, 4 };
  4. int sum = 0;
  5. for (int i = 0; i < a.length; i++) {
  6. sum = sum + a[i];
  7. }
  8. System.out.println(sum);
  9. }
  10. }
Output: 73

Write a program to sort a string array !!

// Method-I: (Using our own algorithm)

  1. public class SortStringArrayByOwnAlgorithm {
  2. public static void main(String[] args) {
  3. String s[] = { "Java", "C++", "Python", "ruby", "Perl", "ishaan" };
  4. String temp;
  5. for (int i = 0; i < s.length; i++) {
  6. for (int j = 0; j < s.length-1; j++) {
  7. if (s[j].compareTo(s[j+1]) > 0) {
  8. temp = s[j];
  9. s[j] = s[j+1];
  10. s[j+1] = temp;
  11. }
  12. }
  13. }
  14. for (String str : s) {
  15. System.out.print(str + " ");
  16. }
  17. }
  18. }
Output: C++ Java Perl Python ishaan ruby


// Mehod-II: (Using our own algorithm)
  1. public class SortStringArrayByOwnAlgorithm {
  2. public static void main(String[] args) {
  3. String s[] = { "Java", "C++", "Python", "ruby", "Perl", "ishaan" };
  4. String temp;
  5. for (int i = 0; i < s.length; i++) {
  6. for (int j = i + 1; j < s.length; j++) {
  7. if (s[i].compareTo(s[j]) < 0) {
  8. temp = s[i];
  9. s[i] = s[j];
  10. s[j] = temp;
  11. }
  12. }
  13. }
  14. for (String str : s) {
  15. System.out.print(str + " ");
  16. }
  17. }
  18. }
Output: ruby ishaan Python Perl Java C++


// Mehod-III: (Using pre-defined API)
  1. public class SortStringArrayAlgorithmExe {
  2. public static void main(String[] args) {
  3. String s[] = { "Java", "C++", "Python", "ruby", "Perl", "ishaan" };
  4. Arrays.sort(s);
  5. for (String str : s) {
  6. System.out.print(str + " ");
  7. }
  8. }
  9. }
Output: C++ Java Perl Python ishaan ruby 

Write a program to sort numeric array !!

// Method-I:
  1. public class SortIntegerArrayAlgorithm {
  2. public static void main(String[] args) {
  3. int a[] = { 2, 3, 4, 5, 22, 13, 5, 3 };
  4. int temp;
  5. for (int i = 0; i < a.length; i++) {
  6. for (int j = 0; j < a.length - 1; j++) {
  7. if (a[j] > a[j + 1]) {
  8. temp = a[j];
  9. a[j] = a[j + 1];
  10. a[j + 1] = temp;
  11. }
  12. }
  13. }
  14. for (int i : a) {
  15. System.out.print(i + " ");
  16. }
  17. }
  18. }
Output: 2 3 3 4 5 5 13 22
Note: This is also called Bubble sort algorithm.

// Method-II:
  1. public class SortIntArrayAlgorithm {

  2. public static void main(String[] args) {
  3. int a[] = { 1, 43, 4, 43, 33, 2, 2, 5, 5, 5, 5, 33, 777 };
  4. Arrays.sort(a);
  5. for (int i : a) {
  6. System.out.print(i + " ");
  7. }
  8. }
  9. }
Output: 1 2 2 4 5 5 5 5 33 33 43 43 777 
Note: Sorting has been done using pre-defined method not our own algorithm.

Bubble Sort Algorithm

// Bubble sort algorithm in increasing order:
  1. public class BubbleSortAlgorithm {

  2. public static void main(String[] args) {
  3. int a[] = { 3, 4, 5, 43, 2, 2, 45, 66, 5, 4, 32 };
  4. int temp;

  5. for (int i = 0; i < a.length; i++) {
  6. for (int j = 0; j < a.length-1; j++) {
  7. if (a[j] > a[j + 1]) {
  8. temp = a[j];
  9. a[j] = a[j + 1];
  10. a[j + 1] = temp;
  11. }
  12. }
  13. }
  14. for (int i : a) {
  15. System.out.print(i + " ");
  16. }
  17. }
  18. }
Ouput: 2 2 3 4 4 5 5 32 43 45 66
Average time complexity: O(n2)

// Bubble sort algorithm in decreasing order:
  1. public class BubbleSortAlgorithm {

  2. public static void main(String[] args) {
  3. int a[] = { 3, 4, 5, 43, 2, 2, 45, 66, 5, 4, 32 };
  4. int temp;

  5. for (int i = 0; i < a.length; i++) {
  6. for (int j = 0; j < a.length-1; j++) {
  7. if (a[j] < a[j + 1]) {
  8. temp = a[j];
  9. a[j] = a[j + 1];
  10. a[j + 1] = temp;
  11. }
  12. }
  13. }
  14. for (int i : a) {
  15. System.out.print(i + " ");
  16. }
  17. }
  18. }
Output: 66 45 43 32 5 5 4 4 3 2 2 
Average time complexity: O(n2)

// II Method: Increasing order
  1. public class BubbleSort{

  2. public static void main(String[] args) {

  3. int arr[] = { 5, 6, 4, 3, 3, 5, 6, 9, 8 };
  4. for (int i = 0; i < arr.length; i++) {
  5. for (int j = 0; j < arr.length; j++) {
  6. if (arr[i] < arr[j]) {
  7. int temp = arr[i];
  8. arr[i] = arr[j];
  9. arr[j] = temp;
  10. }
  11. }
  12. }
  13. for (int i : arr)
  14. System.out.print(i + " ");
  15. }
  16. }
Output: 3 3 4 5 5 6 6 8 9
Average time complexity: O(n2)

Bubble sort in decreasing order:
  1. public class BubbleSort {

  2. public static void main(String[] args) {

  3. int arr[] = { 5, 6, 4, 3, 3, 5, 6, 9, 8 };
  4. for (int i = 0; i < arr.length; i++) {
  5. for (int j = 0; j < arr.length; j++) {
  6. if (arr[i] > arr[j]) {
  7. int temp = arr[i];
  8. arr[i] = arr[j];
  9. arr[j] = temp;
  10. }
  11. }
  12. }
  13. for (int i : arr)
  14. System.out.print(i + " ");
  15. }
  16. }
Output: 9 8 6 6 5 5 4 3 3
Average time complexity: O(n2)

Tuesday, April 17, 2018

How to check palindrome ?

// Method - I:
  1. public class PalindromAlgoritham {

  2. public static void main(String[] args) {
  3. String s1 = "ABCBA";
  4. int p = s1.length() - 1;
  5. boolean flag = true;
  6. for (int i = 0; i < s1.length()/2; i++) {
  7. if (s1.charAt(i) != s1.charAt(p)) {
  8. flag=false;
  9. break;
  10. }
  11. p--;
  12. }
  13. System.out.println((flag?"Palindrome":"Not Palindrome"));
  14. }

  15. }
Output: Palindrome
Time complexity: O(n/2)

// Method - II:
  1. public class PalindromeByCharAtAlgorithm {

  2. public static void main(String[] args) {
  3. String s1 = "ABCDCBA ABCDCBA ABCDCBA";
  4. String rev = "";
  5. for (int i = s1.length() - 1; i >= 0; i--) {
  6. rev = rev + s1.charAt(i);
  7. }
  8. if (s1.equals(rev)) {
  9. System.out.println("Palindrome !!");
  10. } else {
  11. System.out.println("Not Palindrome !!");
  12. }

  13. }

  14. }
OutputPalindrome !!
Time Complexity: O(nlog(n))

// Method - III:
  1. public class PalindromeByStringBuilderAlgorithm {

  2. public static void main(String[] args) {

  3. String str = "313";
  4. int value = Integer.parseInt(str);

  5. StringBuilder sb = new StringBuilder(str);
  6. String reverse = sb.reverse().toString();
  7. int rvalue = Integer.parseInt(reverse);

  8. if (value == rvalue) {
  9. System.out.println("Palindrome !!");
  10. } else {
  11. System.out.println("Not palindrome !!");
  12. }
  13. }
  14. }
Output: Palindrome !!
Time Complexity: O(n)

How to check prime number ?

  1. public class PrimeNumberAlgorithm {
  2. public static void main(String[] args) {
  3. isPrimeNumber(11);
  4. }
  5. private static void isPrimeNumber(int n) {
  6. boolean isPrime = true;
  7. int m = n / 2;
  8. for (int i = 2; i <= m; i++) {
  9. if (n % i == 0) {
  10. isPrime = false;
  11. break;
  12. }
  13. }
  14. System.out.println(isPrime == true ? "Prime number !!" : "Not prime number !!");
  15. }
  16. }
Output: Prime number !!
Time complexity is O(n/2)

Monday, April 16, 2018

How to add two binary numbers ?


  1. public class AddBinayNumber {

  2. public static void main(String[] args) {
  3. String s1 = "11";
  4. String s2 = "1";
  5. String sum = addTwoBinaryNumber(s1, s2);
  6. System.out.println(sum);
  7. }

  8. private static String addTwoBinaryNumber(String s1, String s2) {
  9. StringBuilder sb = new StringBuilder();
  10. int p1 = s1.length() - 1;
  11. int p2 = s2.length() - 1;
  12. int carry = 0;
  13. while (p1 >= 0 || p2 >= 0) {
  14. int sum = carry;
  15. if (p1 >= 0) {
  16. char ch1 = s1.charAt(p1);
  17. sum = sum + ch1 - '0';
  18. p1--;
  19. }
  20. if (p2 >= 0) {
  21. char ch2 = s2.charAt(p2);
  22. sum = sum + ch2 - '0';
  23. p2--;
  24. }
  25. carry = sum >> 1;
  26. sum = sum & 1;
  27. sb.append(sum == 0 ? '0' : '1');
  28. }
  29. if (carry > 0) {
  30. sb.append('1');

  31. }
  32. sb.reverse();
  33. return sb.toString();
  34. }
  35. }
Output: 100

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...