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

java Interview Goal

                                                  Hi All,         I write this blog for Fresher  And  Experience  who have start Career In IT_Industry With  java Technology, I am not a professional blogger, I am  working  as Java Developer since last 2 years,   The main reason to write this blog is to share my Experience In Interviews. ABOUT THE AUTHOR           Nice to meet you, I’m Akshay Ingole. I’m a not a professional blogger ,  I am  working  as Java Developer since last 2 years,   The main reason to write this blog is to share my Experience In Interviews as well as share the topics that trending in java.   I hope It is Useful For All. 

The Future of Java Developers in the Age of AI and ChatGPT

  In today's rapidly evolving tech landscape, AI tools like ChatGPT are becoming more integrated into the software development process. As a Java developer, whether you're just starting out or have years of experience, you might wonder: How can I stay relevant and succeed in the age of AI? In this post, we'll explore practical strategies to ensure you not only survive but thrive as a Java developer in this AI-driven world. 1. Embrace AI as a Tool, Not a Threat AI isn't here to replace you—it's here to help you. Tools like ChatGPT can automate repetitive tasks, assist with coding challenges, and even generate code snippets, allowing you to focus on more complex and creative aspects of development. For Freshers: Use AI tools to learn and understand Java more quickly. Let them assist you in writing code, but make sure you're also learning the logic and concepts behind it. For Experienced Developers: Integrate AI tools into your workflow to enhance productivity. L...

What are the best opportunities for java in 2021?

Firstly, Java is widely used for building enterprise-scale web applications. Java is known to be extremely stable and so, many large enterprises have adopted it. If you are looking for a development based job at a large organization, Java is the language that you should learn. It is widely used in Android App Development. So if anyone is willing to find a career in Android App Development, he/she should have an intermediate level of experience in Java. Some of the different domains where Java is used widely are as follows: Financial services:  It is used in server-side applications. Big Data:  Hadoop MapReduce framework is written using Java. Banking:  To deal with transaction management. Stock market:  To write algorithms as to which company they should invest in. Retail:  Billing applications that you see in a store/restaurant are completely written in Java. Android:  Applications are either written in Java or use Java API. Scientific and Research Communi...