Samsung Interview Question
Java DevelopersCountry: India
the charAt() is in the string class. is it possible to find the length without using this method?
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
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);
}
}
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();
}
}
}
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();
}
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".
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
- Swapnil April 29, 2012