Samsung Interview Question for Java Developers


Country: India




Comment hidden because of low score. Click to expand.
5
of 5 vote

String s = "What is the length";
                int i=0;
		try{	
			while(true)
			{
				s.charAt(i);
				i++;
			}
		}
		catch(StringIndexOutOfBoundsException e)
		{
			System.out.println("the length is " + i);
		}

- Swapnil April 29, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Basically, keep accessing the string till you get your first Out of Bound exception

- Swapnil April 29, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

the charAt() is in the string class. is it possible to find the length without using this method?

- Rasha April 29, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

You could always just cast the String to lower case, add an "A" to the end and then call indexOf, that would give you the length and no exception. source: coderanchdotcom

- gansai April 29, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Aren't you using the inbuilt method: charAt(i) ???

- Anonymous April 30, 2012 | Flag
Comment hidden because of low score. Click to expand.
3
of 3 vote

class test
{
public static void main(String[] args){
String str="A String";
char str1[]=str.toCharArray();
int i=0;
for(char s : str1){
i++;
}
System.out.println("Length =" + i);
}
}

- Anonymous April 30, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

i guess the question said that inbuilt string functions should not be used

- goutham467 April 30, 2012 | Flag
Comment hidden because of low score. Click to expand.
2
of 2 votes

Following code might help:

import java.lang.reflect.Field;
public class FindStringLength {

	public static void main(String[] args) {
		String s = "What is the length";
		Field value;
		try {
			value = String.class.getDeclaredField("value");
			value.setAccessible(true);
			int length = ((char[]) value.get(s)).length;
			System.out.println(length);
		} catch (NoSuchFieldException | SecurityException
				| IllegalArgumentException | IllegalAccessException e) {
			e.printStackTrace();
		}

	}

}

- Rashid May 25, 2012 | Flag
Comment hidden because of low score. Click to expand.
3
of 3 vote

String name="TestText";
		try {
			File rawfile=new File("filename");
			
			FileWriter file=new FileWriter(rawfile);
			file.write(name);
			file.close();
			
			FileReader reader=new FileReader(rawfile);
			int readByte=reader.read();

			int i=0;
			while(readByte!=-1)
			{i++;
				
			readByte=reader.read();
			}
			
			System.out.println("length is   :"+i);
	
		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

- Avijit May 29, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

You cannot solve this without invoking any method within String class. If that is a constraint, then pass the string as a jstring to a JNI method and then within that method do this:

const char* array = env->GetStringUTFChars(myString, 0);

Then inside your JNI method, count till you reach "\0".

- Ajith May 01, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

GetStringUTFChars would call built-in String methods though. So if that's allowed, why use JNI at all? Why not StringBuffer s = new StringBuffer(inputString); and then operations on that?

- eugene.yarovoi May 04, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Is java string doesn't end with '\0' ?

- Nitish April 29, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

no

- aaron liang September 16, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

I wasn't able to find the exact length or number of chars in the string but i found the approximate length withing range of 4 characters. Here is the code:

public class Sizeof
{
    public static void main (String [] args) throws Exception
    {
        // Warm up all classes/methods we will use
        runGC ();
        usedMemory ();
        // Array to keep strong references to allocated objects
        final int count = 100000;
        StringBuilder [] strings = new StringBuilder [count];
        
        long heap1 = 0;
        // Allocate count+1 objects, discard the first one
        for (int i = -1; i < count; ++ i)
        {
            StringBuilder string = null;
            
            // Instantiate your data here and assign it to object
            /*
             * 64-> 1-2 , 72 -> 3-6 , 80 -> 7-10 , 88 -> 11-14
             */
            string = new StringBuilder ("12345671234"); 
            
            if (i >= 0)
            	strings [i] = string;
            else
            {
            	string = null; // Discard the warm up object
                runGC ();
                heap1 = usedMemory (); // Take a before heap snapshot
            }
        }
        runGC ();
        long heap2 = usedMemory (); // Take an after heap snapshot:
        
        final int size = Math.round (((float)(heap2 - heap1))/count);
        System.out.println ("'before' heap: " + heap1 +
                            ", 'after' heap: " + heap2);
        System.out.println ("heap delta: " + (heap2 - heap1) +
            ", {" + strings [0].getClass () + "} size = " + size + " bytes");
        int lower=3 ; int upper = 6; int increment=0; 
        if(size==64) {System.out.println("Num of char= 1 or 2");}
        else if(size==72) {System.out.println("Num of char= 3 to 6");}
        else {increment=((size-72)/8)*4;   System.out.println("Num of char= "+""+ (lower+increment) +" to "+""+(upper+increment));}
        
        for (int i = 0; i < count; ++ i) strings [i] = null;
        strings = null;
    }
    private static void runGC () throws Exception
    {
        // It helps to call Runtime.gc()
        // using several method calls:
        for (int r = 0; r < 4; ++ r) _runGC ();
    }
    private static void _runGC () throws Exception
    {
        long usedMem1 = usedMemory (), usedMem2 = Long.MAX_VALUE;
        for (int i = 0; (usedMem1 < usedMem2) && (i < 500); ++ i)
        {
            s_runtime.runFinalization ();
            s_runtime.gc ();
            Thread.currentThread ().yield ();
            
            usedMem2 = usedMem1;
            usedMem1 = usedMemory ();
        }
    }
    private static long usedMemory ()
    {
        return s_runtime.totalMemory () - s_runtime.freeMemory ();
    }
    
    private static final Runtime s_runtime = Runtime.getRuntime ();
} // End of class

- praveenkcs28 January 30, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

String name="kiran";
		int i=0;
		for(char c:name.toCharArray())
		{
			i++;
		}
		System.out.println("The lenght of a String is "+i);

- Gangii87 October 04, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

and

- Anonymous September 17, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

and

- fgh September 17, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

and

- fgh September 17, 2014 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More