Compress a given string in-place and with constant extra space.

Run-length encoding Program. OR
Given an input string, write a function that returns the Run Length Encoded string for the input string. OR
Compress a given string inplace and with constant extra space.


Compress a given string "aacccddd" to "a2c3d3"
Constraint: Inplace compression, no extra space to be used.
Assumption: Output size will not exceed input size. 

Example: input:"acc" output: "a1c2" buffer overflow, because output size length is 4 and input size length is 3. Such inputs will not be given.

Lets understand what is the input and the expected output.


Type Casting Interview Questions In Java

Type Casting Interview Questions In Java


Type casting helps calling methods of a class using generic reference thereby maintains Polymorphism.


Question 1. We have a requirement to display all the features of a Bird and a class is designed as shown below, how to display all the features of each Bird?

interface Bird{
 void walk();
}

interface Fly{
 void fly();
}

interface Swim{
 void swim();
}

class Duck implements Bird, Fly, Swim{
 @Override
 public void swim() {
  System.out.println("Duck.swim()");
 }

 @Override
 public void fly() {
  System.out.println("Duck.fly()");
 }

 @Override
 public void walk() {
  System.out.println("Duck.walk()");
 }
}

class Pigeon implements Bird, Fly{
 @Override
 public void fly() {
  System.out.println("Pigeon.fly()");
 }

 @Override
 public void walk() {
  System.out.println("Pigeon.walk()");
 }
}

For displaying all the features of Pigeon and Duck, we only need to know what all operations Birds can support like Fly, Swim etc?

Based on type checking, we can call particular operation and display all features.
class Zoo{
 public static void main(String[] args) {
  
  Bird bird1 = new Duck();
  bird1.walk();
  if(bird1 instanceof Fly){
   ((Fly)bird1).fly();
  }
  if(bird1 instanceof Swim){
   ((Swim)bird1).swim();
  }
  
  Bird bird2 = new Pigeon();
  bird2.walk();
  if(bird2 instanceof Fly){
   ((Fly)bird2).fly();
  }
  if(bird2 instanceof Swim){
   ((Swim)bird2).swim();
  }
 }
}

Interface typecast helps to achieve this kind of behaviour.


Question 2.
What is the output of below program? will there be any error/exception? if yes then compile time or run time and why?

class SampleClass1 {
    public void test(){}
}
class SampleClass2 {
    public void test(){}
}

class MainTest {

    public void main(String[] args) {
     SampleClass1 sc1 = new SampleClass1();
     SampleClass2 sc2 = (SampleClass2) sc1;
    }
}

It will give Compile Time Error: "Cannot cast from SampleClass1 to SampleClass2".
Casting is possible only if there is Parent-child relationship between classes.


Question 3.
What is the output of below program? will there be any error/exception? if yes then compile time or run time and why?

interface SInterface1 {}

class SampleClass1 {}

class MainTest1 {
 public static void main(String[] args) {
  SampleClass1 sc1 = new SampleClass1();  
  SInterface1 sc2 = (SInterface1) sc1;
 }
}

It will NOT give Compile Time Error but will give Runtime Exception: 
"java.lang.ClassCastException: SampleClass cannot be cast to SInterface1".

Question here is why it didn't gave Compile time error?
Compiler is really not sure here to give compile error because sc1 at runtime can be reference of 
class SampleClass2, say (class SampleClass2 extends SampleClass1 implements SInterface1) in that case typecasting is perfectly valid. So Compiler doesn't give Compile error in this case, but when you run the program it sees that sc1 doesn't point to class that implements SInterface1 and that is why it cannot be typecasted.

Valid typecase possible at runtime,
interface SInterface1 {}
class SampleClass1 {}

class SampleClass2 extends SampleClass1 implements SInterface1{}

class MainTest1 {
 public static void main(String[] args) {
  SampleClass1 sc1 = new SampleClass1(); 
  sc1 = new SampleClass2();
  SInterface1 sc2 = (SInterface1) sc1;
 }
}



Question 4.
What is the output of below program? will there be any error/exception? if yes then compile time or run time and why?

class ClassA{}
class ClassB{}

interface InterfaceI{}

class MainTest11 {
 public static void main(String[] args) {
  InterfaceI i = (InterfaceI)(new ClassA());
  ClassA b = (ClassB)(new ClassA()); 
 }
}

It will give Compile Time Error: "Cannot cast from ClassA to ClassB" at line 9.
It will give Runt Time ClassCastException: "ClassA cannot be cast to InterfaceI" at line 8.

Check below image for better understanding of how Compiler treats casting to 
Reference and Class,


Question 5.
What is the output of below program? will there be any error/exception? if yes then compile time or run time and why?

interface Interface1 { }
interface Interface2 { }
class Class1 implements Interface1 { }

class Test{
 public static void main(){
  Class1 c1 = new Class1();
  String str = new String("Hello"); //OR Integer str = new Integer(1); 

  Interface2 x = (Interface2)c1;  //why compiler does not complain here?
  Interface2 y = (Interface2)str; //why compiler complains here?
 }
}
It will not give Compile time Error at line 10 but gives Compile error at line 11, why?
According to Question 4, which explains rules of typecasting,

Interface2 x = (Interface2) c1;

Compiler will not care what c1 is, it just validates "whether c1 can be object of a Class which is subclass of c1's class type and implements Interface2"? 

For line 10, that is possible because there can be class like,
Class A extends Class1 implements Interface2{}
c1 = new A();
Interface2 x = (Interface2)c1;

For line 9, that is not possible, str can't be object of class,
  1. which extends String class and (This is not possible)
  2. Implements Interface2. (This is possible)
String is as final class, So no class can be subclass of (extends) String class, that is why compiler is sure and gave compile error at line 11.

If we declare Class1 final, then compiler will complain at line 10 as well.

You may also like to see


Advanced Java Multithreading Interview Question-Answer

How is ambiguous overloaded method call resolved in java?

Exception Handling Interview Question-Answer

Method Overloading - Method Hiding Interview Question-Answer

Method Overriding rules in Java

Interface interview questions and answers in Java

 

Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

Command Design Pattern.

Command Design Pattern.


Command Design pattern is used to decouple Sender and Receiver.
Sender is totally unaware of Receiver's interface and Receiver is unaware of Sender.
Sender and Receiver communicates using command.



Command Design Pattern Example In Java.



Receiver.java
abstract class Receiver{
 public abstract void append(String data);
 public abstract String getContent();
 public abstract void copy(String copyData);
 public abstract void paste();
 public abstract void cut(int startIndex, int endIndex);
 public abstract void setContent(String content);
 public abstract String getName();
}

Notepad.java
class Notepad extends Receiver{
 private StringBuilder content;
 private String copyData;

 public Notepad(String init) {
  content = new StringBuilder(init);
 }
 public void append(String data){
  content.append(data);
 }
 public String getContent() {
  return content.toString();
 }
 public void copy(String copyData){
  this.copyData = copyData;
 }
 public void paste(){
  content.append(copyData);
 }
 public void cut(int startIndex, int endIndex){
  content = content.delete(startIndex, endIndex);
 }
 public void setContent(String content) {
  this.content = new StringBuilder(content);
 }
 public String getName() {
  return "Notepad";
 }
}

Wordpad.java
class Wordpad extends Receiver{
 private StringBuilder content;
 private String copyData;

 public Wordpad(String init) {
  content = new StringBuilder(init);
 }
 public void append(String data){
  content.append(data);
 }
 public String getContent() {
  return content.toString();
 }
 public void copy(String copyData){
  this.copyData = copyData;
 }
 public void paste(){
  content.append(copyData);
 }
 public void cut(int startIndex, int endIndex){
  content = content.delete(startIndex, endIndex);
 }
 public void setContent(String content) {
  this.content = new StringBuilder(content);
 }
 public String getName() {
  return "Wordpad";
 }
}

Command.java
interface Command{
 public void execute();
 public void redo();
}

Undo.java
interface Undo{
 public void undo();
}

CopyCommand.java
class CopyCommand implements Command{ 
 private String copiedData = "";

 public CopyCommand(String copiedData) {
  this.copiedData=copiedData;
 }
 public void execute() {
  System.out.println("Successfully copied: "+copiedData);
 }
 public void redo() {
  execute();
 }
 public String getCopiedData() {
  return copiedData;
 }
}

PasteCommand.java
class PasteCommand implements Command, Undo{
 private Receiver receiver=null;
 private String contentToPaste="";
 private String previousContent="";

 public PasteCommand(Receiver receiver, String contentToPaste) {
  this.receiver=receiver;
  this.contentToPaste=contentToPaste;
 }
 public void execute() {
  previousContent = receiver.getContent();
  receiver.copy(contentToPaste);
  receiver.paste();
  System.out.println("Data Pasted successfully in "+ receiver.getName() +" new content is : "+receiver.getContent());
 }
 public void undo() {
  receiver.setContent(previousContent);
  System.out.println("Done undoing and receiver "+ receiver.getName() +" data is : "+receiver.getContent());
 }
 public void redo() {
  execute();
 }
}
CutCommand.java
class CutCommand implements Command, Undo{ 
 private Receiver receiver=null;
 private String previousContent=null;
 private int startIndex=0;
 private int endIndex=0;

 public CutCommand(Receiver receiver, int startIndex, int endIndex) {
  this.receiver = receiver;
  this.startIndex = startIndex;
  this.endIndex = endIndex;
 }
 public void execute() {
  previousContent = receiver.getContent();
  receiver.cut(startIndex, endIndex);
  System.out.println("Data Cut successfully in "+ receiver.getName() +" new content is : "+receiver.getContent());
 }
 public void undo() {
  receiver.setContent(previousContent);
  System.out.println("Done undoing and receiver "+ receiver.getName() +" data is : "+receiver.getContent());
 }
 public void redo() {
  execute();
 }
}

CommandManager.java
class CommandManager{
 private Stack<Command> redoCommandStack = null;
 private Stack<Command> undoCommandStack = null;

 public CommandManager() {
  undoCommandStack = new Stack<Command>();
  redoCommandStack = new Stack<Command>();
 }

 public void setCommand(Command command) {
  undoCommandStack.add(command);
 }
 public void execute(){
  undoCommandStack.peek().execute();
 }
 public void undo(){
  if(!undoCommandStack.isEmpty()){
   redoCommandStack.push(undoCommandStack.peek());
   ((Undo)(undoCommandStack.pop())).undo();

  }else{
   System.out.println("Nothing to undo");
  }
 }
 public void redo(){
  if(!redoCommandStack.isEmpty()){
   redoCommandStack.pop().redo();
  }else{
   System.out.println("Nothing to redo");
  }
 }
}

CommandDesignPattern.java
public class CommandDesignPattern {

 public static void main(String[] args) {

  CommandManager commandManager = new CommandManager();
  Notepad notepadReceiver = new Notepad("Notepad, how are you?");
  Wordpad wordpadReceiver = new Wordpad("Wordpad, how are you?");

  //COPY
  Command copyCommand2 = new CopyCommand("good");
  commandManager.setCommand(copyCommand2);
  commandManager.execute();

  //PASTE
  Command pasteCommand = new PasteCommand(wordpadReceiver, ((CopyCommand)copyCommand2).getCopiedData());
  commandManager.setCommand(pasteCommand);
  commandManager.execute();

  //CUT
  Command copyCommand1 = new CutCommand(notepadReceiver, 2, 5);
  commandManager.setCommand(copyCommand1);
  commandManager.execute();

  //UNDO
  System.out.println("\nUndo::");
  commandManager.undo();
  System.out.println("Undo::");
  commandManager.undo();

  //REDO
  System.out.println("\nRedo::");
  commandManager.redo();
  System.out.println("Redo::");
  commandManager.redo();
 }
}


 

Real World Example.


Resturant is a classic example of Command Pattern.
Customer(Invoker) is not aware of Chef(Receiver) and they communicate via Waiter(Command Manager) by giving Menu Name(Commands) to them.
Customer doesn't need to know how to communicate directly with Chef.

Command Design Pattern used in JDK API.


java.lang.Runnable interface exhibits Command design pattern.

Thread pools
  • A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. 
  • It maintains a pool of threads that execute commands from the queue. 
  • The items in the queue are command objects. 
  • Typically these objects implement a common interface such as java.lang.Runnable that allows the thread pool to execute the command even though the thread pool class itself was written without any knowledge of the specific tasks 

You may also like to see


Observer Design Pattern

When to use Builder design pattern

Adapter Design Pattern

Decorator Design Pattern

Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.