Citigroup Interview Question
Java DevelopersCountry: India
My try in Java
public class StrLen {
public static void main(String[] args) {
System.out.println(strlen("abcde"));
}
static int strlen(String str) {
if (str != null) {
for(int len = 0;; len++) {
try {
str.charAt(len);
}
catch (IndexOutOfBoundsException e) {
return len;
}
}
}
return 0;
}
}
/**
* How could you make sure that thread A ,B and C run sequentially without using join method?
*
* @author manoj.sharma
* @source Barclays
*/
public class ThreadJoiningWithoutJoin {
public static void main(String[] args) {
final JoinTask task = new JoinTask();
Thread A = new Thread(){
public void run(){
task.doJob(1, "JOB A DONE...");
}
};
Thread B = new Thread(){
public void run(){
task.doJob(2, "JOB B DONE...");
}
};
Thread C = new Thread(){
public void run(){
task.doJob(3, "JOB C DONE...");
}
};
C.start();
B.start();
A.start();
}
}
// Shared Class or Object
class JoinTask {
private int currentRank = 1;
public void doJob(int rank, String msg) {
synchronized(this) {
while (rank != currentRank) {
try {wait();}catch(InterruptedException ex) {ex.printStackTrace();};
}
System.out.println("Job:" + currentRank + " : " + msg );
currentRank++;
notifyAll();
}
}
}
It does not need to check all positions.
Check char at position 2 then 4 then 8 and so on until caught exception.
public static int len(String str){
if(str==null)
return 0;
else{
int index=2;
try {
while (true){
str.charAt(index);
index *= 2;
}
} catch (IndexOutOfBoundsException e) {
return checkSize(str,index/2,index);
}
}
}
then call recursive method which returns the position of last char.
public static int checkSize(String str, int l, int r){
if(l+1==r)
return r;
else {
int index=(l+r)/2;
try{
str.charAt(index);
return checkSize(str,index,r);
}
catch (IndexOutOfBoundsException e) {
return checkSize(str,l,index);
}
}
}
public class StringTest {
public static void main(String args[]){
String s = new String("test213");
try {
int count = (Integer)getFieldValue(s, "count");
int offset = (Integer)getFieldValue(s, "offset");
System.out.println("Size :"+(count-offset));
} catch (Exception e) {
e.printStackTrace();
}
}
static Object getFieldValue(String s,String fieldName) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Object chars = null;
Field fieldValue = String.class.getDeclaredField(fieldName);
fieldValue.setAccessible(true);
chars = fieldValue.get(s);
return chars;
}
}
Use Reflection to get values of count and offset.
You can read bytes from String. It will return byte array. Now you can get the length of it, which is length of String.
Source code is given below :
public int getSize(String str) {
byte[] arr = str.getBytes();
int length = arr.length;
System.out.println("Length = " + length);
return length;
}
- Anonymous October 17, 2013