Showing posts with label Java Interview Questions. Show all posts
Showing posts with label Java Interview Questions. Show all posts

Find the Occurrences Of Each Character In a String

Find the Occurrences Of Each Character In a String without using collection.
Here we are going to create simple array to store the character occurrence. If we look at ASCII value of each character including space then it starts from 32 to 126. So we will create array size of 94 which can hold all the character occurrences.

Find the Occurrences Of Each Character In a String


Let's see simple example in Java how to implement in a simple way.

public class CharacterOccurrance {

 public static void main(String[] args) {
  String str = "Java Discover~";

  CharacterOccurrance obj = new CharacterOccurrance();
  int[] occurrance = obj.findCharOccurrance(str);
  obj.printOccurrance(occurrance);
 }

 public int[] findCharOccurrance(String str) {
  int[] occurrance = new int[95];
  for (int i = 0; i < str.length(); i++) {
   int index = str.charAt(i);
   occurrance[index - 32]++;
  }
  return occurrance;
 }

 public void printOccurrance(int[] occurrance) {
  System.out.println("Character : Occurrance");
  for (int i = 0; i < occurrance.length; i++) {
   if (occurrance[i] > 0) {
    char ch = (char) (i + 32);
    System.out.println(ch + " \t  : " + occurrance[i]);
   }
  }
 }
}



OUTPUT:


Character : Occurrance
     : 1          <----- Space
D    : 1
J    : 1
a    : 2
c    : 1
e    : 1
i    : 1
o    : 1
r    : 1
s    : 1
v    : 2
~    : 1

Save Ironman

Jarvis is weak in computing palindromes for Alphanumeric characters.
While Ironman is busy fighting Thanos, he needs to activate sonic punch but Jarvis is stuck in computing palindromes.
You are given a string containing the alphanumeric character. Find whether the string is palindrome or not.
If you are unable to solve it then it may result in the death of Iron Man.
Input:
The first line of the input contains t, the number of test cases. Each line of the test case contains string 'S'.
Output:
Each new line of the output contains "YES" if the string is palindrome and "NO" if the string is not a palindrome.
Constraints:
1<=t<=100
1<=|S|<=100000
Note: Consider alphabets and numbers only for palindrome check. Ignore symbols and whitespaces.
Example:
Input:

2
am :IronnorI Ma, i
Ab?/Ba
Output:
YES
YES


import java.util.Scanner;

public class SaveIronman {

 private static final Scanner scanner = new Scanner(System.in);

 public static void main(String[] args) {

  int lengthsCount = scanner.nextInt();
  scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

  String values[] = new String[lengthsCount];
  for (int i = 0; i < lengthsCount; i++) {
   String str = scanner.nextLine();
   values[i] = str;
  }
  findPalindromes(values);
 }
 
 public static void findPalindromes(String[] values) {
  
  for (String string : values) {
   
   char[] strCh = string.toCharArray();
   StringBuilder strBuild = new StringBuilder();
   for (char c : strCh) {
    if(Character.isDigit(c)) strBuild.append(Character.toString(c));
    if(Character.isAlphabetic(c)) strBuild.append(Character.toString(c).toLowerCase());
   }
   boolean flag = true;
   for(int i=0,j=strBuild.length()-1;i<j;i++,j--) {
    if(strBuild.charAt(i) != strBuild.charAt(j)) {
     System.out.println("NO");
     flag = false;
     break;
    }
   }
   if(flag)
   System.out.println("YES");
  }
 }
}

INPUT:


2
I am :IronnorI Ma, i
Ab?/Ba
OUTOUT:


YES
YES

Java Interview Questions - 9

Below are few java interview questions where candidate need to be more clear on basics and how it works when they asked simples questions. All these questions are programmatic questions and need to answer whether program will compile and run without any error and next what will be the out?


package com.pract;

import java.lang.reflect.Method;

class DeclaredMethodsPractBase {

 public void myParent1(){};
 protected void myParent2(){};
 private void myParent3(){};
}

public class DeclaredMethodsPract extends DeclaredMethodsPractBase{
 
 public void myChild11(){};
 protected void myChild12(){};
 private void myChild13(){};
 
 public static void main(String[] args) throws ClassNotFoundException {
  
  Class<?> classs = Class.forName("com.pract.DeclaredMethodsPract");
  
  Method[] methods = classs.getDeclaredMethods();
  
  for (Method method : methods) {
   System.out.print(method.getName() + ", ");
  }
 }
}

1. Runtime error
2. main, myChild11, myChild12, myChild13, myParent1,
3. main, myChild11, myChild12, myChild13, myParent1, myParent2,
4. main, myChild11, myChild12, myChild13, myParent1, myParent2, myParent3,



public class EnumPract {

 enum Numbers{ONE, TWO, THREE};
 
 public static void main(String[] args) {
  
  System.out.print((Numbers.ONE == Numbers.ONE) + ", ");
  System.out.print(Numbers.ONE.equals(Numbers.ONE));
 }
}

1. Compile time error
2. true, false
3. false, false
4. false, true
5. true, true



public class InternPract {

 public static void main(String[] args) {
  String a1 = "Java";
  String a2 = new String("Java");
  String a3 = a1.intern();
  
  System.out.print((a1 == a2) + ", "+(a1 == a3));
 } 
}

1. false, true
2. true, true
3. true, false
4. false, false



import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class MapObjectPract {

 public static void main(String[] args) {
  
  Map<String, String> map = new HashMap<String, String>();
  
  System.out.print((map instanceof Object) + ", ");
  System.out.print((map instanceof Map) + ", ");
  System.out.print((map instanceof HashMap) + ", ");
  System.out.print(map instanceof Collection);
 }
}

1. true, false, true, false
2. false, true, true, false
3. true, true, true, false
4. false, false, true, false



public class OperatorPract {

 public static void main(String[] args) {
  
  int i = 0;
  i = i++ + method(i);
  System.out.print(i);
 }
 
 static int method(int i){
  System.out.print(i+":");
  return 0;
 }
}

1. 1:0
2. 1:1
3. 0:1
4. 0:0



class Recursion{
 int method(int n){
  int result = method(n - 1);
  return result;
 }
}

public class RecuPract {

 public static void main(String[] args) {
  Recursion obj = new Recursion();
  int val = obj.method(10);
  System.out.println("completed : "+ val);
 }
}

1. completed : 0
2. compile time error
3. Runtime error
4. completed : -1



class Test implements Runnable{
 
 @Override
 public void run() {
  System.out.print("HELLO : "+Thread.currentThread().getName() + ", ");
 }
}

public class RunnablePract {

 public static void main(String[] args) {

  Test obj = new Test();
  
  Thread t1 = new Thread(obj, "T1");
  Thread t2 = new Thread(obj, "T2");
  
  t1.start();
  t1.join();
  t2.start();
 }
}

1. Runtime error
2. HELLO : T1, HELLO : T2,
3. HELLO : T2, HELLO : T1,
4. Compile time error



import java.util.HashSet;

public class SetPract {

 public static void main(String[] args) {
  
  HashSet<Integer> set = new HashSet<Integer>();
  for(int i=0;i<100;i++){
   set.add(i);
   set.remove(i - 1);
  }
  
  System.out.println("SET SIZE ::: "+set.size());
 }
}

1. SET SIZE ::: 100
2. SET SIZE ::: 1
3. SET SIZE ::: 99
4. SET SIZE ::: 0



public class StringArrayPract {

 private String[] array;
 
 public StringArrayPract() {
  array = new String[10];
 }
 
 public void setArray(String val, int i){
  array[i] = val;
 }
 
 public String getArray(int i){
  return array[i];
 }
 
 public static void main(String[] args) {
  
  StringArrayPract obj = new StringArrayPract();
  System.out.println("VALUE IS : "+obj.getArray(5));
 }
}

1. Runtime error
2. VALUE IS : null
3. Compile time error
5. VALUE IS :



import java.util.TreeSet;

public class TreeSetPract {

 public static void main(String[] args) {
  
  TreeSet<String> tSet = new TreeSet<String>();
  tSet.add("one");
  tSet.add("two");
  tSet.add("three");
  tSet.add("one");
  
  for (String string : tSet) {
   System.out.print(string+", ");
  }
 }
}

1. one, two, three,
2. one, two, three, one
3. one, one, three, two,
4. one, three, two, 

Java Interview Questions - 8

In our earlier tutorial we have seen lot of Java interview questions and sample programs. In this tutorial we see similar set of interview questions and answers.


What is the purpose of the System class?


Which TextComponent method is used to set a TextComponent to the read-only state?


How are the elements of a CardLayout organized?


Is &&= a valid Java operator?


Name the eight primitive Java types.


Java Interview Questions - 7

Which class should you use to obtain design information about an object?


What is the relationship between clipping and repainting?


Is "abc" a primitive value?


What is the relationship between an event-listener interface and an event-adapter class?


What restrictions are placed on the values of each case of a switch statement?


What modifiers may be used with an interface declaration?


Is a class a subclass of itself?


What is the highest-level event class of the event-delegation model?


What event results from the clicking of a button?


How can a GUI component handle its own events?


What is the difference between a while statement and a do statement?


How are the elements of a GridBagLayout organized?


What advantage do Java's layout managers provide over traditional windowing systems?


What is the Collection interface?


What modifiers can be used with a local inner class?


What is the difference between static and non-static variables?


What is the difference between the paint() and repaint() methods?


What is the purpose of the File class?


Can an exception be rethrown?


Which Math method is used to calculate the absolute value of a number?


How does multithreading take place on a computer with a single CPU?


When does the compiler supply a default constructor for a class?


When is the finally clause of a try-catch-finally statement executed?


Which class is the immediate superclass of the Container class?


If a method is declared as protected, where may the method be accessed?


How can the Checkbox class be used to create a radio button?


Which non-Unicode letter characters may be used as the first character of an identifier?


What restrictions are placed on method overloading?


What happens when you invoke a thread's interrupt method while it is sleeping or waiting?


What is casting?


What is the return type of a program's main() method?


Name four Container classes.


What is the difference between a Choice and a List?


What class of exceptions are generated by the Java run-time system?


What class allows you to read objects directly from a stream?


What is the difference between a field variable and a local variable?


Under what conditions is an object's finalize() method invoked by the garbage collector?


How are this() and super() used with constructors?


What is the relationship between a method's throws clause and the exceptions that can be thrown during the method's execution?


What is the difference between the JDK 1.02 event model and the event-delegation model introduced with JDK 1.1?


How is it possible for two String objects with identical values not to be equal under the == operator?


Why are the methods of the Math class static?


What Checkbox method allows you to tell if a Checkbox is checked?


What state is a thread in when it is executing?


What are the legal operands of the instanceof operator?


How are the elements of a GridLayout organized?


What an I/O filter?


If an object is garbage collected, can it become reachable again?


What is the Set interface?


What classes of exceptions may be thrown by a throw statement?


What are E and PI?


Are true and false keywords?


What is a void return type?


What is the purpose of the enableEvents() method?


What is the difference between the File and RandomAccessFile classes?


What happens when you add a double value to a String?


What is your platform's default character encoding?


Which package is always imported by default?


What interface must an object implement before it can be written to a stream as an object?


How are this and super used?


What is the purpose of garbage collection?


What is a compilation unit?


What interface is extended by AWT event listeners?


What restrictions are placed on method overriding?


How can a dead thread be restarted?


What happens if an exception is not caught?


What is a layout manager?


Which arithmetic operations can result in the throwing of an ArithmeticException?


What are three ways in which a thread can enter the waiting state?


Can an abstract class be final?


What is the ResourceBundle class?


What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?


What is numeric promotion?


What is the difference between a Scrollbar and a ScrollPane?


What is the difference between a public and a non-public class?


To what value is a variable of the boolean type automatically initialized?


Can try statements be nested?


What is the difference between the prefix and postfix forms of the ++ operator?


What is the purpose of a statement block?


What is a Java package and how is it used?


What modifiers may be used with a top-level class?


What are the Object and Class classes used for?


How does a try statement determine which catch clause should be used to handle an exception?


Can an unreachable object become reachable again?


When is an object subject to garbage collection?


What method must be implemented by all threads?


What methods are used to get and set the text label displayed by a Button object?


Which Component subclass is used for drawing and painting?


What are synchronized methods and synchronized statements?


What are the two basic ways in which classes that can be run as threads may be defined?


What are the problems faced by Java programmers who don't use layout managers?


What is the difference between an if statement and a switch statement?


What is the List interface?




Java Interview Questions - 7

In our earlier tutorial we have seen lot of Java interview questions and sample programs. In this tutorial we see similar set of interview questions and answers.

What state does a thread enter when it terminates its processing?


What is the Collections API?


Can a lock be acquired on a class?


What is the Vector class?


What modifiers may be used with an inner class that is a member of an outer class?


What is an Iterator interface?


What is the difference between the >> and >>> operators?


What's new with the stop(), suspend() and resume() methods in JDK 1.2?


Java Interview Questions - 7

Is null a keyword?


Which characters may be used as the second character of an identifier, but not as the first character of an identifier?


What is the List interface?


what is a transient variable?


which containers use a border Layout as their default layout?


Why do threads block on I/O?


How are Observer and Observable used?


What is synchronization and why is it important?


What is the preferred size of a component?


What method is used to specify a container's layout?


Which containers use a FlowLayout as their default layout?


How does Java handle integer overflows and underflows?


Which method of the Component class is used to set the position and size of a component?


How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?


What is the difference between yielding and sleeping?


Which java.util classes and interfaces support event handling?


Is sizeof a keyword?


What are wrapped classes?


Does garbage collection guarantee that a program will not run out of memory?


What restrictions are placed on the location of a package statement within a source code file?


Can an object's finalize() method be invoked while it is reachable?


What is the immediate superclass of the Applet class?


What is the difference between preemptive scheduling and time slicing?


Name three Component subclasses that support painting.


What value does readLine() return when it has reached the end of a file?


What is the immediate superclass of the Dialog class?


What is clipping?


What is a native method?


Can a for statement loop indefinitely?


What are order of precedence and associativity, and how are they used?


When a thread blocks on I/O, what state does it enter?


To what value is a variable of the String type automatically initialized?


What is the catch or declare rule for method declarations?


What is the difference between a MenuItem and a CheckboxMenuItem?


What is a task's priority and how is it used in scheduling?


What class is the top of the AWT event hierarchy?


When a thread is created and started, what is its initial state?


Can an anonymous class be declared as implementing an interface and extending a class?


What is the range of the short type?


What is the range of the char type?


In which package are most of the AWT events that support the event-delegation model defined?


What is the immediate superclass of Menu?


What is the purpose of finalization?


Which class is the immediate superclass of the MenuComponent class.


What invokes a thread's run() method?


What is the difference between the Boolean & operator and the && operator?


Name three subclasses of the Component class.


What is the GregorianCalendar class?


Which Container method is used to cause a container to be laid out and redisplayed?


What is the purpose of the Runtime class?


How many times may an object's finalize() method be invoked by the garbage collector?


What is the purpose of the finally clause of a try-catch-finally statement?


What is the argument type of a program's main() method?


Which Java operator is right associative?


What is the Locale class?


Can a double value be cast to a byte?


What is the difference between a break statement and a continue statement?


What must a class do to implement an interface?


What method is invoked to cause an object to begin executing as a separate thread?


Name two subclasses of the TextComponent class.


What is the advantage of the event-delegation model over the earlier event-inheritance model?


Which containers may have a MenuBar?


How are commas used in the initialization and iteration parts of a for statement?


What is the purpose of the wait(), notify(), and notifyAll() methods?


What is an abstract method?


How are Java source code files named?


What is the relationship between the Canvas class and the Graphics class?


What are the high-level thread states?


What value does read() return when it has reached the end of a file?


Can a Byte object be cast to a double value?


What is the difference between a static and a non-static inner class?


What is the difference between the String and StringBuffer classes?


If a variable is declared as private, where may the variable be accessed?


What is an object's lock and which object's have locks?


What is the Dictionary class?


How are the elements of a BorderLayout organized?


What is the % operator?


When can an object reference be cast to an interface reference?


What is the difference between a Window and a Frame?


Which class is extended by all other classes?


Can an object be garbage collected while it is still reachable?


Is the ternary operator written x : y ? z or x ? y : z ?


What is the difference between the Font and FontMetrics classes?


How is rounding performed under integer division?


What happens when a thread cannot acquire a lock on an object?


What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?


What classes of exceptions may be caught by a catch clause?


If a class is declared without any access modifiers, where may the class be accessed?


What is the SimpleTimeZone class?


What is the Map interface?


Does a class inherit the constructors of its superclass?


For which statements does it make sense to use a label?