Pages

Thursday, June 2, 2011

[ Java ] Technical Questions With Answers



Java Technical Questions With Answers

Q1. How could Java classes direct program messages to the system console, but
error messages, say to a file?
A. The class System has a variable out that represents the standard output, and the
variable err that represents the standard error device. By default, they both point at the
system console. This how the standard output could be re-directed:
Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st);
System.setOut(st);

Q2. What's the difference between an interface and an abstract class?
A. An abstract class may contain code in method bodies, which is not allowed in an
interface. With abstract classes, you have to inherit your class from it and Java does not
allow multiple inheritance. On the other hand, you can implement multiple interfaces in your
class.

Q3. Why would you use a synchronized block vs. synchronized method?
A. Synchronized blocks place locks for shorter periods than synchronized methods.

Q4. Explain the usage of the keyword transient?
A. This keyword indicates that the value of this member variable does not have to be
serialized with the object. When the class will be de-serialized, this variable will be initialized
with a default value of its data type (i.e. zero for integers).

Q5. How can you force garbage collection?
A. You can't force GC, but could request it by calling System.gc(). JVM does not guarantee
that GC will be started immediately.

Q6. How do you know if an explicit object casting is needed?
A. If you assign a superclass object to a variable of a subclass's data type, you need to do
explicit casting. For example:
Object a; Customer b; b = (Customer) a;
When you assign a subclass to a variable having a supeclass type, the casting is performed
automatically.

Q7. What's the difference between the methods sleep() and wait()
A. The code sleep(1000); puts thread aside for exactly one second. The code wait(1000),
causes a wait of up to one second. A thread could stop waiting earlier if it receives the
notify() or notifyAll() call. The method wait() is defined in the class Object and the method
sleep() is defined in the class Thread.

Q8. Can you write a Java class that could be used both as an applet as well as an
application?
A. Yes. Add a main() method to the applet.

Q9. What's the difference between constructors and other methods?
A. Constructors must have the same name as the class and can not return a value. They are
only called once while regular methods could be called many times.

Q10. Can you call one constructor from another if a class has multiple
constructors
A. Yes. Use this() syntax.

Q11. Explain the usage of Java packages.
A. This is a way to organize files when a project consists of multiple modules. It also helps
resolve naming conflicts when different packages have classes with the same names.
Packages access level also allows you to protect data from being used by the nonauthorized
classes.

Q12. If a class is located in a package, what do you need to change in the OS
environment to be able to use it?
A. You need to add a directory or a jar file that contains the package directories to the
CLASSPATH environment variable. Let's say a class Employee belongs to a package
com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.java. In this case, you'd
need to add c:\dev to the variable CLASSPATH. If this class contains the method main(),
you could test it from a command prompt window as follows:
c:\>java com.xyz.hr.Employee

Q13. What's the difference between J2SDK 1.5 and J2SDK 5.0?
A.There's no difference, Sun Microsystems just re-branded this version.

Q14. What would you use to compare two String variables - the operator == or
the method equals()?
A. I'd use the method equals() to compare the values of the Strings and the == to check if
two variables point at the same instance of a String object.

Q15. Does it matter in what order catch statements for FileNotFoundException
and IOExceptipon are written?
A. Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's
subclasses have to be caught first.

Q16. Can an inner class declared inside of a method access local variables of this
method?
A. It's possible if these variables are final.

Q17. What can go wrong if you replace && with & in the following code:
String a=null; if (a!=null && a.length()>10) {...}
A. A single ampersand here would lead to a NullPointerException.

Q18. What's the main difference between a Vector and an ArrayList
A. Java Vector class is internally synchronized and ArrayList is not.

Q19. When should the method invokeLater()be used?
A. This method is used to ensure that Swing components are updated through the eventdispatching
thread.

Q20. How can a subclass call a method or a constructor defined in a superclass?
A. Use the following syntax: super.myMethod(); To call a constructor of the superclass, just
write super(); in the first line of the subclass's constructor
For senior-level developers:

Q21. What's the difference between a queue and a stack?
A. Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule

Q22. You can create an abstract class that contains only abstract methods. On
the other hand, you can create an interface that declares the same methods. So
can you use abstract classes instead of interfaces?
A. Sometimes. But your class may be a descendent of another class and in this case the
interface is your only option.

Q23. What comes to mind when you hear about a young generation in Java?
A. Garbage collection.

Q24. What comes to mind when someone mentions a shallow copy in Java?
A. Object cloning.

Q25. If you're overriding the method equals() of an object, which other method
you might also consider?
A. hashCode()

Q26. You are planning to do an indexed search in a list of objects. Which of the
two Java collections should you use:
ArrayList or LinkedList?
A. ArrayList

Q27. How would you make a copy of an entire Java object with its state?
A. Have this class implement Cloneable interface and call its method clone().

Q28. How can you minimize the need of garbage collection and make the
memory use more effective?
A. Use object pooling and weak object references.

Q29. There are two classes: A and B. The class B need to inform a class A when
some important event has happened. What Java technique would you use to
implement it?
A. If these classes are threads I'd consider notify() or notifyAll(). For regular classes you can
use the Observer interface.

Q30. What access level do you need to specify in the class declaration to ensure
that only classes from the same directory can access it?
A. You do not need to specify any access level, and Java will use a default package access
level.

[Unix] VI editor commands


Some useful vi commands

1.) vi filename gets you into the editor

2.) h - move left one space

3.) j - move down one line

4.) k - move up one line

5.) l - move right one space

6.) i - go into insert mode

7.) 'esc' key - get out of insert mode

8.) x - delete a character

9.) dd - delete the current line, 2dd delete the current and next line, 3dd etc.

10.) / - to into search mode to search for a pattern

11.) a - go into append mode to append characters, use 'esc' key to get out of this mode

12.) ctrl f - page forward one screen

13.) ctrl b - page back one screen

14.) G - the go command, type 44G to move the cursor to line 44. G w/o a line number move
you to the end of the file.

15.) ctrl g - tells you what line you are on in the file and how many lines the file contains.

16.) shift ZZ gets your file written to disk and exits the editor

17.) :quit! quits the file w/o saving your changes (in case you mess up).

[ Written test ] CTS Cognizant questions


Written test consists of three sections  CTS Cognizant.

VERBAL SECTION (25 questions-25min)
(1-10) comprehension (passages r too long)
(11-15) find the incorrect sentences
(16-20) find the correct sentences
(21-25) arrange the jumbled sentences
This is a quiet tough section. Just make guesses. Mark option B or C.Always read passage at last.Read questions first.
ANALTICAL SECTION (25 questions-30min) 
(1-5) Venn diagram 

A group is divided into three. The first group is persons of 5'6 height and second and third r 6'0 and 6'6 respectively. There r totally 130 peoples, 50 of them r 5'6 and 65 of them r 6'6, 10 of them r 5'6 and 6'6, 15 of them r 5'6 and 6, 20 of them r 6'6 and 6, and 5 of them r all the three.
(1) How many of them r 6 feet? (Ans 70)
(2) How many of them r only 6 feet? (Ans 30)
(3) How many of them are only 5’6? (Ans 20)
(4) How many of them are only 6’6? (Ans 30)
(5) How many of them are at least two? (Ans 50)  
Important formula in Venn diagram is
EXACTLY ONE = TOTAL - EXACTLY TWO - ALL THREE  
(6-10) quantitative questions  

Questions on Blood relations(quite difficult) 
Other questions r from profit loss and other general questions. Sorry I don’t remember  
(11-15) data sufficiency--Very easy one
(16-20) binary conversion
Please don’t read anything in the question. Just change any value to binary and convert that 1 to $ and 0 to *.
(Eg) LCM of (12 15 10) (ans 60 = 111100 = $$$$**)
(21-25) cubes
Questions like :if a dice is thrown 2 on top,3&5 at left &right,in another turn 5 on top,3&4 at left&right and one another condition(dont remember exactly)
21-25 What is opposite to 5?.....
NON VERBAL SECTION (20 questions-20 min)  
(1-4) syllogism (study all rules in the aggarwal book but TIME book will help u a lot)
(Eg) All mosquitoes’ are lizards.
All lizards are insects.
(Ans: all mosquitoes’ are insects)
(5-6) logical deduction (study all rules from TIME book)
(7-15) figure sequence and odd one out from figures (very easy)(just go through R S Agarwal)  
(16-17) Seating arrangement
(18-20) logical puzzle
After two hours the sortlist was declared by them .I was almost sure that I would be clearing the aptitude.

          
The Merit Track conducted the test. It was organized perfectly and they expect discipline from us.. Before the test u have to fill a form. Do it carefully because some of my friends got questions 4m tat.

1.Software Orientation:
2.Hobbies and extra-curricular activities
3.Strengths and Weakness
4.Expectation from CTS
5.Why CTS
6. Long term and short-term goal with CTS
7.What are the qualities necessary for software professional to be successful



WRITTEN TEST (3 sections) NO –VE MARKING

1.Analytical Ability (25 Q, 30 Minutes)
Venn diagram questions
Data sufficiency
coding 1 represented as $ and 0 as *(easy.. jus convert it into Binary)
Cubes related questions are very important

My suggestion is do Coding First. Then Venn dig. Cube problem n others..u can surely score full marks fm coding n venn dig…cube is also easy when u understand it.For cube take the cubic root of the no of pieces.64 means 4(keep as x value)..then 2 side painted means   12*(x-2).1side painted means 6*(x-2) 2 .  (horizontal n vertical) like wise u must think  n apply according to the question..

1.venn dig- people hving dif heights 6feet ,6’6 feet, 5’5 feet.and questions like no of people who is 6 feet.no of people who is 5’5feet…..
2.In codin there will be only normal arithmetic operations n L.c.m..i don remember them.
For ex..64/4= 16 = $****.first solve it n convert it to binary..

3.Cube- a cube of 12 cm is cut into small 3cm pieces..then place another 4 small cubes  over it..and another 2 small cubes over the 4cubes..then again one more cube over the 2 cube…the cube is then painted from top to bottom
12/3=4…so 4row 4column…draw a dig of cube first. Imagining the cube only help u to solve rather than formulas. How many cubes r painted on only one side?
how many cubes r painted on only 2 sides?
how many cubes r painted on only 3 sides?
how many cubes r painted on only 4 sides?
how many cubes r painted 0 sides?
(my friends told me tat cube problems hav more marks than other questions)

2.Verbal Ability (20 Q, 20 Min)
Comprehension
Find out the incorrect sentence
Find out the correct sentence
Jumbled Passages
-Don prepare any thing for this ..It won help u..Jumbled sent n correct incorrect sent are a little confusing..it depends on ur grammer n English language skills.  do the comprehension last(it is a very big passage..i didn’t even read  it ,jus ticked..no time)
3.Attention Details (20 Q, 20 Min)
Find the odd man out
Analogy of figures (Simple)
syllogism
Puzzle
Very easy compared to other sections..any one can crack it with out any preparation..If u think to prepare jus go through puzzle test n syllogism from R.S.Agarwal Verbal reasoning
Analogy of figures –Non verbal Reasoning
   
  Set 3
      1. A says " the horse is not black".
      B says " the horse is either brown or grey."
      c says " the hoese is brown"
      At least one is telling truth and atleast one is lying. tell 
  the colour of horse.
     
   Answer : grey
      
   2. A son and father goes for boating in river upstream . After 
  rowing for 1 mile son notices the hat of his fathe falling in the river. 
  After 5min. he tells his father that his hat has fallen. So they turn around 
  and are able to pick the hat at the point from where they began boating 
  after 5min.
  Tell the speed of river.
   Ans...6 miles/hr
      
   3  A+B+C+D=D+E+F+G=G+H+I=17  where each letter represent a 
  number from 1 to 9. Find out what does letter D and G represent if letter A=4.   
   (8 marks)
   ans.   D=5
          G=1
    4. Argentina had football team of 22 player of which captain is 
  from Brazilian team and goalki from European team. For remainig 
  palayer they have picked 6 from argentinan and 14 from european. Now for a 
  team of 11 they must have goalkeeper and captain so out of 9 now they plan to 
  select 3 from argentinian and 6 from European. Find out no. of methods avilable
  for it (2 marks)
   Ans : 160600( check out for right no. 6C3 * 14C6)
      
   5 Three thives were caught stealing sheep, mule and camel.
     A says " B had stolen sheep "
     C says " B had stolen mule"
     B says he had stolen nothing.
      the one who had stolen horse is speaking truth. the one who had stolen 
   camel is lying . Tell  who had stolen what? (5 marks)
   ans. A- camel
        B- mule
        C- horse
   6  a group of friends  goes for dinner and gets bill of Rs 2400 .
 Two of them says that they have forgotten their purse so remaining 
  make an extra contribution of Rs 100 to pay up the bill. Tell the no. of 
  person in that group. (3 marks)
 Ans - 8 person
7. In acolony there are some families. Each of them have 
  children but different in numbers.Following are conditions
     a  no of adult no of sons no of daughters no of families.
     b each sister must have atleast one brother and should have 
  at themost 1 sister.      
     c  no of children in one family exceeds the sum of no of 
  children in the rest families.
   Tell the no of families.(5 marks)
    ans : 3 families
   8. There are 6 people W,H,M,C,G,F who are murderer , victim , 
  judge , police, witness, hangman. There was no eye witness only 
  circumtancial witness. The murderer was sentenced to death.
   Read following statement and determine who is who.
   1. M knew both murderer and victim.
   2. Judge asked C to discribe murder incident.
   3. W was last to see F alive.
   4. Police found G at the murder site.
   5 H and W never met.