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

The Future of Java Developers in the AI Decade

In this AI decade, Java developers are positioned to play a crucial role in various areas: 1. AI and Machine Learning: While Python is often the language of choice for AI and machine learning, Java still has its place, especially in enterprise-level applications and systems where stability, scalability, and security are paramount. Java developers can work on integrating AI and machine learning capabilities into existing Java-based systems or developing new AI-powered applications using Java frameworks like Deeplearning4j or Weka. 2. Big Data and Analytics: With the growing importance of big data analytics, Java developers can contribute to building robust data processing and analytics systems. Java is widely used in big data frameworks like Apache Hadoop and Apache Spark, enabling developers to work on distributed computing, data processing, and real-time analytics applications. 3. Cloud Computing: As more companies move their infrastructure to the cloud, Java developers can leverage t

Fresher Need to start from this technology

For freshers, some technologies are relatively simpler to start with due to their ease of learning and abundant resources available for beginners: 1. Python: Known for its readability and simplicity, Python is often recommended as a first language due to its clean syntax and vast community support. It's used in various fields like web development, data analysis, artificial intelligence, and more. 2. HTML/CSS: Fundamental for web development, HTML (HyperText Markup Language) and CSS (Cascading Style Sheets) are essential and relatively easy to grasp. They form the backbone of web pages and are essential for anyone interested in web development. 3. JavaScript:Alongside HTML and CSS, JavaScript is crucial for web development, adding interactivity and functionality to websites. It's beginner-friendly and essential for front-end development. 4. Java: Although it might have a steeper learning curve than Python, Java is widely used in enterprise applications, Android development, and

What is JDK, JRE and JVM?

What are JDK, JRE, and JVM: JDK :- Java Development Kit (in short JDK) is Kit which provides the environment to Develop and execute(run ) the Java program. For eg. You(as Java Developer) are developing an accounting application on your machine, so what do you going to need into your machine to develop and run this desktop app? You are going to need  J-D-K  for that purpose for this you just need to go to the official website of sun or oracle to download the latest version of JDK into your machine. Hence, JDK is a kit(or package) which includes two things i) Development Tools(to provide an environment to develop your java programs) and ii) JRE (to execute your java program). JDK is only used by Java Developers. JRE: - Java Runtime Environment (to say JRE) is an installation package which provides an environment to only run(not develop) the java program(or application)onto your machine. For eg(continuing with the same example) after developing your accounting application