Showing posts with label oops. Show all posts
Showing posts with label oops. Show all posts

Saturday, August 24, 2019

What is the output of the code?

Problem statement:
Given java code, what will be the output of it?
  1. interface Car {
  2. public void startEngine();
  3. }
  4. class MySuzuki implements Car {
  5. public void startEngine() {
  6. System.out.println("MySuzuki");
  7. }
  8. }
  9. class MyFerrari implements Car {
  10. public void startEngine() {
  11. System.out.println("MyFerrari");
  12. }
  13. }
  14. public class OOPSExample {
  15. public static void main(String[] args) {
  16. Car obj = new MySuzuki();
  17. obj.startEngine();
  18. }
  19. }
Output:
MySuzuki

Sunday, August 11, 2019

What is the output of the following code?

Problem statement: 
Given the code of java. Can you tell me the output of this?
  1. interface Annonymous {
  2.     public int getValue();
  3. }
  4. public class Sample1 {
  5.     int data = 15;
  6.     public static void main(String[] args) {
  7.         Annonymous a = new Annonymous() {
  8.             int data = 5;
  9.             public int getValue() {
  10.                 return data;
  11.             }
  12.             public int getData() {
  13.                 return data;
  14.             }
  15.         };
  16.         Sample1 s = new Sample1();
  17.         System.out.println(a.getValue() + a.getData() + s.data);
  18.     }
  19. }
Output:
compilation error at line number 17 due to a.getData(). Here getData() is not a method of Annonymous interface.

Tuesday, May 14, 2019

how do you check whether two strings are anagram to each other?

Problem statement:
Given two Strings S1 and S2. You have to check whether these two strings are anagram to each other?
  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. public class Anagram {
  4.     public static void main(String[] args) {
  5.         String S1 = "LISTEN";
  6.         String S2 = "SILENT";
  7.         if (areAnagram(S1, S2)) {
  8.             System.out.println("Anagram");
  9.         } else {
  10.             System.out.println("Not an Anagram");
  11.         }
  12.     }
  13.     static boolean areAnagram(String s1, String s2) {
  14.         char c1[] = s1.toCharArray();
  15.         char c2[] = s2.toCharArray();
  16.         int n1 = c1.length;
  17.         int n2 = c2.length;
  18.         if (n1 != n2)
  19.             return false;        
  20.         Arrays.sort(c1);
  21.         Arrays.sort(c2);        
  22.         for (int i = 0; i < n1; i++)
  23.             if (c1[i] != c2[i])
  24.                 return false;
  25.         return true;
  26.     }
  27. }
Output: 
Anagram

Sunday, May 12, 2019

what will be the output of the following code?

Problem statement:
what is the output of the following code?
  1. interface Test1 {
  2.     default void run() {
  3.         System.out.println("test1");
  4.     }
  5. }
  6. interface Test2 {
  7.     default void run() {
  8.         System.out.println("test2");
  9.     }
  10. }
  11. public class A implements Test1, Test2 {
  12.     public void run() {
  13.         System.out.println("A");
  14.     }
  15.     public static void main(String args[]) {
  16.         A a = new A();
  17.         a.run();
  18.         Test1 t1 = new A();
  19.         t1.run();
  20.         Test2 t2 = new A();
  21.         t2.run();
  22.     }
  23. }
Output:
A
A
A

what is the output of the program?

Problem statement:
what is the output of the following code?
  1. public class A {
  2.     public static void showMe() {
  3.         System.out.println("A");
  4.     }
  5. }
  6. class B extends A {
  7.     public static void showMe() {
  8.         System.out.println("B");
  9.     }
  10. }
  11. class C extends B {
  12.     public static void showMe() {
  13.         System.out.println("C");
  14.     }
  15. }
  16. class Main {
  17.     public static void main(String[] args) {
  18.         A a = new B();
  19.         a.showMe();
  20.         A a1 = new A();
  21.         a1.showMe();
  22.         B b = new C();
  23.         b.showMe();
  24.         C c = new C();
  25.         c.showMe();
  26.     }
  27. }
Output:
A
A
B
C

Friday, July 20, 2018

Can we have different return type in method overriding in java?

Problem statement: can we have different return type in method overriding in java

Yes ! it may differ but their are some limitations. 

Before Java 5.0, when you override method, both parameters and return type must match exactly
In Java 5.0, it introduces a new facility called covariant return type. You can override a method with the same signature but returns a subclass of the object returned. In another words, a method in a subclass can return an object whose type is a subclass of the type returned by the method with the same signature in the superclass.
For example:
class OverridingExe2 {
    public Object run() {
        System.out.println("object");
        return null;
    }
}
public class OverridingExe1 extends OverridingExe2 {
    public String run() { // covariant return type from java 5.0
        System.out.println("string");
        return null;
    }
    public static void main(String args[]) throws Exception {
        OverridingExe2 r = new OverridingExe1();
        r.run();
    }
}
Output:
string

Monday, July 16, 2018

How do you calculate Square Root of a number in Java?

Problem statement: Find the square root of a number in java !
1st Approach:
public class SquareRootExe {
    public static void main(String args[]) {
        double sqrRoot = squareRoot(4);
        System.out.println(sqrRoot);
    }
    public static double squareRoot(double n) {
        double t;
        double sqRoot = n / 2;
        do {
            t = sqRoot;
            sqRoot = (t + (nt)) / 2;
        } while ((t - sqRoot) != 0);
        return sqRoot;
    }
}
2nd Approach:
public class SquareRootExe {
    public static void main(String args[]) {
        double sqrRoot = squareRoot(4);
        System.out.println(sqrRoot);
    }
    public static double squareRoot(double n) {
        double res = Math.sqrt(n);
        return res;
    }
}
Output:
2.0

How do you calculate Cube Root of a number in Java?

Problem statement: Find the cube root of a number in java.
public class CubeRootExe {
    public static void main(String args[]) {
        double cbRt = cubeRoot(8);
        System.out.println(cbRt);
    }
    public static double cubeRoot(double n) {
        return Math.cbrt(n);
    }
}
Output:
2.0

what is the code for cloning an object in java?

class Human implements Cloneable {
    int age;
    long salary;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
public class CloningExe {
    public static void main(String args[]) throws CloneNotSupportedException {
        Human h1 = new Human();
        h1.age = 21;
        h1.salary = 1200;
        System.out.println("h1 age: " + h1.age + ", h1 salary: " + h1.salary);
        Human h2 = (Human) h1.clone();
        System.out.println("-----------------------");
        System.out.println("h1 age: " + h1.age + ", h1 salary: " + h1.salary);
        System.out.println("h2 age: " + h2.age + ", h2 salary: " + h2.salary);
    }
}
Output:
h1 age: 21, h1 salary: 1200
-------------------------------
h1 age: 21, h1 salary: 1200
h2 age: 21, h2 salary: 1200

2nd Approach:
class Human implements Cloneable {
    int age;
    long salary;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
public class CloningExe {
    public static void main(String args[]) throws CloneNotSupportedException {
        Human h1 = new Human();
        h1.age = 21;
        h1.salary = 1200;
        System.out.println("h1 age: " + h1.age + ", h1 salary: " + h1.salary);
        Human h2 = (Human) h1.clone();
        h2.salary = 1300;
        System.out.println("-----------------------");
        System.out.println("h1 age: " + h1.age + ", h1 salary: " + h1.salary);
        System.out.println("h2 age: " + h2.age + ", h2 salary: " + h2.salary);
    }
}
Output:
h1 age: 21, h1 salary: 1200
------------------------------
h1 age: 21, h1 salary: 1200
h2 age: 21, h2 salary: 1300

what is the code for deep copy in java?

class Human {
    int age;
    long salary;
}
public class DeepCopyExe {
    public static void main(String args[]) {
        Human h1 = new Human();
        h1.age = 20;
        h1.salary = 1000;
        System.out.println("h1 age: "+h1.age+", h1 salary: "+h1.salary);
        Human h2 = new Human();
        h2.salary = 1200;
        System.out.println("h1 age: "+h1.age+", h1 salary: "+h1.salary);
        System.out.println("h2 age: "+h2.age+", h2 salary: "+h2.salary);
    }
}
Output:
h1 age: 20, h1 salary: 1000
h1 age: 20, h1 salary: 1000
h2 age: 0, h2 salary: 1200

what is the code for shallow copy in java?

class Human {
    int age;
    long salary;
}
public class ShallowCopyExe {
    public static void main(String args[]) {
        Human h1 = new Human();
        h1.age = 20;
        h1.salary = 1000;
        System.out.println("h1 age: "+h1.age+", h1 salary: "+h1.salary);
        Human h2 = h1;
        h2.salary = 1200;
        System.out.println("h1 age: "+h1.age+", h1 salary: "+h1.salary);
        System.out.println("h2 age: "+h2.age+", h2 salary: "+h2.salary);
    }
}
Output:
h1 age: 20, h1 salary: 1000
h1 age: 20, h1 salary: 1200
h2 age: 20, h2 salary: 1200

what do you mean by Shallow Cloning and Deep Cloning in java?

Problem statement: Shallow copy vs Deep copy.
shallow = little depth
Shallow copy [meaning reference copy]
is method of copying an object and is followed by default in cloning. In this method the fields of an old object X are copied to the new object Y. While copying the object type field the reference is copied to Y i.e object Y will point to same location as pointed out by X. If the field value is a primitive type it copies the value of the primitive type

Therefore, any changes made in referenced objects in object X or Y will be reflected in other object


Deep copy [meaning object copy]

If we want to create a deep copy of object X and place it in a new object Y then new copy of any referenced objects fields are created and these references are placed in object Y. This means any changes made in referenced object fields in object X or Y will be reflected only in that object and not in the other. In below example, we create a deep copy of object.

A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.

Explanation with program:

import java.util.ArrayList;
class TestExe {
    int x, y;
}
// reference of TestExe and implements clone with deep copy
class Test2 implements Cloneable {
    int a, b;
    TestExe c = new TestExe();
    public Object clone() throws CloneNotSupportedException {
        // Assign the shallow copy to new reference variable t
        Test2 t = (Test2) super.clone();
        t.c = new TestExe();
        return t;
    }
}
public class DeepCloning {
    public static void main(String args[]) throws CloneNotSupportedException {
        Test2 t1 = new Test2();
        t1.a = 10;
        t1.b = 20;
        t1.c.x = 30;
        t1.c.y = 40;
        Test2 t2 = (Test2) t1.clone();
        t2.a = 100;
        // Change in primitive type of t2 will not be reflected in t1 field
        t2.c.x = 300;
        // Change in object type field of t2 will not be reflected in t1(deep copy)
        System.out.println(t1.a + " " + t1.b + " " + t1.c.x + " " + t1.c.y);
        System.out.println(t2.a + " " + t2.b + " " +t2.c.x + " " + t2.c.y);
    }
}
Output:
10 20 30 40
100 20 300 0

Wednesday, May 23, 2018

Class vs Object vs Instance

Problem statement: what are the difference between Class, Object & Instance?
In OO Programming, we often hear of terms like “Class”, “Object” and “Instance”; but what actually is a Class / Object / Instance?
In short, An object is a software bundle of related state and behavior. A class is a blueprint or prototype from which objects are created. An instance is a single and unique unit of a class.
Example, we have a blueprint (class) represents student (object) with fields like name, age, course (class member). And we have 2 students here, Foo and Bob. So, Foo and Bob is 2 different instances of the class (Student class) that represent object (Student people).
Let me go into details…
Object
Real world objects shares 2 main characteristics, state and behavior. Human have state (name, age) and behavior (running, sleeping). Car have state (current speed, current gear) and state (applying brake, changing gear). Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields and exposes its behavior through methods.
Class
Class is a “template” / “blueprint” that is used to create objects. Basically, a class will consists of field, static field, method, static method and constructor. Field is used to hold the state of the class (eg: name of Student object). Method is used to represent the behavior of the class (eg: how a Student object going to stand-up). Constructor is used to create a new Instance of the Class.
Instance
An instance is a unique copy of a Class that representing an Object. When a new instance of a class is created, the JVM will allocate a room of memory for that class instance.

Thursday, May 3, 2018

Difference between final, finally and finalize()

final:
  • final is a keyword
  • final is used to apply restrictions on class, method and variable
  • final class cannot be inherited
  • final method cannot be overriden
  • final variable value cannot be changed
  1. class FinalExample {
  2. public static void main(String[] args) {
  3. final int x = 100;
  4. x = 200;// Compile Time Error
  5. }
  6. }
finally:
  • finally is a block
  • finally block always execute, whether exception is handled or not
  • in one scenario finally block doesn't execute is System.exit(0);
  1. class FinallyExample {
  2. public static void main(String[] args) {
  3. try {
  4. int x = 300;
  5. } catch (Exception e) {
  6. System.out.println(e);
  7. } finally {
  8. System.out.println("finally block is executed");
  9. }
  10. }
  11. }
finalize():
  • finalize() is a method
  • finalize is used to perform clean up processing just before object is garbage collected
  1. class FinalizeExample {
  2. public void finalize() {
  3. System.out.println("finalize called");
  4. }
  5. public static void main(String[] args) {
  6. FinalizeExample f1 = new FinalizeExample();
  7. FinalizeExample f2 = new FinalizeExample();
  8. f1 = null;
  9. f2 = null;
  10. System.gc();
  11. }
  12. }

Output of the program [method overloading-iii]

Problem statement: Output of the method overloading program !
  1. class MethodOverload {}

  2. class MethodOverloadExe2 {
  3. public void run(Object o) {
  4. System.out.println("object");
  5. }
  6. public void run(String o) {
  7. System.out.println("string");
  8. }
  9. public void run(MethodOverload o) {
  10. System.out.println("user data type");
  11. }
  12. }
  13. public class OverloadingExe2 {
  14. public static void main(String[] args) {
  15. MethodOverloadExe2 m = new MethodOverloadExe2();
  16. m.run(null);
  17. }
  18. }
Output:
The method run(Object) is ambiguous for the type MethodOverloadExe2

Output of the program [Method overlaoding-i]

Problem statement: Output of the program !!
  1. class MethodOverloadExe {
  2. public void run(Object o) {
  3. System.out.println("object");
  4. }
  5. public void run(String o) {
  6. System.out.println("string");
  7. }
  8. }
  9. public class OverloadingExe {
  10. public static void main(String[] args) {
  11. MethodOverloadExe m = new MethodOverloadExe();
  12. m.run(null);
  13. }
  14. }
Output:
string

Sunday, April 29, 2018

Can we override static method in java?

No ! we cannot override the static methods. Since static method belongs to class level not object level.

class StaticExe1 {
public static void run() {
System.out.println("run of StaticExe1");
}
public  void fly() {
System.out.println("fly of non-static Exe1");
}
}

class StaticExe2 extends StaticExe1 {
public static void run() {
System.out.println("run of StaticExe2");
}
public  void fly() {
System.out.println("fly of non-static Exe2");
}
}
class StaticExe3 extends StaticExe2 {
public static void run() {
System.out.println("run of StaticExe3");
}
public  void fly() {
System.out.println("fly of non-static Exe3");
}
}

public class StaticMethod {

public static void main(String[] args) {

StaticExe2 ex = new StaticExe3();
ex.run();
ex.fly();
}


}
Output:
run of StaticExe2

fly of non-static Exe3

Tuesday, April 24, 2018

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 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.

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...