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

IPL 2025: The Ultimate Season Preview, Stats, and Predictions

 The Indian Premier League (IPL) 2025 is set to be bigger and better than ever. With a mega auction, new regulations, and rising superstars, this season is shaping up to be the most thrilling edition in IPL history. Let’s dive deep into team analyses, key player stats, historic milestones, and predictions to see what IPL 2025 has in store! IPL 2025 at a Glance Start Date: March 22, 2025 Final Match Venue: Eden Gardens, Kolkata Total Matches: 74 Teams: 10 New Rule: Introduction of 'Power Boost Over' (Allows a team to add an extra over to Powerplay if all wickets are intact by the 8th over) --- Interesting IPL 2025 Data & Records 1. The ₹100 Crore Auction - Highest Spending in IPL History Total Money Spent: ₹1050 crore (~$125 million) Most Expensive Player: Rishabh Pant (Lucknow Super Giants) - ₹27 crore Shreyas Iyer (Punjab Kings) - ₹26.75 crore Trent Boult (Delhi Capitals) - ₹18.5 crore 2. The ‘Orange Cap’ Race - Run-Scoring Machines Predicting the top contenders for the hi...

Java 24 Released: What's New and Why It Matters?

 Oracle has officially released Java 24 on March 18, 2025, bringing a host of new features aimed at improving developer productivity, security, and performance. This release includes over 20 enhancements, making Java even more powerful for modern application development. Let’s dive into the key features and improvements in Java 24 and understand why they matter. --- 1. AI and Machine Learning Support Java 24 introduces features designed to enhance AI-powered applications. Developers can now integrate AI models and perform AI inference more efficiently using built-in Java capabilities. Why It Matters? With AI becoming a crucial part of modern applications, Java 24 makes it easier to process and deploy AI models without relying heavily on third-party libraries. --- 2. Post-Quantum Cryptography To prepare for the future threats of quantum computing, Java 24 includes new cryptographic algorithms that protect against potential security breaches. Why It Matters? Quantum computers could p...

The Mysterious Journey of Astronaut Sunita Villms: A Struggle Between Earth and the Unknown

 Astronaut Sunita Williams and her colleague, Barry "Butch" Wilmore, recently returned to Earth after an unexpected nine-month mission aboard the International Space Station (ISS). Originally scheduled for a brief eight-day stay, their mission was extended due to technical issues with the Boeing Starliner spacecraft, leading to a prolonged 286-day duration in space.  Mission Extension and Challenges The mission's extension was primarily due to propulsion problems with the Starliner craft, necessitating their continued presence on the ISS. This unforeseen prolongation presented both physical and psychological challenges for the astronauts. Prolonged exposure to microgravity can lead to muscle atrophy, bone density loss, and other health concerns. To mitigate these effects, astronauts adhere to rigorous exercise regimens while aboard the station.  Health Observations Upon Return Upon their return, noticeable physical changes were observed, particularly with Sunita Williams,...