Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

Java technical test

  • 17-03-2014 6:08pm
    #1
    Registered Users, Registered Users 2 Posts: 9,153 ✭✭✭


    Hey I know these threads come up quite frequently basically I have a tecnical test with IBM without any real idea what to expect.

    To be honest what has made it worse is that the manager I did the first interview laughed at how easy it was and assured me if be fine, then the HR lady said it was never something anyone complained about but I really have no idea where to review/practice and now I'm worried I'll make an eijet of myself.

    So I thought a thread on technical questions might come in handy for people to practice before going into interviews.

    So no answers unless someone is stuck but previous questions I have encountered are.

    Q1
    How to tell if a binary is a palindrom.

    Q2
    Given two lists List all the unique words which occur in each list and if a word occurs multiple times show it multiple times. (This was badly phrased when I got it so I'm going to show some examples to explain)

    L1=Tom,Tom,Tom,John
    L2=Tom,john, mike,Rob
    Combined list = Tom,Tom, Mike, Rob

    Also any advice for my own test let me know.


Comments

  • Registered Users, Registered Users 2 Posts: 159 ✭✭magooly


    Core Java Interview Questions(100)


    1 Q Why threads block or enters to waiting state on I/O?
    A Threads enters to waiting state or block on I/O because other threads can execute while the I/O operations are performed.

    2 Q What are transient variables in java?
    A Transient variables are variable that cannot be serialized.

    3 Q How Observer and Observable are used?
    A Subclass of Observable class maintain a list of observers. Whenever an Observable object is updated, it invokes the update() method of each of its observers to notify the observers that it has a changed state. An observer is any object that implements the interface Observer.

    4 Q What is synchronization
    A Synchronization is the ability to control the access of multiple threads to shared resources. Synchronization stops multithreading. With synchronization , at a time only one thread will be able to access a shared resource.

    5 Q What is List interface ?
    A List is an ordered collection of objects.

    6 Q What is a Vector
    A Vector is a grow able array of objects.

    7 Q What is the difference between yield() and sleep()?
    A When a object invokes yield() it returns to ready state. But when an object invokes sleep() method enters to not ready state.

    8 Q What are Wrapper Classes ?
    A They are wrappers to primitive data types. They allow us to access primitives as objects.

    9 Q Can we call finalize() method ?
    A Yes. Nobody will stop us to call any method , if it is accessible in our class. But a garbage collector cannot call an object's finalize method if that object is reachable.

    10 Q What is the difference between time slicing and preemptive scheduling ?
    A In preemptive scheduling, highest priority task continues execution till it enters a not running state or a higher priority task comes into existence. In time slicing, the task continues its execution for a predefined period of time and reenters the pool of ready tasks.

    11 Q What is the initial state of a thread when it is created and started?
    A The thread is in ready state.

    12 Q Can we declare an anonymous class as both extending a class and implementing an interface?
    A No. An anonymous class can extend a class or implement an interface, but it cannot be declared to do both

    13 Q What are the differences between boolean & operator and & operator
    A When an expression containing the & operator is evaluated, both operands are evaluated. And the & operator is applied to the operand. When an expression containing && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then only the second operand is evaluated otherwise the second part will not get executed. && is also called short cut and.

    14 Q What is the use of the finally block?
    A Finally is the block of code that executes always. The code in finally block will execute even if an exception is occurred. finally will not execute when the user calls System.exit().

    15 Q What is an abstract method ?
    A An abstract method is a method that don't have a body. It is declared with modifier abstract.


    16 Q what is a the difference between System.err and System.out
    A We can redirect System.out to another file but we cannot redirect System.err stream

    17 Q What are the differences between an abstract class and an interface?
    A An abstract class can have concrete method, which is not allowed in an interface. Abstract class can have private or protected methods and variables and only public methods and variables are allowed in interface. We can implement more than one interface , but we can extend only one abstract class. Interfaces provides loose coupling where as abstract class provides tight coupling.

    18 Q What is the difference between synchronized block and synchronized method ?
    A Synchronized blocks place locks for the specified block where as synchronized methods place locks for the entire method.

    19 Q How can you force garbage collection in java?
    A You cannot force Garbage Collection, but you can request for it by calling the method System.gc(). But it doesn't mean that Garbage Collection will start immediately. The garbage collection is a low priority thread of JVM.

    20 Q How can you call a constructor from another constructor ?
    A By using this() reference.

    21 Q How can you call the constructor of super class ?
    A By using super() syntax.

    22 Q What's the difference between normal methods and constructors?
    A Constructors must have the same name of the class and can not have a return type. They are called only once, while regular methods can be called whenever required. We cannot explicitly call a constructor.

    23 Q What is the use of packages in java ?
    A Packages are a way to organize files in java when a project consists of more than one module. It helps in resolving name conflicts when different modules have classes with the same names.

    24 Q What must be the order of catch blocks when catching more than one exception?
    A The sub classes must come first. Otherwise it will give a compile time error.

    25 Q How can we call a method or variable of the super class from child class ?
    A We can use super.method() or super.variable syntax for this purpose.

    26 Q If you are overriding equals() method of a class, what other methods you might need to override ?
    A hashCode

    27 Q How can you create your own exception ?
    A Our class must extend either Exception or its sub class

    28 Q What is serialization ?
    A Serialization is the process of saving the state of an object.

    29 Q What is de-serialization?
    A De-serialization is the process of restoring the state of an object.

    30 Q What is externalizable ?
    A It is an interface that extends Serializable. It is having two different methods writeExternal() and readExternal. This interface allows us to customize the output.

    31 Q Does garbage collection guarantee that a program will not run out of memory?
    A Garbage collection does not guarantee that a program will not run out of memory. It is also possible for programs to create objects that are not subject to garbage collection. And there is no guarantee that Garbage Collection thread will be executed.

    32 Q What is a native method?
    A

    A native method is a method that is implemented in a language other than Java.

    33 Q What are different type of exceptions in Java?
    A There are two types of exceptions in java. Checked exceptions and Unchecked exceptions. Any exception that is is derived from Throwable and Exception is called checked exception except RuntimeException and its sub classes. The compiler will check whether the exception is caught or not at compile time. We need to catch the checked exception or declare in the throws clause. Any exception that is derived from Error and RuntimeException is called unchecked exception. We don't need to explicitly catch a unchecked exception.
    34 Q Can we catch an error in our java program ?
    A Yes. We can . We can catch anything that is derived from Throwable. Since Error is a sub class of Throwable we can catch an error also.

    35 Q What is thread priority?
    A Thread Priority is an integer value that identifies the relative order in which it should be executed with respect to others. The thread priority values ranging from 1- 10 and the default value is 5. But if a thread have higher priority doesn't means that it will execute first. The thread scheduling depends on the OS.

    36 Q How many times may an object's finalize() method be invoked by the garbage collector?
    A Only once.

    37 Q What is the difference between a continue statement and a break statement?
    A

    Break statement results in the immediate termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement.

    38 Q What must a class do to implement an interface?
    A

    It must identify the interface in its implements clause. Also it must provide definition for all the methods in the interface otherwise it must be declared abstract.

    39 Q What is an abstract class?
    A An abstract class is an incomplete class. It is declared with the modifier abstract. We cannot create objects of the abstract class. It is used to specify a common behavioral protocol for all its child classes.

    40 Q What is the difference between notify and notifyAll method ?
    A notify wakes up a single thread that is waiting for object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. notifyAll Wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods.

    41 Q What does wait method do ?
    A It causes current thread to wait until either another thread invokes notify or notifyAll method of the current object, or a specified amount of time has elapsed.

    42 Q What are the different states of a thread ?
    A The different thread states are ready, running, waiting and dead.

    43 Q What is the difference between static and non static inner class ?
    A A non-static inner class can have an object instances that are associated with instances of the class's outer class. A static inner class can not have any object instances.

    44 Q What is the difference between String and StringBuffer class ?
    A Strings are immutable (constant), their values cannot be changed after they are created. StringBuffer supports mutable objects.

    45 Q Which is the base class for all classes ?
    A java.lang.Object.

    46 Q What is the difference between readers and streams?
    A

    Readers are character oriented where streams are byte oriented. The readers are having full support for Unicode data.

    47 Q What is constructor chaining ?
    A When a constructor of a class is executed it will automatically call the default constructor of the super class (if no explicit call to any of the super class constructor) till the root of the hierarchy.

    48 Q What are the different primitive data type in java ?
    A There are 8 primitive types in java. boolean , char, byte, short, int long, float, double.

    49 Q What is static ?
    A static means one per class. static variables are created when the class loads. They are associated with the class. In order to access a static we don't need objects. We can directly access static methods and variable by calling classname.variablename.

    50 Q Why we cannot override static methods?
    A Static means they are associated with a class. In static methods , the binding mechanism is static binding. So it must be available at the compile time.

    51 Q What is the difference between static and non static variables ?
    A A static variable is associated with the class as a whole rather than with specific instances of a class. There will be only one value for static variable for all instances of that class. Non-static variables take on unique values with each object instance.

    52 Q When does a compiler supplies a default constructor for a class?
    A If there is no other constructor exist in a class, the compiler will supply a default constructor.

    53 Q What are the restrictions placed on overriding a method ?
    A The overridden method have the exact signature of the super class method, including the return type. The access specified cannot be less restrictive than the super class method. We cannot throw any new exceptions in overridden method.

    54 Q What are the restrictions placed on overloading a method ?
    A Overloading methods must differ in their parameter list, or number of parameters.

    55 Q What is casting ?
    A

    Casting means converting one type to another. There are mainly two types of casting. Casting between primitive types and casting between object references. Casting between primitive numeric types is used to convert larger data types to smaller data types. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.

    56 Q What is the difference between == and equals ?
    A The equals method can be considered to perform a deep comparison of the value of an object, whereas the == operator performs a shallow comparison. If we are not overriding the equals method both will give the same result. == will is used to compare the object references. It is used to check whether two objects are points to the same reference.

    57 Q What is a void return type ?
    A A void indicates that the method will not return anything.

    58 Q What will happen if an exception is not caught ?
    A An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup, which results in the termination of the program.

    59 Q What are the different ways in which a thread can enter into waiting state?
    A There are three ways for a thread to enter into waiting state. By invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method.

    60 Q What is a ResourceBundle class?
    A The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to create the program's appearance to the particular locale in which it is being run.


    61 Q What is numeric promotion?
    A Numeric promotion is the conversion of a smaller numeric type to a larger numeric type. In numerical promotion, byte, char, and short values are converted to int values. The int, long and float values are converted to the desired types if required.

    62 Q What is the difference between the prefix and postfix forms of the ++ operator?
    A The prefix form first performs the increment operation and then returns the value of the increment operation. The postfix form first returns the current value of the expression and then performs the increment operation on that value.

    63 Q What are synchronized methods and synchronized statements?
    A Synchronized methods are methods that are declared with the keyword synchronized. A thread executes a synchronized method only after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. It is a block of code declared with synchronized keyword. A synchronized statement can be executed only after a thread has acquired the lock for the object or class referenced in the synchronized statement.

    64 Q How can we create a thread?
    A A thread can be created by extending Thread class or by implementing Runnable interface. Then we need to override the method public void run().

    65 Q What is the difference between a switch statement and an if statement?
    A If statement is used to select from two alternatives. It uses a boolean expression to decide which alternative should be executed. The expression in if must be a boolean value. The switch statement is used to select from multiple alternatives. The case values must be promoted to an to int value.

    66 Q What is hashCode?
    A The hashcode of a Java Object is simply a number (32-bit signed int) that allows an object to be managed by a hash-based data structure. A hashcode should be, equal for equal object (this is mandatory!) , fast to compute based on all or most of the internal state of an object, use all or most of the space of 32-bit integers in a fairly uniform way , and likely to be different even for objects that are very similar. If you are overriding hashCode you need to override equals method also.

    67 Q What is an I/O filter?
    A An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.

    68 Q What is the difference between RandomAccessFile and File?
    A The File class contains information the files and directories of the local file system. The RandomAccessFile class contains the methods needed to directly access data contained in any part of a file.

    69 Q What is final ?
    A A final is a keyword in java. If final keyword is applied to a variable, then the variable will become a constant. If it applied to method, sub classes cannot override the method. If final keyword is applied to a class we cannot extend from that class.

    70 Q What is the difference among JVM Spec, JVM Implementation, JVM Runtime ?
    A The JVM spec is the blueprint for the JVM generated and owned by Sun. The JVM implementation is the actual implementation of the spec by a vendor and the JVM runtime is the actual running instance of a JVM implementation

    71 Q How is the difference between thread and process?
    A

    A process runs in its own address space. No two processes share their address space. Threads will run in the same address space of the process that owns them.

    72 Q What is the difference between Vector and ArrayList ?
    A

    Vector is synchronized, ArrayList is not. Vector is having a constructor to specify the incremental capacity. But ArrayList don't have. By default Vector grows by 100% but ArrayList grows by 50% only.

    73 Q What is the difference between Hashtable and HashMap ?
    A Hashtable is synchronized . but HashMap is not synchronized. Hashtable does not allow null values , but HashMap allows null values.

    74 Q What are the access modifiers available in Java.
    A Access modifier specify where a method or attribute can be used. Public is accessible from anywhere. Protected is accessible from the same class and its subclasses. Package/Default are accessible from the same package. Private is only accessible from within the class.

    75 Q Why java is said to be pass-by-value ?
    A When assigning an object to a variable, we are actually assigning the memory address of that object to the variable. So the value passed is actually the memory location of the object. This results in object aliasing, meaning you can have many variables referring to the same object on the heap.

    76 Q What do you mean by immutable ? How to create an immutable object ?
    A Immutability means an object cannot be modified after it has been initialized. There will not be any setter methods in an immutable class. And normally these classes will be final.

    77 Q What is class loader in java ?
    A A class loader is a class that is responsible for loading the class. All JVM contains one class loader called primordial class loader.

    78 Q What is a weak reference ?
    A A weak reference is the one that does nor prevent the referenced object from being garbage collected. The weak reference will not keep the object that it refers to alive. A weak reference is not counted as a reference in garbage collection. This will make the memory use more effective.

    79 Q What is object cloning?
    A It is the process of duplicating an object so that two identical objects will exist in the memory at the same time.

    80 Q What is object pooling?
    A Creating a large number of identical short lived objects is called object pooling. This helps to minimize the need of garbage collection and makes the memory use more effective.

    81 Q What is garbage collection?
    A

    Garbage collection is the process of releasing memory used by unreferenced objects. It relieves the programmer from the process of manually releasing the memory used by objects .

    82 Q What is the disadvantage of garbage collection?
    A It adds an overhead that can affect performance. Additionally there is no guarantee that the object will be garbage collected.

    83 Q What is a Dictionary?
    A Dictionary is a parent class for any class that maps keys to values., In a dictionary every key is associated with at most one value.

    84 Q What is JAR file ?
    A JAR stands for Java Archive. This is a file format that enables you to bundle multiple files into a single archive file. A jar file will contains a manifest.mf file inside META-INF folder that describes the version and other features of jar file.

    85 Q Why Java is not fully objective oriented ?
    A Due to the use of primitives in java, which are not objects.

    86 Q What is a marker interface ?
    A An interface that contains no methods. Eg: Serializable, Cloneable, SingleThreadModel etc. It is used to just mark java classes that support certain capability.

    87 Q What are tag interfaces?
    A Tag interface is an alternate name for marker interface.

    88 Q What are the restrictions placed on static method ?
    A We cannot override static methods. We cannot access any object variables inside static method. Also the this reference also not available in static methods.

    89 Q What is JVM?
    A JVM stands for Java Virtual Machine. It is the run time for java programs. All are java programs are running inside this JVM only. It converts java byte code to OS specific commands. In addition to governing the execution of an application's byte codes, the virtual machine handles related tasks such as managing the system's memory, providing security against malicious code, and managing multiple threads of program execution.

    90 Q What is JIT?
    A JIT stands for Just In Time compiler. It compiles java byte code to native code.

    91. What is java byte code?
    Byte code is an sort of intermediate code. The byte code is processed by virtual machine.

    92. What is method overloading?
    Method overloading is the process of creating a new method with the same name and different signature.

    93. What is method overriding?
    Method overriding is the process of giving a new definition for an existing method in its child class.

    94. What is finalize() ?
    Finalize is a protected method in java. When the garbage collector is executes , it will first call finalize( ), and on the next garbage-collection it reclaim the objects memory. So finalize( ), gives you the chance to perform some cleanup operation at the time of garbage collection.

    95. What is multi-threading?
    Multi-threading is the scenario where more than one threads are running.

    96. What is deadlock?
    Deadlock is a situation when two threads are waiting on each other to release a resource. Each thread waiting for a resource which is held by the other waiting thread.

    97. What is the difference between Iterator and Enumeration?
    Iterator differ from enumeration in two ways Iterator allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. And , method names have been improved.

    98. What is the Locale class?
    A Locale object represents a specific geographical, political, or cultural region

    99. What is internationalization?
    Internationalization is the process of designing an application so that it can be adapted to various languages and regions without changes.

    100. What is anonymous class ?
    An anonymous class is a type of inner class that don’t have any name.

    101. What is the difference between URL and URLConnection?
    A URL represents the location of a resource, and a URLConnection represents a link for accessing or communicating with the resource at the location.

    102. What are the two important TCP Socket classes?
    ServerSocket and Socket. ServerSocket is useful for two-way socket communication. Socket class help us to read and write through the sockets. getInputStream() and getOutputStream() are the two methods available in Socket class.

    103. Strings are immutable. But String s=”Hello”; String s1=s+”World” returns HelloWorld how ?
    Here actually a new object is created with the value of HelloWorld

    104. What is classpath?
    Classpath is the path where Java looks for loading class at run time and compile time.

    105. What is path?
    It is an the location where the OS will look for finding out the executable files and commands.


  • Moderators, Sports Moderators, Regional Abroad Moderators Posts: 2,666 Mod ✭✭✭✭TrueDub


    magooly wrote: »
    Core Java Interview Questions(100)
    <snipped enormous list of questions>

    That's a good list, but it's not what the OP asked about, he was wondering about technical tests.

    OP, what's usually being looked for here is your ability to reason your way through a problem, and translate that reasoning into code. They will be looking for correct use of control constructs and possibly stuff like recursion.


  • Registered Users, Registered Users 2 Posts: 9,153 ✭✭✭everdead.ie


    So the plan was I was going to update this with some technical questions from the interview but it wasn't at all as described nothing written did a white board session on java and sql went through designing and what java api's I would use to implement stuff like that.

    All went well and offered the job a few days later.....


  • Registered Users, Registered Users 2 Posts: 4 schokea


    Can you please post some of the whiteboard and SQL questions if you remember them :)


  • Registered Users, Registered Users 2 Posts: 851 ✭✭✭TonyStark


    Write a function to find the maximum of two numbers. You are not permitted to use the IF construct.


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 9,153 ✭✭✭everdead.ie


    schokea wrote: »
    Can you please post some of the whiteboard and SQL questions if you remember them :)
    I can't really give you specifics because they were aimed at my own experience how I had used sql to solve problems in work, creating tables, inserting etc.

    The Design session was also based around my work I had made an app and they asked me to show a design on how you interacted with it how I would improve it now, how I would scale it up.


    That's all I can remember the whole thing was a blur but they were lovely and easy to deal with.


  • Registered Users, Registered Users 2 Posts: 2,021 ✭✭✭ChRoMe


    TonyStark wrote: »
    You are not permitted to use the IF construct.

    I hate those sort of bull**** questions.


  • Registered Users, Registered Users 2 Posts: 4 schokea


    ChRoMe wrote: »
    I hate those sort of bull**** questions.

    Ye they are crap but I suppose every decent developer should know about the ternary operator:

    max = (a > b) ? a : b;

    but after reading this question I googled about a bit and found that the Java math library has a max() that does this for you:

    Math.max(10,20); returns 20


  • Registered Users, Registered Users 2 Posts: 40,038 ✭✭✭✭Sparks


    schokea wrote: »
    Ye they are crap but I suppose every decent developer should know about the ternary operator:
    max = (a > b) ? a : b;
    but after reading this question I googled about a bit and found that the Java math library has a max() that does this for you:
    Math.max(10,20); returns 20

    So help me, if the crowd I was interviewing for accepted either of those answers, I'd have to think long and hard about working there.
    What exactly do you think the ternary operator and the max() functions are under the hood but if statements? So either they just mean don't use the if keyword in which case, that's a really horrible test and indicates a level of competence that hints to long nights fixing stupid mistakes; or they really mean don't use comparisons at all, which is a bitch of a question.

    First way I can think of if it's the latter demonstrates how ugly a question it is (I'll do it for chars here in C so it's more obvious):
    #include <stdio.h>
    
    unsigned char max(unsigned char a, unsigned char b) {
       unsigned char answer[65536];
       int answerIndex = 0;
       for (int i = 0; i<=255; i++) {
          for (int j = 0; j<=255; j++) {
             /* this is setup, so using if here isn't 
              * cheating because we could just enter 
              * all this by hand... ewww */
             answer[i<<8|j] = i > j ? i : j; 
          }
       }
    
       /*  here's the real max function */
       answerIndex = a << 8 | b;
       return answer[answerIndex];
       /*  good programmers should now feel the need for a shower */
    }
    
    int main () {
       printf ("max (128,255) = %i\n", max(128,255));
       return(0);
    }
    

    Nasty. In my defence, it's late and I'm tired :D If I was running a tech interview and someone came up with that answer to that question but said it was messy, I'd pass them because interviews are stressful, but I'd send it back if it showed up in a code review in day-to-day work as being too mucky.

    There is a much, much cleaner way if you bittwiddle, because signed ints will be in two's complement format on pretty much every machine I can think of so you can check the sign without doing comparisons something like this:
    int diff = a - b;
    int complement = (diff >> 31) & 0x01;
    int max = a - k * diff;
    
    So you're grabbing the two's complement bit of diff with the shifting there (we're assuming 32 bit ints, but that's a reasonably safe bet in modern C/C++) (and really the masking shouldn't be needed, I just have really old habits :D ), and it'll be either 0 or 1 so k*diff will be 0 if a > b and it'll be equal to a - b if a < b; therefore max is either just a (if a > b) or a - (a - b) which is just b, if a < b.

    Here's the thing. That's a nice question if you want someone who can do low-level bit-twiddling in C or C++, but the whole point of languages like Java was to get the hell away from that kind of thing. So it's still a stupid Java question. You might as well ask someone to write an associative array in python from scratch instead of using dictionaries.


  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,110 Mod ✭✭✭✭Tar.Aldarion


    I went for an android interview, 3rd and final round. The whole test was in C/++ and was got to do with "do this without using inbuilt functions and bonus marks for the more shifting of bits you do". At no stage in the interviews was anything java or android really asked about, an odd question here and there. It was disgusting, and they were offering 20k.

    The whole point is that I'm abstracted from that stuff, waste of time, and I had no idea how to do anything with bit shifting anyway. It would take me a good while to even follow the logic in Sparks post :D


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 27,370 ✭✭✭✭GreeBo


    Sparks wrote: »
    Here's the thing. That's a nice question if you want someone who can do low-level bit-twiddling in C or C++, but the whole point of languages like Java was to get the hell away from that kind of thing. So it's still a stupid Java question. You might as well ask someone to write an associative array in python from scratch instead of using dictionaries.


    There are other approaches though, stick them into a sortable collection, sort and then pick the first (or last) element depending on the sort order for example.

    I'd use the question to see if someone can come up with imaginative solutions that others can understand, not low-level crap that the next guy is going to have to google to understand before he can attempt to make a change.


  • Registered Users, Registered Users 2 Posts: 40,038 ✭✭✭✭Sparks


    GreeBo wrote: »
    There are other approaches though, stick them into a sortable collection, sort and then pick the first (or last) element depending on the sort order for example.
    That's cheating :) The non-cheating answer to the harder version of the question kindof means that if you checked the assembly, there'd be no conditionals in there. C'mon, play the game, it's fun :D
    I'd use the question to see if someone can come up with imaginative solutions that others can understand, not low-level crap that the next guy is going to have to google to understand before he can attempt to make a change.
    That's why it's such an awful question for a language like Java (but actually, kindof a good question if bittwiddling is going to be a thing in the job).

    And if you've been coding for a while now, you know all these things aren't wierd or exotic, they were commonplace a decade or two ago, and still are in some areas of coding at low level or in places where really high performance is a factor. There are whole lists of them (this one looks new but it's just been reformatted from the version I first saw in 1993, and it was very old then; and there's also hakmemc and the famous Graphics Gems collections) and people used to read those lists quite a lot.

    So for low-level stuff, this is actually okay (but if the applicant is stressed, it could go horribly wrong) - the problem is that it's a horrible high-level question and shouldn't be on a java test at all.


  • Registered Users, Registered Users 2 Posts: 40,038 ✭✭✭✭Sparks


    It would take me a good while to even follow the logic in Sparks post :D
    No it wouldn't, if you weren't at work and weren't distracted, you wouldn't even get through a cup of coffee in the time it took to grok it.

    You want something hard to follow at that level, go look up John Caramack's inverse square estimation routine in the original Quake engine code:
    float InvSqrt(float x){
       float xhalf = 0.5f * x;
       int i = *(int*)&x; // store floating-point bits in integer
       i = 0x5f3759d5 - (i >> 1); // initial guess for Newton's method
       x = *(float*)&i; // convert new bits into float
       x = x*(1.5f - xhalf*x*x); // One round of Newton's method
       return x;
    }
    

    There's an entire academic paper written about that one :D
    (Well, okay, the paper is mainly about the choice of 0x5f3759d5 as the magic number in there, but it's still shiny).


  • Registered Users, Registered Users 2 Posts: 9,153 ✭✭✭everdead.ie


    Sparks wrote: »
    So help me, if the crowd I was interviewing for accepted either of those answers, I'd have to think long and hard about working there.
    What exactly do you think the ternary operator and the max() functions are under the hood but if statements? So either they just mean don't use the if keyword in which case, that's a really horrible test and indicates a level of competence that hints to long nights fixing stupid mistakes; or they really mean don't use comparisons at all, which is a bitch of a question.

    First way I can think of if it's the latter demonstrates how ugly a question it is (I'll do it for chars here in C so it's more obvious):
    #include <stdio.h>
    
    unsigned char max(unsigned char a, unsigned char b) {
       unsigned char answer[65536];
       int answerIndex = 0;
       for (int i = 0; i<=255; i++) {
          for (int j = 0; j<=255; j++) {
             /* this is setup, so using if here isn't 
              * cheating because we could just enter 
              * all this by hand... ewww */
             answer[i<<8|j] = i > j ? i : j; 
          }
       }
    
       /*  here's the real max function */
       answerIndex = a << 8 | b;
       return answer[answerIndex];
       /*  good programmers should now feel the need for a shower */
    }
    
    int main () {
       printf ("max (128,255) = %i\n", max(128,255));
       return(0);
    }
    
    Nasty. In my defence, it's late and I'm tired :D If I was running a tech interview and someone came up with that answer to that question but said it was messy, I'd pass them because interviews are stressful, but I'd send it back if it showed up in a code review in day-to-day work as being too mucky.

    There is a much, much cleaner way if you bittwiddle, because signed ints will be in two's complement format on pretty much every machine I can think of so you can check the sign without doing comparisons something like this:
    int diff = a - b;
    int complement = (diff >> 31) & 0x01;
    int max = a - k * diff;
    
    So you're grabbing the two's complement bit of diff with the shifting there (we're assuming 32 bit ints, but that's a reasonably safe bet in modern C/C++) (and really the masking shouldn't be needed, I just have really old habits :D ), and it'll be either 0 or 1 so k*diff will be 0 if a > b and it'll be equal to a - b if a < b; therefore max is either just a (if a > b) or a - (a - b) which is just b, if a < b.

    Here's the thing. That's a nice question if you want someone who can do low-level bit-twiddling in C or C++, but the whole point of languages like Java was to get the hell away from that kind of thing. So it's still a stupid Java question. You might as well ask someone to write an associative array in python from scratch instead of using dictionaries.
    Hmm I'm guessing they would frown on it but below is a really simple way to do it in java.
    Actually I'd say they'd ask for another way as well.
    public int getMaxWithNoIFWhile(int a, int b) {
    
    while(a>b) {
    return a;
    }
    return b;
    }
    
    
    public int getMaxWithNoIFFor(int a, int b) {
    
    for(int i;a>b;i++) {
    return a;
    }
    return b;
    }
    


  • Registered Users, Registered Users 2 Posts: 40,038 ✭✭✭✭Sparks


    Yeah, that's still cheating, you're still using conditionals hidden in the while and for loops ;):D


  • Registered Users, Registered Users 2 Posts: 9,153 ✭✭✭everdead.ie


    Sparks wrote: »
    Yeah, that's still cheating, you're still using conditionals hidden in the while and for loops ;):D
    Ya that's true I'm trying to see if there is another way can't think of any other off the top of my head.


  • Registered Users, Registered Users 2 Posts: 40,038 ✭✭✭✭Sparks


    There's probably another bittwiddling way to do it, and you could do a version of the disgusting lookup table solution that's even worse (instead of using it as a lookup table, use it as a jump table where you goto the address in the lookup table and either land at a return(a) or return(b) statement), but even I won't code that :D

    Thing is, there aren't that many ways to do stuff this low-down, which is yet another strike against this as an interview question...


  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,110 Mod ✭✭✭✭Tar.Aldarion


    Sparks wrote: »
    No it wouldn't, if you weren't at work and weren't distracted, you wouldn't even get through a cup of coffee in the time it took to grok it.

    You want something hard to follow at that level, go look up John Caramack's inverse square estimation routine in the original Quake engine code:
    float InvSqrt(float x){
       float xhalf = 0.5f * x;
       int i = *(int*)&x; // store floating-point bits in integer
       i = 0x5f3759d5 - (i >> 1); // initial guess for Newton's method
       x = *(float*)&i; // convert new bits into float
       x = x*(1.5f - xhalf*x*x); // One round of Newton's method
       return x;
    }
    

    There's an entire academic paper written about that one :D
    (Well, okay, the paper is mainly about the choice of 0x5f3759d5 as the magic number in there, but it's still shiny).
    Gonna have a read of that cheers, I love reading the work of FBs newest employees anyway :D

    Distracted is right, all of our products now echo my name to the screen temporarily :o

    hmm another one I was asked was convert string to int without using atoi etc, get cracking lads.


  • Registered Users, Registered Users 2 Posts: 40,038 ✭✭✭✭Sparks


    FBs newest employee
    Right, that's it, you're banned.

    shutupshutupshutupshutupshutupshutupshutupshutupSHUTUP! :D
    Distracted is right, all of our products now echo my name to the screen temporarily :o
    Bug report: Tar is a bit narcissistic and now our product is enabling him :D
    hmm another one I was asked was convert string to int without using atoi etc, get cracking lads.
    Hmmmmm..... ascii or truly evil unicode? :D


  • Technology & Internet Moderators Posts: 28,830 Mod ✭✭✭✭oscarBravo


    hmm another one I was asked was convert string to int without using atoi etc, get cracking lads.

    In Python:
    digits = "0123456789"
    result = 0
    for d in input_string:
      result = result * 10 + digits.index(d)
    
    Adapt as necessary for less... elegant languages. ;)


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 40,038 ✭✭✭✭Sparks


    oscarBravo wrote: »
    less... elegant languages. ;)
    I love me some Python, but even I wouldn't have said that while Ruby was listening :D


  • Registered Users, Registered Users 2 Posts: 6,566 ✭✭✭GrumPy


    I went for an android interview, 3rd and final round. The whole test was in C/++ and was got to do with "do this without using inbuilt functions and bonus marks for the more shifting of bits you do". At no stage in the interviews was anything java or android really asked about, an odd question here and there. It was disgusting, and they were offering 20k.

    The whole point is that I'm abstracted from that stuff, waste of time, and I had no idea how to do anything with bit shifting anyway. It would take me a good while to even follow the logic in Sparks post :D

    Third round, they gave you a C++ exam (for Android?!), and offering 20k?
    Jaysus! That's an insult. 3 interviews deep, and an exam that doesn't really make sense.


  • Technology & Internet Moderators Posts: 28,830 Mod ✭✭✭✭oscarBravo


    Sparks wrote: »
    I love me some Python, but even I wouldn't have said that while Ruby was listening :D

    I can't get to love Ruby. The syntax just leaves me cold. After almost three decades of professional software development, I think I've found my One True Love in Python.


  • Registered Users, Registered Users 2 Posts: 40,038 ✭✭✭✭Sparks


    oscarBravo wrote: »
    I can't get to love Ruby. The syntax just leaves me cold. After almost three decades of professional software development, I think I've found my One True Love in Python.
    I have this theory that certain people grok certain languages and that the mapping is unique to each person. Me, I grok C and python and I know a few others well enough to do good work in them, but I keep looking at Ruby and thinking I'd like to learn it but it never sits still in my head long enough to do anything worthwhile with. Still strikes me a a really pretty language though.

    But then, Erlang made lots of sense to me from day one and I'm told that's a bit abnormal, so I might be a bad data point :D


  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,110 Mod ✭✭✭✭Tar.Aldarion


    GrumPy wrote: »
    Third round, they gave you a C++ exam (for Android?!), and offering 20k?
    Jaysus! That's an insult. 3 interviews deep, and an exam that doesn't really make sense.
    Yeah, apparently was down to the last two, adn teh hour long phone interview that I did also...focused on RTOS. Wut.
    oscarBravo wrote: »
    In Python:
    digits = "0123456789"
    result = 0
    for d in input_string:
      result = result * 10 + digits.index(d)
    
    Adapt as necessary for less... elegant languages. ;)
    Python is cheating ;)

    135.jpg
    oscarBravo wrote: »
    I can't get to love Ruby. The syntax just leaves me cold. After almost three decades of professional software development, I think I've found my One True Love in Python.
    Python, what can i say, I never did it until i started working here, it is beautiful.


  • Registered Users, Registered Users 2 Posts: 40,038 ✭✭✭✭Sparks


    The LaTeX one is very very very true. But the Assembly one isn't right, that joke makes more sense if he was talking about Forth :D


  • Registered Users, Registered Users 2 Posts: 1,311 ✭✭✭Procasinator


    For those who are to lazy to attempt the max themselves:
    http://stackoverflow.com/questions/1375882/mathematically-find-max-value-without-conditional-comparison

    I think the top answer is what Sparks was trying to get at in his second example, but I'm not fully sure on how his example works (where does k come from?).

    The answer says:
    a - ((a-b)*((a-b)>>31))
    


    It assumes 2-complements and a int type of 32 bits.
    How it works:
    IF a < b, than a-b will negative. Negative numbers will have the most significant bit (MSB) set to 1, and so
    (a-b)>>31 = -1 (arithmetic shift will keep the number negative).
    In two-complements, -1 will have every bit set to 1. So:
    a-b & -1 = a-b
    Plugging back into original formula will be a - (a - b) shows the a cancel each other out, and we are left with b.

    IF a >= b, then a-b will be positive. A positive will have a MSB of 0, and hence:
    (a-b)&((a-b)>>31) = a-b & 0 = 0.
    Plugging back in, we get a - 0, which leaves us with a.


  • Registered Users, Registered Users 2 Posts: 40,038 ✭✭✭✭Sparks


    Yeah, the top answer there is doing what I was doing (exactly the same thing in fact), but I'll happily lay claim to have written the more readable version!
    (Not to mention, any decent compiler would take my code and his code and produce the same assembler - the only difference is that I'm using an explicit intermediate variable and doing the steps on different lines).


  • Registered Users, Registered Users 2 Posts: 1,311 ✭✭✭Procasinator


    Sparks wrote: »
    Yeah, the top answer there is doing what I was doing (exactly the same thing in fact), but I'll happily lay claim to have written the more readable version!
    (Not to mention, any decent compiler would take my code and his code and produce the same assembler - the only difference is that I'm using an explicit intermediate variable and doing the steps on different lines).

    Yeah, they are very similar.
    For readability, they would be similar if you wrote out the SO answer like:
    int diff = a - b;
    int complement = diff >> 31;
    int max = a - (diff & complement);
    

    Which I prefer slightly, as we are doing one less operation - but like you said, it is likely optimised to the same output.


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 851 ✭✭✭TonyStark


    Hey I know these threads come up quite frequently basically I have a tecnical test with IBM without any real idea what to expect.

    To be honest what has made it worse is that the manager I did the first interview laughed at how easy it was and assured me if be fine, then the HR lady said it was never something anyone complained about but I really have no idea where to review/practice and now I'm worried I'll make an eijet of myself.

    So I thought a thread on technical questions might come in handy for people to practice before going into interviews.

    So no answers unless someone is stuck but previous questions I have encountered are.

    Q1
    How to tell if a binary is a palindrom.

    Q2
    Given two lists List all the unique words which occur in each list and if a word occurs multiple times show it multiple times. (This was badly phrased when I got it so I'm going to show some examples to explain)

    L1=Tom,Tom,Tom,John
    L2=Tom,john, mike,Rob
    Combined list = Tom,Tom, Mike, Rob

    Also any advice for my own test let me know.

    Just in relation to the programming part of the original post. I regularly use projecteuler.com and codeeval.com as basically a source for newer online challenges.

    Tend to as of late prefer the the codeeval site as it is language agnostic and you can version some of the attempts. Might be interesting to have a "boards" league. Where once a week a problem from the easy, medium & hard sections are selected and we post back our solutions and then our actual scores from the automated grader, discuss some of the solutions have a flame war and then move on :-)


  • Technology & Internet Moderators Posts: 28,830 Mod ✭✭✭✭oscarBravo


    I'll just throw in a mention for codingame.com, it can be fun too.


  • Registered Users, Registered Users 2 Posts: 2,021 ✭✭✭ChRoMe


    TonyStark wrote: »
    Might be interesting to have a "boards" league. Where once a week a problem from the easy, medium & hard sections are selected and we post back our solutions and then our actual scores from the automated grader, discuss some of the solutions have a flame war and then move on :-)

    I really like this idea.


  • Registered Users, Registered Users 2 Posts: 40,038 ✭✭✭✭Sparks


    While we're throwing out sites, I take it we've all got http://codekata.com/ in our bookmarks?


  • Registered Users, Registered Users 2 Posts: 763 ✭✭✭Dar


    Sparks wrote: »
    While we're throwing out sites, I take it we've all got http://codekata.com/ in our bookmarks?

    Also CodeJam 2014 is starting on 11th April.


  • Registered Users, Registered Users 2 Posts: 40,038 ✭✭✭✭Sparks


    Pfffft codejam. SOOOO last year. SpaceApps is where its at :D


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 1,922 ✭✭✭fergalr


    This looks worthwhile: http://www.topcoder.com/asteroids/asteroiddatahunter/

    Like most worthwhile things, probably bigger than can be tackled in an evening... :|


Advertisement