JP Morgan Interview Question for Senior Software Development Engineers


Country: United States
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
4
of 4 vote

public class Test1 {

	/**
	 * @param args
	 * @throws ExecutionException 
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException, ExecutionException {

		ExecutorService executerService = Executors.newFixedThreadPool(2);
		
		Task task1 = new Task(1, 2);
		
		Task task2 = new Task(3, 4);
		
		Future<Integer> asyncResult1 = executerService.submit(task1);
		
		Future<Integer> asyncResult2 = executerService.submit(task2);
		
		System.out.println(" Final output is - "+asyncResult1.get() * asyncResult2.get());
		

	}

	
	static class Task implements Callable<Integer>{

		
		Integer val1 = null;
		Integer val2 = null;
		
		public Task(Integer a, Integer b){
			this.val1 = a;
			this.val2 = b;
		}
		
		@Override
		public Integer call() throws Exception {			
			return this.val1 + this.val2;
		}
		
	}
	
}

- Kiran February 19, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

It takes fixed values, but they can be taken via scanner or some other way

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

public class MyCallable  {
    final static CountDownLatch cdl = new CountDownLatch(2);
    final static int a=10;
    final static int b=20;
    final static int c=30;
    final static int d=40;




    public static void main(String args[]){
       
        ExecutorService executor = Executors.newFixedThreadPool(2);
       
        //Create MyCallable instance
        int i=5;
        final int k;
        Callable<Integer> cl1= ()-> {

            
            cdl.countDown();
            return a+b;
        };
        Callable<Integer> cl2= ()-> {

            
            cdl.countDown();
            return c+d;
        };

            Future<Integer> future1 = executor.submit(cl1);
        Future<Integer> future2 = executor.submit(cl2);

        try {
            cdl.await();
            System.out.print(future1.get()*future2.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }catch (ExecutionException e) {
            e.printStackTrace();
        }

        //shut down the executor service now
        executor.shutdown();
    }

}

- YogiInMeditation February 15, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package main

import "fmt"

func Add(res chan int, i, j int) {
	res <- i + j
}

func Calc(a, b, c, d int) int {
	res := make(chan int)
	go Add(res, a, b)
	go Add(res, c, d)
	res1 := <-res
	res2 := <-res
	return res1 * res2
}

func main() {
	fmt.Println(Calc(1, 2, 3, 4))
}

- dmitry.labutin February 06, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/*  
 This is where other we seriously do some awesome stuff  
*/
def do_non_sense_using_thread(a,b,c,d){
  t1 = thread()->{ println('I am in thread with id :' +  $.i) ; a + b }
  t1.join()
  t2 = thread()->{ println('I am in thread with id :' +  $.i) ; c + d }
  t2.join()
  t1.value * t2.value 
}
println ( do_non_sense_using_thread( 1,2,3,4) )
/* The result : LOL  
I am in thread with id :10
I am in thread with id :11
21
*/

- NoOne February 06, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Scanner scanner = new Scanner(System.in);
        a = scanner.nextInt();
        b = scanner.nextInt();
        
        c = scanner.nextInt();
        d = scanner.nextInt();
        
        
        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                 a1 = a + b;
               System.out.println(a1);
            }
            
        };
        Thread add = new Thread(r1);
        add.start();
        
        Runnable r2 = new Runnable() {
            @Override
            public void run() {
                 a2 = c + d;
               System.out.println(a2);
            }
            
        };
        
        Thread add2 = new Thread(r2);
        add2.start();
        
        try {
            add2.join();
            add.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(Test1.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        
        Runnable r3 = new Runnable() {
            @Override
            public void run() {
               int ans = a1 * a2;  
               System.out.println(ans);
            }
        };

        Thread mul = new Thread(r3);
        mul.start();

- Unni February 08, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Scanner scanner = new Scanner(System.in);
        a = scanner.nextInt();
        b = scanner.nextInt();
        
        c = scanner.nextInt();
        d = scanner.nextInt();
        
        
        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                 a1 = a + b;
               System.out.println(a1);
            }
            
        };
        Thread add = new Thread(r1);
        add.start();
        
        Runnable r2 = new Runnable() {
            @Override
            public void run() {
                 a2 = c + d;
               System.out.println(a2);
            }
            
        };
        
        Thread add2 = new Thread(r2);
        add2.start();
        
        try {
            add2.join();
            add.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(Test1.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        
        Runnable r3 = new Runnable() {
            @Override
            public void run() {
               int ans = a1 * a2;  
               System.out.println(ans);
            }
        };

        Thread mul = new Thread(r3);
        mul.start();

- Unni February 08, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Test1 {

    private static volatile int a, b,c,d;
    
    private static volatile int a1,a2;
    
    public static void main(String []arg) {
        
        Scanner scanner = new Scanner(System.in);
        a = scanner.nextInt();
        b = scanner.nextInt();
        
        c = scanner.nextInt();
        d = scanner.nextInt();
        
        
        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                 a1 = a + b;
               System.out.println(a1);
            }
            
        };
        Thread add = new Thread(r1);
        add.start();
        
        Runnable r2 = new Runnable() {
            @Override
            public void run() {
                 a2 = c + d;
               System.out.println(a2);
            }
            
        };
        
        Thread add2 = new Thread(r2);
        add2.start();
        
        try {
            add2.join();
            add.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(Test1.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        
        Runnable r3 = new Runnable() {
            @Override
            public void run() {
               int ans = a1 * a2;  
               System.out.println(ans);
            }
        };

        Thread mul = new Thread(r3);
        mul.start();
        
        try {
            mul.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(Test1.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

- Unni February 08, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.concurrent.Callable;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class AddNumbersUsingExecutorService {

    public static void main(String[] args) throws Exception{
        // TODO Auto-generated method stub
        
        CopyOnWriteArrayList<Integer> al = new CopyOnWriteArrayList<>();
        
        AddNumService[] an = {new AddNumService(10, 20),
                new AddNumService(30, 40)
        };
        
        ExecutorService service = Executors.newFixedThreadPool(2);
        for(AddNumService an1 : an){
            Future<Integer> f = service.submit(an1);
            al.add(f.get());
        }
        service.shutdown();
        System.out.println(al.get(0) * al.get(1));
        al = null;
    }

}

class AddNumService implements Callable<Integer>{
    int num1, num2;
    public AddNumService(int num1, int num2) {
        // TODO Auto-generated constructor stub
        this.num1 = num1;
        this.num2 = num2;
    }

    @Override
    public Integer call() throws Exception {
        // TODO Auto-generated method stub
        System.out.println(Thread.currentThread().getName());
        return num1 + num2;
    }
    
}

- Utsav February 22, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class task implements Callable<Integer> {
int a, b;

task(int A, int B) {
this.a = A;
this.b = B;
}

@Override
public Integer call() throws Exception {
return a + b;
}

public static void main(String[] args) {
task thread1 = new task(20, 30);
task thread2 = new task(40, 50);
FutureTask<Integer> futuretask1 = new FutureTask<Integer>(thread1);
FutureTask<Integer> futuretask2 = new FutureTask<Integer>(thread2);
futuretask1.run();
futuretask2.run();
try {
System.out.println("(a+b)*(c+d) is: " + futuretask1.get()
* futuretask2.get());
} catch (Exception e) {
e.printStackTrace();
}
}
}

- RuchitaJain March 08, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class task implements Callable<Integer> {
int a, b;

task(int A, int B) {
this.a = A;
this.b = B;
}

@Override
public Integer call() throws Exception {
return a + b;
}

public static void main(String[] args) {
task thread1 = new task(20, 30);
task thread2 = new task(40, 50);
FutureTask<Integer> futuretask1 = new FutureTask<Integer>(thread1);
FutureTask<Integer> futuretask2 = new FutureTask<Integer>(thread2);
futuretask1.run();
futuretask2.run();
try {
System.out.println("(a+b)*(c+d) is: " + futuretask1.get()
* futuretask2.get());
} catch (Exception e) {
e.printStackTrace();
}}}

- RuchitaJain March 08, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Java 8 simple solution :

package com.practice;

import java.util.Scanner;

/**
 * Created by prateek on 14/3/17.
 */
public class ThreadProblem {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a,b,c,d : ");
        //Enter space separated values.
        int a = sc.nextInt();
        int b = sc.nextInt();
        int c = sc.nextInt();
        int d = sc.nextInt();

        int[] res = new int[2];
        Thread add1 =  new Thread(() -> {
            res[0] = a + b;
            System.out.printf("Thread %d : %d+%d=%d\n", Thread.currentThread().getId(),a,b,res[0]);
        });
        add1.start();

        Thread add2 = new Thread(() -> {
            res[1] = c + d;
            System.out.printf("Thread %d : %d+%d=%d\n", Thread.currentThread().getId(),c,d,res[1]);
        });
        add2.start();

        try {
            add1.join();
            add2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.printf("Thread %d : %d*%d=%d\n", Thread.currentThread().getId(),res[0], res[1], (res[0] * res[1]));

    }
}

- mail.prateek.agarwal March 14, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

import static java.lang.String.format;

public class ThreadPrinting {

    public static void main(String[] args) throws Exception {

        int[] inputs = {2,6,3,8};

        Callable<Integer> firstAddition = additionThread(inputs[0], inputs[1], 'a', 'b');
        Callable<Integer> secondAddition = additionThread(inputs[2], inputs[3], 'c', 'd');

        ExecutorService executorService = Executors.newFixedThreadPool(2);
        List<Future<Integer>> futureList = executorService.invokeAll(Arrays.asList(firstAddition, secondAddition));

        int result = futureList.parallelStream().mapToInt((integerFuture) -> {
            try {
                return integerFuture.get();
            } catch (Exception e) {
                e.printStackTrace();
                return 1;
            }
        }).reduce(1, (a, b) -> a * b);

        System.out.println(result);

    }

    private static Callable<Integer> additionThread(int a, int b, char first, char second) {
        return  () -> {
            int sum = a + b;
            System.out.println(format(" Thread %s -> %s +%s = %s",Thread.currentThread().getName() ,first, second, sum));
            return sum;
        };
    }
}

- binitbhas May 01, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args) throws InterruptedException, ExecutionException {
		System.out.println(calculate(1, 2, 3, 4));
	}

	private static Integer calculate(int a, int b, int c, int d) throws InterruptedException, ExecutionException {
		ExecutorService executerService = Executors.newFixedThreadPool(2);
		Future<Integer> asyncResult1 = executerService.submit(() -> a + b);
		Future<Integer> asyncResult2 = executerService.submit(() -> c + d);
		executerService.shutdown();
		return asyncResult1.get() * asyncResult2.get();
	}

- RP March 25, 2018 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More