Skip to main content

Logical Interview Questions and Answers

Logical Interview Questions and Answers


Logic-based interview puzzles are becoming increasingly popular in recruitment processes to help employers find the brightest candidates and gain insight into a candidate’s thought process.

1. Find FaboconiSeries?

public static void FaboconiSeries()
 {
 int n=10;
 int a=0;
 int b=1;
 System.out.println(a+","+b);
 for(int i=0;i<n;i++)
 {
int c=a+b;
 a=b;
 b=c;
 System.out.println(c+".................FaboconiSeries");
 }
  }

2. Find ArmstrogNumber?

public void ArmstrogNumber()
 {
 int n=153;
 int temp=n;

 int sum=0;
 while(temp!=0)
 {
int a=temp%10;
sum=sum+a*a*a;
temp=temp/10;
 }
 if(sum==n)
 {
 System.out.println("yes................ArmstrogNumber");
 }
 }

3. Find Factorial?

 public void Factorial()
 {
 int n=5;
   int a=1;
for(int i=1;i<=n;i++)
{System.out.println(a+","+i);
a=a*i;
System.out.println(a+","+i);
}
System.out.println(a+".................Factorial");
 }

4. Find Reversestring?

public void reversestring()
 {
 //using n
 String s="akshay";
 char[] ch=s.toCharArray();
 for(int i=ch.length-1;i>=0;i--)
 {
 System.out.print(ch[i]);
 }

 //using n/2

 String s1="akshay";
 char[] ch1=s1.toCharArray();
 for(int i=0;i<=ch1.length/2;i++)
 {
 char temp=ch1[i];
 ch1[i]=ch1[ch1.length-i-1];
 ch1[ch1.length-i-1]=temp;
 }
 System.out.println(Arrays.toString(ch1));
 }

5. Find using recursion reverse?

//using recursion reverse
 public static String stringreverse(String str)
 {
 String s1="a";
 String s2="a";
 if(s1.equals(s2))
 {
 System.out.println("true");
 }
 if(str.isEmpty())
 {
 return str;

 }
return stringreverse(str.substring(1))+str.charAt(0);
 }

6. Find Occurance Of Array?


 public void occurance()
 {
 int[] array= {1,2,3,1,4,1,1,2,3,4,5,5,4};

 HashSet<Integer> hs = new HashSet<>();
 for(int i=0;i<array.length;i++) {
 hs.add(array[i]);
 }

 for(int c:hs)
 {
 int count=0;
 for(int j=0;j<array.length;j++)
 {
 if(c==array[j])
 {
 count++;
 }
 }
 System.out.println(c+"occurance is:=="+count);
 }
 }
}

#Common Class And Main Method For Calling All Methods Above.

import java.util.Arrays;
import java.util.HashSet;

abstract public class Logical
{
 public static void main(String[] args)
 {
       Logical l=new Logical();
      l.occurance();                                  // Calling Accurance
       String t=l.stringreverse("akshay");
       System.out.println(t);                        //Calling Reverse String
       l.FaboconiSeries();                              //Calling Faboconi Series
       l.ArmstrogNumber();                         //Calling Armstrong Number
       l.Factorial();                                        //Calling Factorial
      l.reversestring();                                  //Calling Reverstring
 Logical.FaboconiSeries();
 }

7.occurance of string character.

import java.util.*;
public class HelloWorld

 public static void main(String []args)
{
   System.out.println("Hello World");
   String str="abcdeabscderdscaaaaa";
   char[] arr=str.toCharArray();
   HashSet<Character> hs= new HashSet(); 
   for(int i=0;i<arr.length;i++)
   {   
    hs.add(arr[i]);
    } 
   System.out.println(hs);
   for(char set:hs)
    {
         int count=0;
         for(int j=0;j<arr.length;j++)
   {
          if(set==arr[j])
           count++;
   }   
  System.out.println(set+"::occurance is:"+count);
 }
     }
}

8.The occurrence of number.

import java.util.*;
public class HelloWorld
{
     public static void main(String []args){
     System.out.println("Hello World");
     int a[]={3,4,2,3,5,6,7,2,3,4,4,56};
     HashSet<Integer> a1=new HashSet<Integer>();
     for(int i=0;i<a.length;i++)
     {
            a1.add(a[i]);
      }
     System.out.println(a1);
     for(int set:a1)
     {        int count=0;

             for(int j=0;j<a.length;j++)
            {
                if(set==a[j])
                {
                    count++;
                }
            }
       System.out.println(set+"occuerance is:"+count);
        }
     }
}

 9.The occurrence of number by key.

import java.util.*;
public class HelloWorld
{
        public static void main(String []args){
        System.out.println("Hello World");
        int a[]={3,4,2,3,5,6,7,2,3,4,4,56};
        int x=5;
        int count=0;
        for(int i=0;i<a.length;i++)
        {
            if(x==a[i])
            {
                count++;
            }
        }
   System.out.println("occurence is:"+count);
 }
}

10.largest number.

//by using list.size()-1
import java.util.*;
public class HelloWorld
{
  public static void main(String []args)
  {
  System.out.println("Hello World"); 
   int[] a={11,23,34,56,76,78,33,12};
  TreeSet<Integer> a1=new TreeSet<Integer>();
    for(int i=0;i<a.length;i++)
   {
            a1.add(a[i]);
    }
  System.out.println(a1);
 List<Integer> list= new ArrayList<Integer>(a1);
  System.out.println(list.get(list.size()-1));
  }
}

//method-2
import java.util.*;
public class HelloWorld
{
   public static void main(String []args)
  {
   System.out.println("Hello World"); 
   double[] numArray = {34,23,65,33,76,90,112,43};
   double search = numArray[0];
    for (int i=0;i<numArray.length;i++)
    {
        if(search < numArray[i])
        search = numArray[i];
     }
   System.out.format("Largest element = %.2f", search);
  }
}

11. Convert String to Int Without using ParseInt() Method.

    public class StringToInteger
   {
    public static void main(String[] args)
    {
        int i = convertToInt("123679");
        System.out.println("String decoded to number " + i);
    }
    public static int convertToInt(String input)
   {
        char[] ch=input.toCharArray();
        int sum=0;
       for(char c:ch)
       {
           sum=(sum*10)+(int)c -(int)'0';
       }
       return sum;
    }
}

12.reverse String in Size/2.

public class ReverseString
 {
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.println("Please enter String");
String str=input.nextLine();
char[] myarray=str.toCharArray();
int size=myarray.length;
char[] original=Arrays.copyOf(myarray, size);
for(int i=0;i<size/2;i++)
{
char temp= myarray[i];
myarray[i]=myarray[size-i-1];
myarray[size-i-1]=temp;
}
System.out.println("orignal array is:"+Arrays.toString(original));
System.out.println("reverse array is"+Arrays.toString(myarray));
}

}

13.Reverse string.

  public class HelloWorld
 {
       public static void main(String []args){
       String str="ashish";
       char[] test=str.toCharArray();
       for(int i=test.length-1;i>=0;i--)
      {
        System.out.println(test[i]);
      }
    }
}

14.Reverse Integer

import java.util.*;
public class HelloWorld
{
     public static void main(String []args)
     {
      int a=4567896;
      int reverse=0;
     System.out.println("integer is:"+a);
      while(a !=0)
        {
          reverse=reverse*10 +a%10;
           a=a/10;
        }
        System.out.println("reverse is"+reverse);
     }
}

15.Devide without Mod.

package org.ashish;
import java.util.*;
public class DivideWithoutMod
{
 public static void main(String[] args)
{
 Scanner input=new Scanner(System.in);
 System.out.println("Enter Divident");
 int divident=input.nextInt();
 System.out.println("Enter Divisor");
 int divisor=input.nextInt();
 int Qoutient=0;
 while(divident>=divisor)
{
divident=divident-divisor;
Qoutient++;

}
System.out.println("Remainder is:"+divident);
System.out.println("Qoutient is:"+Qoutient);
}
}

16.Ascending Order.

import java.util.Arrays;
public class HelloWorld
{
 public static void main(String []args)
{     
   System.out.println("Hello World");
   int numb=7;
   int[]arr={4,2,1,6,7,5,3};
   System.out.println("original array is:"+Arrays.toString(arr));
   int temp; 
  for(int i=0;i<numb-1;i++)
  {
      for(int j=0;j<numb-i-1;j++)
     {                 
        if(arr[j]>arr[j+1])
        {
           temp=arr[j];
           arr[j]=arr[j+1];
           arr[j+1]=temp;       
          }     
      }     
 }
        System.out.println("Sorted array is:"+Arrays.toString(arr)); 
 }
}

17.Araay Union and Intersection by Hashing.

import java.util.HashSet;
// Java program to find union and intersection
// using Hashing
class Main

    // Prints union of arr1[0..m-1] and arr2[0..n-1]
      static void Union(int a[],int b[])
     {
       HashSet<Integer> hs= new HashSet<>(); 
       for(int i=0;i<a.length;i++)
       hs.add(a[i]);
       for(int j=0;j<b.length;j++)
       hs.add(b[j]);
       System.out.println(hs);
     }
     static void Intersection(int a[],int b[])
    {
        HashSet<Integer> hs=new HashSet<>();
        for(int i=0;i<a.length;i++)
        hs.add(a[i]);
        for(int j=0;j<b.length;j++)
        if(hs.contains(b[j]))
        System.out.println(b[j]+"");
     }
   
// Prints intersection of arr1[0..m-1] and arr2[0..n-1]
// Driver method to test the above function
   public static void main(String[] args)
  {
        int a[] = {7, 1, 5, 2, 3, 6};
        int b[] = {3, 8, 6, 20, 7};
        System.out.println("Union of two arrays is : ");
        Union(a,b);
        System.out.println("Intersection of two arrays is : ");
        Intersection(a,b);     
  }
}

18.Iterator & List

Public class test
{
 public static void main(String []args)
{
  System.out.println("Hello World");   
  ArrayList<String> al = new ArrayList<String>(5); 
 al.add("ashish");
 al.add("anita");     
 al.add("ashu");   
 al.add("suniti");   
 al.add("sandip"); 
 al.add("sonal"); 
 System.out.println("original Content of al is:");
 Iterator it= al.iterator();
 while(it.hasNext()) 
 {
   Object elem=it.next();
   System.out.println("Name:"+elem);
  }
ListIterator lit=al.listIterator();
while(lit.hasNext())
{
     Object elem=lit.next();
      lit.set(elem+"test");
      System.out.println("after modification al is:");
   
    it= al.iterator();
   while(it.hasNext())
   {
          Object elem=it.next();
          System.out.println("Name:"+elem);
   }
   while(lit.hasPrevious())
  {
        Object elem=lit.previous();
         System.out.println(elem+"");
   }
  }
}

19.String anagram.

import java.util.*;
public class HelloWorld
{
 public static void main(String []args){
 System.out.println("Hello World");
 boolean status=true;
 String str="keep";
 String str1="peek";
 if(str.length()!=str1.length())
 {
   status=false;
  }
  else{
     char[] chr=str.toLowerCase().toCharArray();
     char[] chr1=str1.toLowerCase().toCharArray();
     Arrays.sort(chr);
     Arrays.sort(chr1);
    status=Arrays.equals(chr,chr1);
}
if (status)
{
  System.out.println(str + " and " + str1 + " are anagrams");
 }
  else{
           System.out.println(str + " and " + str1 + " are not anagrams");
        }
    }
}

20. Mixed Array addition finds occurrence.

import java.util.*;
public class HelloWorld
{
public static void main(String []args){
System.out.println("Hello World");
int[] arr={1,2,3,-1,2,4,3,2};
int sum;
ArrayList list =new ArrayList();
for(int i=0;i<arr.length;i++)
{
  for(int j=1+i;j<arr.length;j++)
  {
     sum=arr[i]+arr[j];
     list.add(sum);
   }
  }
  System.out.println(list);
   int length=list.size();
   HashSet<Integer> hs=new HashSet(list);
   System.out.println(hs);
   for(Object set:hs)
  {
   int count=0;
  for(int i=0;i<length;i++)
 {
    if(set==list.get(i))
   {
        count++;
    }
  }
    System.out.println(set+":occurance is:"+count);
 }
}
}

21.LowerCase to UperCase and Upper to lower.

import java.util.*;
public class HelloWorld{
public static void main(String []args)
{
  System.out.println("Hello World");
  StringBuffer str= new StringBuffer("KeepReady");
  convertOpposite(str);
  System.out.println(str);
  }
 public static void convertOpposite(StringBuffer str)
 {
   for(int i=0;i<str.length();i++)
   {
     Character c=str.charAt(i);
     if(Character.isLowerCase(c))
      {
         str.replace(i, i+1, Character.toUpperCase(c)+"");
      }
     else{
            str.replace(i, i+1, Character.toLowerCase(c)+""); 
           }
        }
}

22.String Length without length method.

public class Main
{
 public static void main(String[] args)
 {
System.out.println("Hello World");
String str="abcde";
int count=0;
for(char c:str.toCharArray())
{
  count++;  
}
System.out.println(count);
}
}

23. Write Custom Exception .

 class myException extends Exception
{
     myException(String s)
    {
        super(s);
    }
}
public class Main
{
     static void validate(int age) throws myException
    {
        if(age<18)
        {
            throw new myException("under age need id proof");
        }
        else{
                throw new myException("above 18 ok");
               }
      public static void main(String[] args)
      {
System.out.println("Hello World");
try{
validate(19);
}
catch(Exception e)
{
    System.out.println(e);
}
}
}

24.Custom_Thread.

1.By implementing Runnable Interface:

public class Main implements Runnable
{
    public void run()
   {
System.out.println("thread running");
    }
     public static void main(String[] args)
    {
           System.out.println("Hello World");
Main m = new Main();
Thread t= new Thread(m);
t.start();
     }
}

2.By extending Thread Class:

public class Main extends Thread
{
    public void run(){
System.out.println("thread running");
    }
    
public static void main(String[] args) {
System.out.println("Hello World");
Main m = new Main();
m.start();
}
}

24.Write MVC configuration-XML based

1.Dispatcher Servlet configuration(web.xml)

<servlet>
<servlet-name>Spring</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>spring</servlet-name>
 <url-pattern>/</url-pattern>
</servlet-mapping>

2.Spring web configuration File(Spring-servlet.xml)

<beans>
<context:component-scan base-package = "com.tutorialspoint" />
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name = "prefix" value = "/WEB-INF/jsp/" />
      <property name = "suffix" value = ".jsp" />
   </bean>
<bean>
<bean>
</beans>

Comments

Popular posts from this blog

What is Amazon Web Services (AWS)?

 Amazon Web Services Amazon Web Services is a cloud computing platform provided by Amazon. The AWS offers all three service models such as Software as a Service (SaaS), Infrastructure as a Service (IAAS), and Platform as a Service (PaaS). There are more services which comprise the Amazon Web Services including Amazon Elastic Compute Cloud (EC2) which provides virtual servers, Amazon Simple Storage Service (S3) which provides scalable storage for backups, analytics. Then there are other services such as Amazon relational database management system, DynamoDB, AWS Migration hub, and more. AWS provides services in almost every category from mobile development to data analytics. Benefits of using Amazon Web Services: AWS gives access to organizations to use programming models , database and operating system. It provides a cost effective service in which you only have to pay for what you use. Applications can be deployed in multiple regions with just a few clicks. ...

What is Java Unit testing, and how do I learn it...

What is Java Unit testing, and how do I learn it... Java Unit testing is when you create small tests to verify that small bits of your code are working as “units.” Typically you write these tests in Java itself. In each test, you might get the system into a certain state, then you interact with the system to exercise the behavior you want to test. You finally verify whether or not the system did what you expected. A primary goal is to reduce the number of defects that you integrate into the rest of the source base. You’ll find numerous tutorial articles if you search. Most people use JUnit, a simple tool that you’ll find in Eclipse or IDEA.

Which is best, Java or Python in 2020?

Depends what you want to do. You  can  use either language for almost anything, but they definitely have different strengths and weaknesses that can help you decide which one is better for what you are doing. Python is good for: Numeric computing and AI All kinds of science and academic stuff (including natural language processing) Rapid prototyping Website backends Learning and teaching programming concepts all kinds of workflow scripting and other small programs for getting simple jobs done. interfacing with C libraries. Java is good for: Creating and distributing applications (on mobile and desktop) high-performance network backends. creating robust, reliable software at a large scale, especially in teams. implementing more foundational software systems like databases (though you might find C++ a better match for that) As a starting point to learning the JVM and leveraging it for a number of other interesting languages it hosts like Kotlin, Scala, Cloju...