Sunday, July 7, 2019

Stock Buy & Sell Problem

Question: There is a given array of the stock price, each index denotes the price of the stock on that day. You need to find the max profit you will earn if you buy and sell the stock.

Example - Given an array - [10,5,6,8,9,3] where index 0 shows the prices of the stock on day 1 respectively.

Answer   Maxprofit=4
Explanation - first, we purchase at day 2 ( price - 5) and sell at day 5 (price 9 ) profit = 9-5=4

Code - 

package com.vp.learning;

public class StockBuyAndSellProblem {

 public static void main(String[] args) {

  //  given stock data as 
  int[] prices = {10,5,6,8,9,3};

 static int getMaxProfit(int[] prices) {

   return 0;

  int i = 0 ;
  int peak = prices[0];
  int valley = prices[0];
  int maxProfit = 0;
  while(i<prices.length-1) {
   while(i <prices.length-1 && prices[i]>= prices[i+1])
   valley = prices[i];
   while(i <prices.length-1 && prices[i]<= prices[i+1])
   peak = prices[i];

   maxProfit+=peak - valley ;

  return maxProfit;


Explanation :

 What we are doing here is as below

We are using Peak Valley Approach where are first calculate valley value in array

  • valley means lower value 
  • peak means higher value
Now while(i <prices.length-1 && prices[i]>= prices[i+1])

This is calculating the valley values, means the less value index in the array.

second, while loop is calculating the peak value in the array after this valley index.

if you see prices[i]>= prices[i+1] this means, price at current day is greater then the price at next day , that means the next day is valley or lower value, similarly for the next while as well, the price of current is less than the next day, so the next day will be peak value 

and the differences between peak and valley is actually the max profit we will earn for the day.

Time Complexity 

In this case, the time complexity will be O(n)

Hope this will help you in the interview. If you have any issue, please leave us a comment.

Thanks for reading 

Friday, May 17, 2019

Algorithm to find if String contains only Unique characters without using any additional data structure

The string is one of the most asked questions in the Interview of Java developers.

Today we will see one of the most asked questions as to how will you find if String does not contain any duplicate characters.

There are different ways to check them, But we will only discuss the most efficient way to implement this algorithm.


We know that characters have only 256 ascii values and there are only 128 values for alphabet characters. 
So what we will do is we will create one array of boolean of size 128 and we will update the index of array as true whenever we find the char value in the string , else if we get the same value in the string , the already true value will make the loop as false.
Also read - Find Longest Common Ancestor(LCA) Program in java

Time Complexity - O(n)
Space Complexity - O(1)

Code -

public class ArraysAndStringDemo {
 public static void main(String[] args) {
  String str = "programinjava";
 public static boolean isUnique(String str) {
  boolean[] char_set = new boolean[128];
  for(int i =0;i<str.length();i++) {
     int value =str.charAt(i); //getting the ascii value of character
     if(char_set[value])     // checking if it is already in the array
   return false;
     char_set[value] = true;
  return true;


If you have any issue in understanding the same , Please leave us a comment. Happy to help

Thanks for reading

Saturday, March 9, 2019

Real time Logs of AWS Elastic Beanstalk by Command Prompt

Many of us know that one of the most important services of AWS is Elastic beanstalks. We deployed our application on Beanstalk and AWS itself manage most of the thing in it. One of them is Logs of Applications.

People usually were not able to see the tail of the logs of the application what they need to do is to go to the beanstalk and under logs, they ask for the last 100 lines of logs or full logs (which include the of the application along with the other logs ).

Today we will learn how to connect with the beanstalk application through EB CLI and see the logs.

let's follow the below steps.
  1. Install the Python Once installed run below commands
  2. python --version
  3. pip --version
  4. pip install awsebcli --upgrade --user
  5. once ebcli installed successfully, you can check by 
  6. eb --version
  7. define the Python Home in your Environment Variable.
  8. Now Run your command prompt as Administrator  and write 
eb init --interactive
You will see the below image.
  • Now select the region you have deployed your application.
  • After that, you will be asked to Create a new Application 
  • Once your application will be created you will see below screen.
  • You need to select the appropriate platform you have used for your application.
  • Now Once you do it you will be asked to create the SSH 
Select Yes 
  • Then they will ask you to create the keypair 

  • Provide your password  and then you will see the below image 
  • Now you have successfully created your SSH and it is uploaded to your beanstalk as well.
  • you need to attach the SSH with the Application.

Follow below steps 

eb ssh <Application-name> --settings

  • You will get the list of options then it will ask for the keypair which you need to attach.
  • Select the appropraite one.
  • After selecting the one you will be asked to enter the password set earlier.
  • You will then have the Applicaiton connected.
  • Once connected successfully you will be getting below image.
Now go to 
/var/log/tomcat8 ( to see the application logs, if your application is deployed on tomcat)

I Hope you will be able to connect your local machine to EB , If you have any issue  ,Please leave us a comment we will look into it.

Also Read:
  1. Spring Boot and Hibernate Tutorials - Application using Spring Boot
  2. What is Spring boot ?
  3. How to read value from property file in spring boot ?
  4. First Rest API Application - Top Spring Framework Interview Questions
  5. Implementation of Swagger in Spring boot
  6. How to use h2 database in spring boot

Thanks for reading.

Saturday, February 16, 2019

Database Timezone issue -Solution in java

We have at least once in our development has encountered one issue with database and client location is Timezone difference. 

In most of the cases, Our Backend /Application server is in a different timezone and our client server is in a different timezone. So what actually the problem happens is the difference in data time because of Timezone.

Wednesday, November 28, 2018

Thread Pooling In Java Using Executors Class

Most of the Important and most of the developer found one topic in java they perform a task and then they get destroyed. Purpose of multithreading is to perform multiple tasks simultaneously for effective utilization of our resources (time and CPU).

Imagine that there are 10 tasks to perform, so using traditional multithreading mechanism we will need 10 threads. Do you see a drawback in this approach? I see it; creation of a new thread per task will cause resource overhead.

Sunday, September 2, 2018

Remote Debugging of Java Application deployed on AWS Elastic Beanstalk

Most of the time we stuck in the situation where we need to do remote debugging of the application which is running on some server or somewhere other than localhost. We need to debug the code in eclipse. To do that we need to allow the running application to allow remote debugging. 

Generally, we know how to do remote debug in eclipse while the code is running on tomcat. In this post, we will see how to do remote debug when the application is deployed over AWS by elastic beanstalk.

Let's start.

To do Remote debug of AWS deployed the application, we need to follow below steps.

1)We need to Go to AWS Console -> Elastic Beanstalk -> Application -> Configuration

2) Under Configuration you need to go to Software ->Modify ->Container Options 
 Now in Container Options, search for JVM options    In this text box you need to write the below arguments.
-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005
Now, these arguments say that - The remote debug will be listening at 5005 port.

3) Now you need to Go to EC2 Instance running from AWS Console -> EC2

4) After that you need to check which security group is defined for that EC2 Instance, you need to allow this port to communicate outside AWS.

5)For that, you need to add the Port in Inbound and Outbound of the Security Group
   Select the Custom Protocol and define the Port as 5005 and then define Anywhere in Ip accessible.

After this, you will be able to communicate the port with the local debugger of the eclipse.

Now you need to configure the Local Eclipse environment for Remote debugging.

Configure Local Eclipse 

For this you need to go to  Run ->Debug Configuration -> Remote debugging 

Under that define the IP of the application ( you need to find the IP of the application at EC2 Instance Properties )

Define the port as 5005 ( as defined above).

Run the application and hurray, are now connected with the AWS application running.

Now you will be able to debug remotely.

Hope you like the post, If so please share it with your friends and family.

Thanks for reading

Saturday, August 18, 2018

Upload File on AWS S3 Using Java

Most of us know nowadays that AWS  is used for almost everything because of its cheap price as well its availability.

AWS S3 is an online storage for storing file and images and zip, literally everything you want to put. 

Most of us have some use cases where we want to upload the image to aws s3 so that it can we used anywhere we want.

#Usercase we need to get the file or Image from UI and need to upload it to AWS S3 using java.

#Approach To Achieve it 
  • first, need to add the AWS SDK for Java 
  • Then we need to Get the client of AWS which is basically creating a connection with AWS 
  • After successfully getting the connection we will use s3 API to put the image as an object in AWS.

We first need to Add the dependency of AWS SDK in our project ( maven dependency as below )


After this, we need to have the AWS Account Access key and access_id
you can get it from

Access key file will look like below

aws_secret_access_key=<Your Secret_access_key>
Note change <Your-Access-key_id> and <Your Secret_access_key> values with your access key.

Now you need to save the access key file at a location below.

~/.aws/credentials on Linux, macOS, or Unix
C:\Users\USERNAME \.aws\credentials on Windows

Now let see the Code for the Uploading of Image /File on AWS.  (Ref : here )
 we will create one jsp file where we create upload file and call the spring controller , under the controller, you can see the file and it will store to the aws s3.

Thyemleaf Html Code

<!DOCTYPE html>
<html xmlns:th="">
<title>File Upload Example</title>
<link href="webjars/bootstrap/3.3.7/css/bootstrap.min.css"
 rel="stylesheet" />
<script type="text/javascript" src="webjars/jquery/3.3.1/jquery.min.js"></script>
<script src="webjars/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script th:inline="javascript">
 var _validFileExtensions = [ ".csv", ".zip" ,".png" ];
 function Validate(oForm) {
  var arrInputs = oForm.getElementsByTagName("input");
  for (var i = 0; i < arrInputs.length; i++) {
   var oInput = arrInputs[i];
   if (oInput.type == "file") {
    var sFileName = oInput.value;
    if (sFileName.length == 0) {

     alert("Please select a file to upload");
     return false;
    if (sFileName.length > 0) {
     var blnValid = false;
     for (var j = 0; j < _validFileExtensions.length; j++) {
      var sCurExtension = _validFileExtensions[j];
      if (sFileName.substr(
        sFileName.length - sCurExtension.length,
        sCurExtension.length).toLowerCase() == sCurExtension
        .toLowerCase()) {
       blnValid = true;

     if (!blnValid) {
      alert("Invalid File Extension");
      return false;

  return true;


 <div class="container-fluid padding-0">
  <div class="row padding-0">
   <div class="col-md-4">
    <h2>File Upload Example</h2>
   <div class="col-md-4" align="right"></div>
 <nav role="navigation" id="trainingset-container-id"
  class="navbar navbar-default">
  <div class="row" style="margin-top: 10px;">
   <div class="col-md-2">
    <B>Upload File</B>
   <div class="col-md-6">
    <form method="POST" action="/upload"
     onsubmit="return Validate(this);" enctype="multipart/form-data">
     <div class="col-sm-6">

      <input type="file" name="file"  />
     <div class="col-sm-6">
      <input type="submit" class="btn btn-success btn-sm" value="Upload data" />
  <div id="messageboxid">
   <div id="uploadstatus" th:if="${message}">
    <B>Status Of Uploaded File</B>
    <h6 th:text="${message}" />
This will see like this

Now we will see the Upload Controller Code.


package com.programinjava.learn.controller;


import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Regions;

public class UploadController {
 public String singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {

  if (file.isEmpty()) {
   redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
   return "redirect:uploadStatus";
//  bucket name 
  String bucketName ="atserve-photos";
//  get it from user or change it 
  String nameOffile ="myPhoto";
//  getting aws access 
  AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                .withCredentials(new ProfileCredentialsProvider())
  boolean isBucketExist =s3Client.doesBucketExist(bucketName);
  if(!isBucketExist) {
  try {
   InputStream is = file.getInputStream();
   s3Client.putObject(new PutObjectRequest(bucketName,nameOffile,is,new ObjectMetadata()).withCannedAcl(CannedAccessControlList.PublicRead));
   redirectAttributes.addFlashAttribute("message", "SuccessFully Uploaded On AWS S3");
  }catch(Exception e) {
  return "redirect:/uploadStatus";
 public String uploadStatus(ModelMap m) {
  return "Homepage";
 public String displayHomePageForAlarm() {
  return "Homepage";


Let see what we get on AWS S3

So this is how we can see the myPhoto is now uploaded on AWS S3.


Also, learn

Wednesday, August 8, 2018

Mocking of static method in unit testing

While we do unit testing, we mostly encounter the situation where we need to do the unit testing of a method which is calling a static method. if we are using mockito for doing mocking, We will have to suffer as mockito don't provide Static method mocking.

Let's see in a simple manner what is required and how we achieve it.

# Objective: We need to mock the static class which is being used in a method for which we are writing unit test.

# Solution: We have to use Powermockito for that 

What is PowerMockito?
PowerMockito is a PowerMock’s extension API to support Mockito. It provides capabilities to work with the Java Reflection API in a simple way to overcome the problems of Mockito, such as the lack of ability to mock final, static or private methods.

Getting Start with Powermockito

Also read: JUnit Tests Basics and how to do unit testing in java

First, you need to add the dependency in pom.xml

Now as you are using powermockito , you need to change the JUNIT Runner class as
<StaticClassName> will be replace with you static class Name.

Now let see the example.

Project Structure
Now let see the class for with we will write test case.

public class Rectangle {
 public int getAreaOfRectangle(int length , int breadth) {
  return AreaFinder.findArea("rectangle", length, breadth);


The Static Class

public class AreaFinder {
 public static int findArea(String type , int length , int breadth) {
  if(type.equals("rectangle")) {
   return length*breadth;
  }else if(type.equals("square")) {
   return length*length;
  }else {
   return 0;



Test Class

@PrepareForTest(AreaFinder.class)      // need to add the static class for which you mock the method
public class RectangleTest {

 public void getAreaOfRectangleTest() {
  Rectangle rec = new Rectangle();
  int length =10;
  int breadth =20;

  PowerMockito.mockStatic(AreaFinder.class);   // mocking of static class
  PowerMockito.when(AreaFinder.findArea("rectangle", length, breadth)).thenReturn(200); // defining behaviour
  Assert.assertEquals(200, rec.getAreaOfRectangle(length, breadth));


When you run this you will be able to see the test will be run successfully and it will get passed.

If you have any issue regarding the above concept, please let us know.

I hope this will help you in understand how to do mocking of static method in  unit testing.

Thanks for reading

Friday, July 20, 2018

producer consumer problem implementation using wait notify methods.

producer-consumer problem using wait notify

Most of you have heard about the Producer-Consumer problem where one is producing something and another is consuming it.

So basically what actually the producer-consumer problem says 

Producer-Consumer Problem says that if we have a shared resource among 2 threads, and producer's job is to generate the data and put it in the buffer and consumer's job is to take the data from the buffer but then where is the problem? So problem is there should not be a scenario where the producer has produced the data more than the buffer size, which results in overflow problem also consumer should not consume all the data in the buffer and again try, which result in underflow problem. 
So basically its a multi-thread synchronization problem.

Read about: Concurrency CountDownLatch in java

Now, what is the solution?
We can use wait-notify mechanism to solve this problem of synchronization.

  1. We will have 2 thread one is to produce random data and second will get the random data from the shared LinkedList (or and queue).
  2. we will write on a class called processor where there will be 2 methods one is produce() and second will be consume () 
  3. In produce() method we will write random generator and also be checking whether the size of linked list is less than 10 or not if greater we will call wait method over the object called lock which we are using for the locking mechanism.
  4. when produce() put the data in linkedlist it will call lock.notify() which will notify the second thread that there are some data stored in the linked list.
  5. now in consume() we will have a check for the linked list size should not be 0 if so we will call lock.wait() else we will take the data from the list and notify the producer().
Now let see the implementation of the above approach.

learn more about wait notify ()

#Implemenation (this class will have the produce() and consume() method in it )

class Processor {
 LinkedList<Integer> list = new LinkedList<>();
 Object lock = new Object();
 int value =0;
 public void produce() throws InterruptedException{
   synchronized (lock) {
    while(list.size() == 10)
 public void consume() throws InterruptedException {
  Random random = new Random();
  synchronized (lock) {
   while(list.size() == 0)
   int i =list.removeFirst();
   System.out.println("Got the value "+i + "now the list size is "+list.size());

Now we will see the 2 thread class and how we are calling them.


public class ProducerConsumerWithWaitNotify {
 public static void main(String[] args) {
  Processor pro = new Processor();
  Thread t1 = new Thread(new Runnable() {
   public void run() {

    try {
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
  Thread t2 = new Thread(new Runnable() {
   public void run() {

    try {
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block


After executing the code what will be the result, It will be like below

Got the value 0now the list size is 9
Got the value 1now the list size is 9
Got the value 2now the list size is 9
Got the value 3now the list size is 9
Got the value 4now the list size is 9
Got the value 5now the list size is 9
Got the value 6now the list size is 9
Got the value 7now the list size is 9
Got the value 8now the list size is 9
Got the value 9now the list size is 9
Got the value 10now the list size is 9
Got the value 11now the list size is 9
Got the value 12now the list size is 9
Got the value 13now the list size is 9
Got the value 14now the list size is 9

I hope this will help you in understanding the producer-consumer problem implementation using wait notify method in java

If you have any issue or concern, please leave us a comment, will be happy to help

Thanks for reading

Thursday, July 19, 2018

Comparator interface and its example in java

In our previous post we have learn about what is comparable , In this article we will see basics about Comparator.

#What is Comparator ?
Comparator is a interface which is used to order the different user defined objects. When we have 2 object of different classes we want to order them we will use comparator.

Learn about What is Comparable?

#UserCase :
We have an array of person , we want to sort them on different basis , like on the basis of age of the person , or on the basis of name of the person. there are 2 questions comes in our mind , can we use comparable , - No ( as we can only compare on one of the 2 basis not both) , can we use comparator - Yes .


  1. We will first create one person class .
  2. Now we will create 2 different Custom Comparator classes which will implements Comparator<person>
    1. One will be AgeComparator.
    2. Second will be NameComparator.
  3. Now we will create one Main class where we will create list of person. and then we will use Collections.sort and pass the list along with the comparator , we want to use for sorting.

class Person{
 int age;
 String name;
 public int getAge() {
  return age;
 public void setAge(int age) {
  this.age = age;
 public String getName() {
  return name;
 public void setName(String name) { = name;
 public String toString() {
  return "Person [age=" + age + ", name=" + name + "]";

class AgeComparator implements Comparator<Person>{

 public int compare(Person arg0, Person arg1) {
  // TODO Auto-generated method stub
  return arg0.getAge() - arg1.getAge();

class NameComparator implements Comparator<Person>{

 public int compare(Person o1, Person o2) {
  // TODO Auto-generated method stub
  return o1.getName().compareTo(o2.getName());

Main Class

public class ComparatorDemo {
 public static void main(String[] args) {
  List<Person> list = new ArrayList<>();
  Person p1 = new Person();
  Person p2 = new Person();
//  Collections.sort(list,new AgeComparator());
  Collections.sort(list,new NameComparator());
  list.forEach(s-> System.out.println(s));


Person [age=45, name=rohan]
Person [age=35, name=vishal]

Here we can see that the Objects are sorted on the basis of name , we can also do it by using age comparator as well.

If you have any issue , Please let us know , if you want any other topic to be covered in our next article please leave us a comment.

If you like this article please share it with your friends as well.

Thanks for reading