Interveiew Questions

98 views
Skip to first unread message

Shailendra shail

unread,
Feb 5, 2011, 7:05:12 AM2/5/11
to newidea_or...@googlegroups.com
Hi friend,

          Today i got few java interesting question. If you could give best answer.
  1. What is immutable class in java and how to create?
  2. How do you achieve multiple inheritance in java?
  3. What are the methods we can use to maintain session.

Shailendra shail

unread,
Feb 5, 2011, 7:09:42 AM2/5/11
to newidea_or...@googlegroups.com

Shailendra shail

unread,
Mar 4, 2011, 2:08:40 PM3/4/11
to newidea_or...@googlegroups.com
If we are overriding equal method of an object, which method is necessary to override too? 

Shailendra shail

unread,
Mar 4, 2011, 2:11:04 PM3/4/11
to newidea_or...@googlegroups.com
I think we must have to override hashCode() method. If you are going to override equal method.
hashCode should return int.

but can any one guess what exactly hashCode() return for an object and where we can use this?

Shailendra shail

unread,
Mar 5, 2011, 12:15:03 PM3/5/11
to newidea_or...@googlegroups.com
How could Java classes direct program messages to the system console, but error messages, say to a file?

What can go wrong if you replace && with & in the following code:
String a=null; if (a!=null && a.length()>10) {...}

How can you minimize the need of garbage collection and make the memory use more effective?

ccsC...@gmail.com

unread,
Mar 5, 2011, 10:13:30 PM3/5/11
to newidea_or...@googlegroups.com
On , Shailendra shail <mr.shaile...@gmail.com> wrote:
> How could Java classes direct program messages to the system console, but error messages, say to a file?

-- We can write a class like Logger that accepts the message to be displayed and the output stream (PrintWriter instance) as arguments. Lets say-
public static void logMessage(PrintWriter stream, String msg ) { }
Now, in case of program message, call like Logger.logMessage( new PrintWriter(System.out), "Messsage"); while in case of an error, we pass in the Output Stream of that file as the stream argument.


> What can go wrong if you replace && with & in the following code:
>
>
> String a=null; if (a!=null && a.length()>10) {...}

this will throw a NullPointerException as a.length() will now be evaluated cos '&' is a Bitwise And and is not Short Circuited. Earlier, when it was && the second expression would not get evaluated at all.. as its Short Circuited.


> How can you minimize the need of garbage collection and make the memory use more effective?

Minimizing garbage collection does not mean that memory usage of the program. For a program to have effective memory usage, you must indicate the objects ready to be GC'd by nullifying them. We do not have any control over the GC.

Shailendra shail

unread,
Mar 6, 2011, 1:37:28 AM3/6/11
to newidea_or...@googlegroups.com
Thats correct new. I'd like to add some thing like ...

> 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);

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

Shailendra shail

unread,
Mar 7, 2011, 12:49:17 AM3/7/11
to newidea_or...@googlegroups.com
Friends,
          In conversation I have put two buzz-word Object Pooling and Object Reference, Can any one give some some good example or clarification on this in context of java programming?
--
Shailendra Kumar shail

Nishant Gupta

unread,
Mar 7, 2011, 1:18:30 AM3/7/11
to newidea_or...@googlegroups.com
Hi,

Object pooling is a way to manage access to a finite set of objects among competing clients. in other words, object pooling is nothing but sharing of objects between different clients.
Since object pooling allows sharing of objects ,the other clients/processes need to re-instantiate the object(which decreases the load time), instead they can use an existing object. After the usage , the objects are returned to the pool.

One very good application where you can see this happen is Connection Pooling. Connections are nothing but Objects of "Connection" class in Java. Either you use the connection pooling code of the ojdbc14.jar or JBoss, we are basically "caching" some objects and maintaining a ready list of objects.

The general idea for the Object Pool pattern is that if instances of a class can be reused, you avoid creating instances of the class by reusing them.

But we must be Very careful in deciding what to pool. Classes that are under synchronization are one example where pooling can be dangerous.

Regarding Object Reference, Java always manipulates objects by reference. Its not very clear what you want to know about that. Can you be a bit specific ?

Also, a nice Java Puzzle- Try if possible-

Set<Short> testSet = new HashSet<Short>();
                for(short i=0;i<100;i++) {
                    testSet.add(i);
                    testSet.remove(i-1);
                }

                System.out.println("Size="+testSet.size());

Whats the Output ? and more importantly WHY ?



Nishant Gupta,

 APPLE Developer ( TCS-Apple Offshore ) | Mail: nishan...@apple.com | ' 9342420245, 9620779208


Shailendra shail

unread,
Mar 7, 2011, 6:41:30 AM3/7/11
to newidea_or...@googlegroups.com
Interesting..
Its is printing Size=100 but i am not sure y?
even set is containing.. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 16, 19, 18, 21, 20, 23, 22, 25, 24, 27, 26, 29, 28, 31, 30, 34, 35, 32, 33, 38, 39, 36, 37, 42, 43, 40, 41, 46, 47, 44, 45, 51, 50, 49, 48, 55, 54, 53, 52, 59, 58, 57, 56, 63, 62, 61, 60, 68, 69, 70, 71, 64, 65, 66, 67, 76, 77, 78, 79, 72, 73, 74, 75, 85, 84, 87, 86, 81, 80, 83, 82, 93, 92, 95, 94, 89, 88, 91, 90, 98, 99, 96, 97]
which is strange..

even if i am adding
 testSet.remove(1);
after for loop its not removing any element..


But if you look at this

Vector<Short> vect= new Vector<Short>();

        for(short i=0;i<100;i++) {
            vect.add(i);
            try{
                vect.remove(i-1);
            }
            catch(Exception ex){
                System.out.println("err:" + i +ex.toString());
            }
        }
        System.out.println("VSize="+vect.size());

this behaving differently

Any way Neo your answer is good but how come this example describing Object Pooling..?
--
Shailendra Kumar shail

Nishant Gupta

unread,
Mar 7, 2011, 11:11:23 PM3/7/11
to newidea_or...@googlegroups.com
Hi,

The size will be 100. Here is why-

- when we say testSet.remove(i-1), i-1 is an expression involving a short and an int. Whenever such expressions are encountered, the result is promoted to the more accommodating type, in this case int.

- the remove() method in a set accepts a parameter of type - "Object". So, this resultant int is Autoboxed to Integer.

- The remove() method, tries to do a match based upon equality into the set elements and removes the matching element. Now, here we are dealing with Wrappers Short and Integer. While executing their "equals()" method, the equality test fails, and the method cannot find any match to remove. So, the size does not decrease.

But, when you see the add() method in Set interface has been declared with add(T t) as param, which is how it should be, to enforce compile time type checking. Just try passing anything other than a short into add() and you'll find the compiler complaining. Similarly, to enforce type safety, remove() should have been declared the same way, rather than passing an object parameter... any thoughts ??

Regarding the second example, Vector does the removal based upon "index". so if we say remove(0) its does not mean remove the element 0, it means remove the element At 0. The signature of the method is remove(int index). So, even if we pass a short it will automatically get promoted to int. Secondly, this program(Vector one) will throw ArrayIndexOutOfBoundsException 100 times, as at the current index i, we are trying to remove a non-existing index i-1 starting with -1 and onwards till 98. That explains the different behavior.

Thanks & Regards,

Nishant Gupta,
 APPLE - Developer (TCS Offshore)
neo324893 @ AIM
+91 9342420245, 9620779208

Shailendra shail

unread,
Apr 19, 2011, 12:38:42 PM4/19/11
to newidea_or...@googlegroups.com
1) What is the difference between Serializable and Externalizable interface in Java?
This is most frequently asked question in java serialization interview. Here is my version Externalizable provides us writeExternal () and readExternal () method which gives us flexibility to control java serialization mechanism instead of relying on java's default serialization. Correct implementation of Externalizable interface can improve performance of application drastically.

2) How many methods Serializable has? If no method then what is the purpose of Serializable interface?
Serializable interface exists in java.lang package and forms core of java serialization mechanism. It doesn't have any method and also called Marker Interface. When your class implements Serializable interface it becomes Serializable in Java and gives compiler an indication that use Java Serialization mechanism to serialize this object.

3) What is serialVersionUID? What would happen if you don't define this?
SerialVersionUID is public static final constant which should define in your class otherwise compiler will throw warning. If you do not specify serialVersionUID in your class Java compiler automatically generates it while persisting the object and uses its own algorithm to generate it which is normally based on fields of class and normally represent hash code of object. Consequence of not implementing serialVersionUID is that when you add or modify any field in class then already serialized class will not be able to recover because serialVersionUID generated for new class and for old serialized object will be different. Java serialization process relies on correct serialVersionUID for recovering state of serialized object.


4) While serializing you want some of the members not to serialize? How do you achieve it?
this is sometime also asked as what is the use of transient variable, does transient and static variable gets serialized or not etc. so if you don't want any field to be part of object's state then declare it either static or transient based on your need and it will not be included during java serialization process.

5) What will happen if one of the members in the class doesn't implement Serializable interface?
If you try to serialize an object of a class which implements Serializable, but the object includes a reference to an non- Serializable class then a ‘NotSerializableException’ will be thrown at runtime and this is why I always put a SerializableAlert (comment section in my code) to instruct developer to remember this fact while adding a new field in a Serializable class.


6) If a class is Serializable but its super class in not, what will be the state of the instance variables inherited from super class after deserialization?
Java serialization process  only continues in object hierarchy till the class is Serializable i.e. implements Serializable interface in Java And values of the instance variables inherited from super class will be initialized by calling constructor of Non-Serializable Super class during deserialization process .

7) Can you Customize Serialization process or can you override default Serialization process in Java?
The answer is yes you can. We all know that for serializing an object objectOutputStream.writeObject (saveThisobject) is invoked and for reading object ObjectInputStream.readObject () is invoked but there is one more thing which Java Virtual Machine provides you is to define these two method in your class. If you define these two methods in your class then JVM will invoke these two methods instead of applying default serialization mechanism. You can customize behavior of object serialization or deserialization here by doing any kind of pre or post processing task. Important point to note is making these methods private to avoid being inherited, overridden or overloaded. Since only Java Virtual Machine can call private method integrity of your class will remain and Java Serialization will work as normal.

8) Suppose super class of a new class implement Serializable interface, how can you avoid new class to being serialized?
If Super Class of a Class already implements Serializable interface in Java then its already serializable in Java, since you can not unimplemented an interface its not really possible to make it Non Serializable class but yes there is a way to avoid serialization of new class. To avoid java serialization you need to implement writeObject () and readObject () method in your Class and need to throw NotSerializableException from those method. This is another benefit of customizing java serialization process as described in above question and normally it asked as follow-up question as interview progresses.

9) Which methods are used during Serialization and DeSerialization process in java?
This is quite a common question basically interviewer is trying to know that whether you are familiar with usage of readObject (), writeObject (), readExternal () and writeExternal () or not. Java Serialization is done by java.io.ObjectOutputStream class. That class is a filter stream which is wrapped around a lower-level byte stream to handle the serialization mechanism. To store any object via serialization mechanism we call objectOutputStream.writeObject (saveThisobject) and to deserialize that object we call ObjectInputStream.readObject () method. Call to writeObject () method trigger serialization process in java. one important thing to note about readObject() method is that it is used to read bytes from the persistence and to create object from those bytes and its return an Object which needs to be casted on correct type.

10) Suppose you have a class which you serialized it and stored in persistence and later modified that class to add a new field. What will happen if you deserialize the object already serialized?
It depends on whether class has its own serialVersionUID or not. As we know from above question that if we don't provide serialVersionUID in our code java compiler will generate it and normally it’s equal to hash code of object. by adding any new field there is chance that new serialVersionUID generated for that class version is not the same of already serialized object and in this case Java Serialization API will throw java.io.InvalidClassException and this is the reason its recommended to have your own serialVersionUID in code and make sure to keep it same always for a single class.


11) What are the compatible changes and incompatible changes in Java Serialization Mechanism?
The real challenge lies with change in class structure by adding any field, method or removing any field or method is that with already serialized object. As per Java Serialization specification adding any field or method comes under compatible change and changing class hierarchy or unimplementing Serializable interfaces some under non compatible changes. For complete list of compatible and non compatible changes I would advise reading java serialization specification.

12) Can we transfer a Serialized object vie network?
Yes you can transfer a Serialized object via network because java serialized object remains in form of bytes which can be transmitter via network.

13) Which kind of variables is not serialized during Java Serialization?
This question asked sometime differently but the purpose is same whether Java developer knows specifics about static and transient variable or not. Since static variables belong to the class and not to an object they are not the part of the state of object so they are not saved during Java Serialization process. As Java Serialization only persist state of object and not object itself. Transient variables are also not included in java serialization process and are not the part of the object’s serialized state. After this question sometime interviewer ask a follow-up if you don't store values of these variables then what would be value of these variable once you deserialize and recreate those object? This is for you guys to think about :)

Nishant Gupta

unread,
Apr 19, 2011, 10:42:26 PM4/19/11
to newidea_or...@googlegroups.com
Well compiled. Really informative.

As for the last question, the values will be initialized to their default initial values.

Shailendra shail

unread,
Apr 22, 2011, 10:52:54 PM4/22/11
to newidea_or...@googlegroups.com
Thats correct neo.

Shailendra shail

unread,
Apr 28, 2011, 1:04:27 AM4/28/11
to newidea_or...@googlegroups.com
TCS Interview Questions.
  • What is difference between StringBuffer and StringBuilder? Explain.
  • What are the Dependencies Injections in spring framework.
  • How do you load properties/resource file using spring.
  • Is there any difference between load and get method in Hibernate.
  • What is difference between 1st level caching and 2nd level of caching mechanism. How to enable 2nd level of caching?
  • How and where do you configure for 2nd level of caching  for a specific method. What is eternal .
  • How to create a group in Maven
  • What do you mean be dependencies in Mavan
  • Where do we set Repository Configuration to take for all Jars and what is the preferences.
  • Can Maven be used for deployment. If so how?
  • How to force Maven to use a Specific type of JVM?
  • What are the parameters we use in mvn command.
  • What is "With" clause in Oracle
  • How do you create Exception in Oracle and use?
  • How to select 2nd top salary from Salary Table in Oracle
These are the question I have answered yesterday and I thought to share with you. I will request you all to give your answer for above question if you know so that other can learn. My answer will be at last moment. Hope every one will participate in this discussion to answer above questions.

Thanks, Have a grate day ahead :) !

Shailendra shail

unread,
May 5, 2011, 1:48:15 AM5/5/11
to newidea_or...@googlegroups.com
Friends, Did you get any answer for these question? If yes.. Please post.

Nishant Gupta

unread,
May 5, 2011, 2:30:01 AM5/5/11
to newidea_or...@googlegroups.com
Don't know all concepts here, but I've written whatever I knew...

Thanks & Regards,

Nishant Gupta,
Developer 
neo324893 @ AIM )
+91 8050041001, 9620779208 )

On 28-Apr-2011, at 10:34 AM, Shailendra shail wrote:

TCS Interview Questions.
  • What is difference between StringBuffer and StringBuilder? Explain.
StringBuffer is Threadsafe while StringBuilder is not. So, in applicable scenarios, StringBuilder is significantly faster than StringBuffer. But StringBuffer should be used when sync is desired.

  • What are the Dependencies Injections in spring framework.
Don't really know Spring that well.

  • How do you load properties/resource file using spring.
Don't really know Spring that well.

  • Is there any difference between load and get method in Hibernate.
Don't know Hibernate.

  • What is difference between 1st level caching and 2nd level of caching mechanism. How to enable 2nd level of caching?
  • How and where do you configure for 2nd level of caching  for a specific method. What is eternal .
  • How to create a group in Maven
  • What do you mean be dependencies in Mavan
  • Where do we set Repository Configuration to take for all Jars and what is the preferences.
  • Can Maven be used for deployment. If so how?
  • How to force Maven to use a Specific type of JVM?
  • What are the parameters we use in mvn command.
-- Don't know Maven.

  • What is "With" clause in Oracle
With clause is used to assign a name to a subquery block, which can later be referred as that name.
WITH q AS (SELECT * FROM EMP)
SELECT emp_num FROM q where..... ... ... ;

  • How do you create Exception in Oracle and use?
declare
some_custom_exception EXCEPTION;
PRAGMA_EXCEPTION_INIT (some_custom_exception, -2223223); //a number for our exception it'd come as ORA-2223223
begin
... ... ... // ahead with your logic

  • How to select 2nd top salary from Salary Table in Oracle
select sal from( select sal from salary order by sal desc ) where rownum<n ; //here  'n' is the nth highest salary you want to select.

Hari Mohan

unread,
May 5, 2011, 4:26:44 AM5/5/11
to newidea_or...@googlegroups.com
Hi Shail .,

I think for immutability ,the class need not be a final class.
Though String is a final class ,we need not make our custom class a final one.


-Hari Mohan


Shailendra shail

unread,
May 9, 2011, 6:58:11 AM5/9/11
to newidea_or...@googlegroups.com
Very Nice Neo.  Some of remaining question i can clarify.
 

·What is difference between 1st level caching and 2nd level of caching mechanism? How to enable 2nd level of caching?

Sl. No.

1st Level Caching

2nd Level Caching

1

Hibernate support by default

Need manual configuration to enable into hibernateConfig.xml.

This is done by setting the following property in your hibernate config:

    <property name="hibernate.cache.use_second_level_cache">true</property>

You may also want to turn on the Hibernate query cache. This is done by setting the following property in your hibernate config:

    <property name="hibernate.cache.use_query_cache">true</property>

 
<property name="hibernate.cache.provider_class">              net.sf.ehcache.hibernate.SingletonEhCacheProvider</property>

 

2

It cache on session level

Its cache on session Factory level

3

No need any config file

Need ehcache.xml file to get the list of caching object, tenure and other info.

 

·   How and where do you configure for 2nd level of caching for a specific method. What is eternal?

Again same thing, we need to configure into hibernateConfig.xml as stated earlier. Eternal is used to maintain memory for cache and session for caching never expire if you set eternal=true.

·   How to create a group in Maven

To set a grouping for different packages, we use the <groups/> parameter. Each group will be consist of a <title/> and a <packages/> (as String). The <packages/> element supports wildcard (*) to allow subpackages.

        <groups>

            <group>

              <title>Example 1 - Group Packages</title>

              <packages> com.mycompany.myapp:com.mycompany.myapp.package1 </packages>

            </group>

        </groups>

·   What do you mean be dependencies in Maven

This task will check if any of the specified dependencies, and their dependencies are missing or updated, and download them if necessary. The dependencies will be made available as a fileset or path reference.

·   Where do we set Repository Configuration to take for all Jars and what is the preference.

Repository Configuration for all jar we do in settings.xml available in Maven directory installed and user’s .m2 folder. Preference is .m2, On unavailability its goes to main maven settings.

·   Can Maven be used for deployment? If so how?

Yes it can be. See example

<artifact:deploy file="target/my-project-1.0.jar">
    <remoteRepository url="scp://localhost/www/repository">
      <authentication username="${repository.username}" privateKey="${user.home}/.ssh/id_dsa"/>
    </remoteRepository>
    <pom refid="mypom"/>
  </artifact:deploy>

 

·   How to force Maven to use a Specific type of JVM?

You can provide class path and jvm information when you run mvn command. Use compiler plugins.

·   What are the parameters we use in mvn command?

Whatever parameter we give with mvn command are called plugins. There is a lot of available plugins but some of the common used plugins are

Ø  clean

Ø  deploy

Ø  install

Ø  site

Ø  ear

Ø  ejb

Ø  war

Ø  jar

Ø  eclipse

Ø  compiler

 Let us know your view tooooooo :)

Nishant Gupta

unread,
May 9, 2011, 7:05:14 AM5/9/11
to newidea_or...@googlegroups.com
@Shail-> Thanks boss :)

P.S: When you reply to somewhat older mails, pls leave the original text there... cos, in so many days, people are bound to forget.

Anyway, a fresh question...


What is the Command pattern and How can i use it to reduce decision trees in my Action Classes. Note that these action classes are ParameterAware and use a parameterValue to differentiate between different actions that it performs.

Shailendra shail

unread,
Oct 4, 2011, 12:45:46 AM10/4/11
to newidea_or...@googlegroups.com
Aptitude Question for Interview

A man needs to go through a train tunnel. He starts through the tunnel and when he get 1/4 the way through the tunnel, he hears the train whistle behind him. you don't know how far away the train is, or how fast it is going, (or how fast he is going). All you know is that if the man turns around and run back the way he came, he will just barely make it out of the tunnel alive before the train hits him. If the man keeps running through the tunnel, he will also just barely make it out of the tunnel alive before the train hits him. Assume the man runs the same speed whether he goes back to the start or continues on through the tunnel. Also assume that he accelerates to his top speed instantaneously, assume the train misses him by an infinitesimal amount.

How fast is the train going compared to the man?

Shailendra shail

unread,
Oct 4, 2011, 12:52:38 AM10/4/11
to newidea_or...@googlegroups.com
2. How will you measure height of building when you are at the top of the building and if you have stone with you.

3. You are given two candles of equal size, which can burn 1 hour each. You have to measure 90 minutes with these candles. (There is no scale or clock). Also u r given a lighter.

4. 1000 lights connected in series. One bulb has been fused. Hence the circuit is cut and none of the bulbs glow. you have a tester with you and how many time will you need to check to identify faulty bulb.

5. There are 9 coins. 8 are of 1 gm and 1 is of 2 grams. How will you find out the heavier coin in minimum number of weighing and how many weighing it will need?


Note: All these questions are common for written interview across the companies.Try to solve .


Harimohan Karunanithi

unread,
Oct 4, 2011, 1:47:51 AM10/4/11
to newidea_or...@googlegroups.com
Hi guys ,
 
Shail ., those questions are really good....
 
 
Ans : 3
 
If those candles ve 2 lighting point 1 on each side.
 
Light the 1st candle at 1 point and it takes 1hour to destroy itself.
Once the 1 candle is done ,
 
Light the 2nd candle at 2 point at the same time.So , it takes 30 mins to destroy itself.
 
Thus ., 90 misn is measured !!!
 
 
2.The stone u throw from top of the building makes a parabolic path.Hence , we get a parabola and a chord(Line joining 2 points in a parabola) .Lenght of the chord (2 * distance between the stone n building)..
After that , u got to apply the chord's equation and get the value.
 
5.
Usual way : 3 times
divide 9 coins into 8+ 1 randomly.now ., divide the 8coins into 4 + 4  and measure in the weighing machines.If the 2gm coin is present in the 8coins group ., 1 arm of the machine will indicate that.now , divide those 4 coins into 2 + 2 then follow the same procedure and arrive at 1 + 1 and then u got the coin
so ., it takes at maximum of 3 times to find the 2gm coin.
 
Shortest Way : 2 times
 
divide 9 coins into 3+3+3.
Take any 2 groups and weigh ..If the 2 gm coin is in the group.Then take those 3 coins and take 2 ramdomly and divide 1+1 and weigh and If they are equal ,3rd coin is the 2gm coin or else., you the 2gm coin in weighing itself.
 
If .,the first 2 groups weigh equal ., then take the 3rd group and use 1+ 1 logic.If they are equal ., the coin in your hand is the 2gm coin Or  u will get the 2gm coin in the weighing machine itself....!!!
 
So ., it takes maximum 2 times
 
 
 
Regards,
Hari Mohan
 
 
 
 

From: newidea_or...@googlegroups.com [newidea_or...@googlegroups.com] On Behalf Of Shailendra shail [mr.shaile...@gmail.com]
Sent: Tuesday, October 04, 2011 10:22 AM
To: newidea_or...@googlegroups.com
Subject: Re: Interveiew Questions

--
You received this message because you are subscribed to the Google
Groups "Technical Discussion" group.
To post to this group, send email to
newidea_or...@googlegroups.com
To unsubscribe from this group, send email to
newidea_or_techn...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/newidea_or_technical?hl=en

Shailendra shail

unread,
Oct 4, 2011, 1:58:22 AM10/4/11
to newidea_or...@googlegroups.com
Wow. very nice answer. Keep it up Hari, but I m not fully satisfied with answer for 2nd question. If you can explore it more.. and what about 1st question.. any guess?
--
Shailendra Kumar shail

Harimohan Karunanithi

unread,
Oct 4, 2011, 7:00:25 AM10/4/11
to newidea_or...@googlegroups.com
Hi Shail,
 
1Q ans is here .,
 
Train's speed = 2 * man's speed
 
Ref the attachment.
d=distance between train's engine and tunnel entrance.
x=tunnels length
 
s1=train's speed
s2=man's speed
 
t1 = Time taken by train to reach tunnel's entrance and Time taken by man to reach tunnel's entrance
t2=Time taken by train to reach tunnel's exit and Time taken by man to reach tunnel's exit
 
Hence,
 
s1=d/t1                          s2=x/4t1
 
s1=(x+d) /t2                  s2=3x/4t2
 
 
Taking ration between s1 and s2 gives  , s1 =2 * s2
 
 
Regards,
Hari Mohan
 

Sent: Tuesday, October 04, 2011 11:28 AM

Harimohan Karunanithi

unread,
Oct 4, 2011, 7:00:39 AM10/4/11
to newidea_or...@googlegroups.com
solution.png

Shailendra shail

unread,
Oct 4, 2011, 10:46:02 AM10/4/11
to newidea_or...@googlegroups.com
Hari, your answer is absolutely correct. Wow nice.. keep it up.

but for 2nd question: Instead of taking parabola equation you can use s=ut+1/2at^2 where u=0 and a = 10 (gravitational force 9.8 ~ 10).

This may not give absolutely  correct answer but it will give approx answer (because a is depend upon the mass of stone)
a can be calculate base on either
v=u+at where u=0


Hari Mohan

unread,
Oct 4, 2011, 11:51:25 AM10/4/11
to newidea_or...@googlegroups.com
Nice Shail .,
Thats from the second equation of motion...!!
Its the easiest way to calcuate !!


Regards,
Hari Mohan

Shailendra shail

unread,
Jan 5, 2012, 8:43:20 AM1/5/12
to newidea_or...@googlegroups.com
Today's Interview Question

1. What happens when we write scriptlet in java and how to write a scriptlet in JSP so that it will go into init method..
2. How many class file will be created if there is 3 inner class in A class and what will be the name of that class
3. When you compile Class it makes .class file what happens when you compile Interface of Enum. If it is creating same then how it is identified that whether this is interface or Class or Enum?
4. What is the use of Class.forname. What is the difference between Import and Class.forname?
5. What are the statements used for DB Operation?

Shailendra shail

unread,
Jan 5, 2012, 9:25:51 AM1/5/12
to newidea_or...@googlegroups.com
Question is having typo mistake :(

When you compile Class it makes .class file what happens when you compile Interface or Enum. If it is creating same then how it is identified that whether this is interface or Class or Enum?

Shailendra shail

unread,
Feb 7, 2012, 7:50:23 AM2/7/12
to newidea_or...@googlegroups.com
A link for java developer..

http://speedupjavacode.blogspot.com/


Dheeraj

unread,
Feb 7, 2012, 8:20:29 AM2/7/12
to newidea_or...@googlegroups.com
@shail : really cool sir :)

Thanks,

Dheeraj Bhushan

07845807559



---- On Tue, 07 Feb 2012 04:50:23 -0800 Shailendra shail<mr.shaile...@gmail.com> wrote ----

A link for java developer..

http://speedupjavacode.blogspot.com/


--
You received this message because you are subscribed to the Google
Groups "Technical Discussion" group.
To post to this group, send email to
newidea_or...@googlegroups.com
To unsubscribe from this group, send email to

Hari Mohan

unread,
Feb 7, 2012, 8:36:53 AM2/7/12
to newidea_or...@googlegroups.com
Hi Shailu,
 
1.We  can override jspInit() method in JSP and add the logic that should go to init() in Servlet.
 
2. Four classes will be created ,
    for eg,
   D,C and B in A
   hence,
   A.class,A$B.class,A$C.class and A$D.class.
 
3.I think, it still creates .class file !!!! Not Sure !!
 
4.Class.forName() is used to load a class into JVM.
 
 
-Hari Mohan
 
 

vivek joshi

unread,
Aug 31, 2012, 11:34:10 AM8/31/12
to newidea_or...@googlegroups.com
Null Pointer Exception ?

Shailendra shail

unread,
Aug 31, 2012, 11:43:50 AM8/31/12
to newidea_or...@googlegroups.com
Josi ..

Is this question or answer of any above question.. If so please specify the question and then answer ..otherwise put your question in detail...

On Friday, August 31, 2012 9:04:11 PM UTC+5:30, vivek joshi wrote:
Null Pointer Exception ?

vivek joshi

unread,
Aug 31, 2012, 11:48:07 AM8/31/12
to newidea_or...@googlegroups.com
oh...I just saw a question like
String a=null; if (a!=null && a.length()>10){...}              what happens if we replace && by &

so what I wrote was what I think would be the answer to this question. Am I right?

Shailendra shail

unread,
Aug 31, 2012, 12:03:46 PM8/31/12
to newidea_or...@googlegroups.com
You are absolutely right.. Very nice..

What is the output of following snap code

public static void main(String...arg){
  String a="java";
  String b="java4";
  String c="Java" + "4";
  String d=a+ a.length;

  System.out.println(b==c);
  System.out.println(b==d);

  System.out.println("a = " + a + ", b= " + b +", " + b==d);

Shailendra shail

unread,
Jan 25, 2013, 7:30:09 AM1/25/13
to newidea_or...@googlegroups.com
Hi All,
Look at the below code and tell me why the output is only Welcome?


public class Test{

  public static void main(String...arg){
     System.out.println(Pqr.str);
  }
}
class Pqr{
  public static final String str="welcome";
  static{
     System.out.println("world");
  }
}




On Saturday, February 5, 2011 5:35:12 PM UTC+5:30, Shailendra shail wrote:
Hi friend,

          Today i got few java interesting question. If you could give best answer.
  1. What is immutable class in java and how to create?
  2. How do you achieve multiple inheritance in java?
  3. What are the methods we can use to maintain session.

Neo

unread,
Jan 25, 2013, 8:01:36 AM1/25/13
to newidea_or...@googlegroups.com

This is a very tricky question. The points of confusion here are that the static initializer should fire whenever JVM needs to "Load" the class or Technically Resolve the class, and it should fire whenever we try to access a public static final class variable ( n this case str ).
But, here, JVM Does not need to "Resolve" the class or maybe even Load the whole class to know the value of welcome. JVM will ONLY load the class when an instance variable or a static method or an instance method is called ( lazy loading ).
Hence, the static initializer does not fire at that time... However , just add a simple method, and call it, and you can see, it is at "That" time that JVM decides it cannot do without loading the class into memory and hence, the static initializer is called in the following code->

public class Test{

  public static void main(String...arg){
     System.out.println(Pqr.str);
     Pqr.doSome();

  }
}
class Pqr{
  public static final String str="welcome";
  static{
     System.out.println("world");
  }
 public static void doSome() {
      System.out.println("hello world");
  }
}


public static final static members appear to be stored and access in a manner that is independent of a class reference by the JVM, and it makes sense too... As all they need is a namespace to qualify them, doesn't make sense for the classloader to bring the whole class to memory for a simple var access...









--
--
You received this message because you are subscribed to the Google
Groups "Technical Discussion" group.
To post to this group, send email to
newidea_or...@googlegroups.com
To unsubscribe from this group, send email to

Shailendra shail

unread,
Jan 25, 2013, 10:07:36 AM1/25/13
to newidea_or...@googlegroups.com

Seems answer is correct. But I am surprise that why does it happen when I have added final. Neo instead of creating other static method and call; you just remove final from above example. You'll get different output.

My doubt may silly but just want some more clarification about how jvm works.?

Neo

unread,
Jan 28, 2013, 3:37:58 AM1/28/13
to newidea_or...@googlegroups.com
If you remove "final" the JVM can no longer store it in its "quick access" pool, independent of the class. This is because, a non-final static var may be initialized through a static block, or anywhere else in the static part of the class.
Hence, when you try to access it, JVM cannot safely determine that the value of the variable will Never change, (as its not final). Hence, it has to load the class into memory and run the initializers to safely determine the value of that variable.
By Declaring it final, JVM optimizes the var for quick access without loading the whole class or without running the initializers.

Hope this helps.

Shailendra shail

unread,
Aug 19, 2013, 12:57:09 AM8/19/13
to newidea_or...@googlegroups.com
Since long time Interview questions has not been updated and I came across some interesting question for core java which is as below. Please put you comment either wrong or right. It will give us more idea and different view.

1. in String == is 3 times faster then .equals method, so will it be advisable to use intern method as mention below. Give reason for Yes/No
    String a="Hello World";
    String b=new String("Hello World");
    
    if(a==b.intern()){
       System.out.println("yes contents are equal");
    }

2. What is SCP (String Constant Pool) and when a String goes to this area. Will this be allowed to collect by GC?

3. What is Eden space and survivor space,  tenured generation, permGen and How GC move object from one space to another space. 

4. How to increase the size of permGen.

keep updating yourself. 
more questions are on the way... :)  

Neo

unread,
Aug 19, 2013, 1:44:53 AM8/19/13
to newidea_or...@googlegroups.com
Hi,

Here are my answers.
However my view on the questions here is that these are not core java questions but more of a JVM Implementation details category.
A Java "developer" does not need to know all this... while a JVM implementor does.

Regardless, here we go :D


On Mon, Aug 19, 2013 at 10:27 AM, Shailendra shail <mr.shaile...@gmail.com> wrote:
Since long time Interview questions has not been updated and I came across some interesting question for core java which is as below. Please put you comment either wrong or right. It will give us more idea and different view.

1. in String == is 3 times faster then .equals method, so will it be advisable to use intern method as mention below. Give reason for Yes/No
    String a="Hello World";
    String b=new String("Hello World");
    
    if(a==b.intern()){
       System.out.println("yes contents are equal");
    }

---- 
Its true that == will be very fast when compared to the .equals() method, but as it is with all good things, there is a cost associated with it.
a) JLS States that all String literals are automatically interned.
b) Interning "manually" by calling the intern() method is a costly process. ( remove from heap, mark for gc, create poo entry ... )
c) Interning a String created on the Heap ( and not in the SP ... more on this in next answer ) is stupid, and shouldn't be done. If you really wanted to use the == operator, just create them as string literal.

Keeping the above points in mind, I would answer the question in this manner...

The String Pool is NOT an infinite resource, but unless your program is VERY VERY VERY VERY big and runs in memory mostly, we have no reason to worry about the String Constant Pool being exhausted. 
So, for a vast majority of times, it is always good to use String Literals.
Using intern() manually -> No Sir, Bad Idea. I have only seen .intern() in legacy projects, and almost nobody uses it nowadays. ( cost involved )
On top of that, Let's say we have 10 strings each having "Shail" as their content. Creating them on the Heap i.e new String() will give you 10 diff objects, while the SCP intelligently optimizes this use case.


---- 

 
2. What is SCP (String Constant Pool) and when a String goes to this area. Will this be allowed to collect by GC?
-----
 I am not 100% sure, but I don't remember reading anything called the String "Constant" pool, however the JLS only mentions the String Pool. 
So, in my view SCP and SP are the same thing. The String pool is used to store String Literals too ( they hold value at compile time )  and hence, maybe the name SCP. But, there is no different memory area designated to storing string literals exclusively.

Having said that, whenever you declare a String literal, it is automatically interned and is stored in the String Pool. 
Strings from the string pool are not eligible for garbage-collection since JVM maintains a single reference to each unique String object from the String pool. Yes, I know the Documentation of .intern() makes one believe that they might be, but no.
I will not go into details of this right now, as it has to do more with the implementation of a JVM than Core Java. (Tell me if you need very very detailed explanation for this).
----- 

3. What is Eden space and survivor space,  tenured generation, permGen and How GC move object from one space to another space. 
----
  • Eden Space: The pool from which memory is initially allocated for most objects. (Heap Memory)

  • Survivor Space: The pool containing objects that have survived the garbage collection of the Eden space. (Heap Memory)

  • Tenured Generation: The pool containing objects that have existed for some time in the survivor space. (Heap Memory)

    This automatically explains how objects move from one space to another.

    And my favourite ;) PermGen :D

    Let me quote an OpenJDK-8 Implementor (dfa)

    "Non-heap memory includes a method area shared among all threads and memory required for the internal processing or optimization for the Java VM. It stores per-class structures such as a runtime constant pool, field and method data, and the code for methods and constructors. The method area is logically part of the heap but, depending on the implementation, a Java VM may not garbage collect or compact it. Like the heap memory, the method area may be of a fixed or variable size. The memory for the method area does not need to be contiguous.

    • Permanent Generation: The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas."

      I am sure everybody here, would have seen the OutOfMemory:Permgen Space error, ( there is another OutOfMemory: error, ... Java Heap Space) )

      Keeping the aforementioned definition of Permanent Generation ( PermGen ) space in mind, we can figure out the reason for it.

    ---- 


4. How to increase the size of permGen.

We need to set the following JVM Startup parameter -> -XX:MaxPermSize=256m
But PermGen Space cannot be more than the Heap Size ( i.e in Xmx param ).
 

keep updating yourself. 
more questions are on the way... :)  


On Saturday, February 5, 2011 5:35:12 PM UTC+5:30, Shailendra shail wrote:
Hi friend,

          Today i got few java interesting question. If you could give best answer.
  1. What is immutable class in java and how to create?
  2. How do you achieve multiple inheritance in java?
  3. What are the methods we can use to maintain session.

--
--
You received this message because you are subscribed to the Google
Groups "Technical Discussion" group.
To post to this group, send email to
newidea_or...@googlegroups.com
To unsubscribe from this group, send email to
newidea_or_techn...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/newidea_or_technical?hl=en
 
---
You received this message because you are subscribed to the Google Groups "Technical Discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to newidea_or_techn...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Shailendra shail

unread,
Aug 19, 2013, 2:56:17 AM8/19/13
to Technical Discussion
Wow. Very true. Awesome answer. 

Thanks a lot Neo. Even one more thank for informing "questions here is that these are not core java questions but more of a JVM Implementation details category" 
It's true but good to have this knowledge for java developer as some of us are unaware and goes blank when recruiter ask question related to this.

I would need some more clarity as you have stated that Strings from the string pool are not eligible for garbage-collection since JVM maintains a single reference to each unique String object from the String pool

can we say, internalized strings stay in the memory forever? 

I found a nice blog which have explained this with suitable example.   (Myth:3)


Note: Friends hope you all will have some comments, feedback, conflicts and concern. Please don't hesitate to ask if you have anything in mind. 

--
Shailendra Kumar shail

Neo

unread,
Aug 19, 2013, 3:25:34 AM8/19/13
to newidea_or...@googlegroups.com
All,

I would like to correct myself, when I said "Internalized Strings are NOT candidates for GC". While this remains true for older JVMs, ( hence the confusion ), it is no longer valid now.
In modern fragmented JVMs, Internalized Strings are indeed GC'ed, albeit in a different fashion.

This article explains it awesomely ... 

Shail : Your statement "internalized strings stay in memory forever" is no longer true, but it was true for Older JVMs. 

I would like to share a video for whoever is actually interested in some REALLY deep concepts of the JVM, Bytecode compilation/interpretation and stuff...  1hour 30 minute video, but worth the time.



ankurguptajpr

unread,
Jun 18, 2015, 7:40:16 AM6/18/15
to newidea_or...@googlegroups.com
 Hey friends 
its long time that I visited and posted here.

I have one question, need your views:

int i =0;

i++
sysout(i); ----> results 1

int i =0;

i = i++
sysout(i); ----> results 0  give full detailed understanding 

Shailendra shail

unread,
Jun 18, 2015, 8:06:37 AM6/18/15
to Technical Discussion

In the background, something like the following occurs:

int temp = i; // store current value of i
i = i + 1; // increase i because of i++
i = temp; // assign to i

This happens because with i++, first the value of i is evaluated and only then i is increased.

If you change it to ++i you get the following:
i = i + 1; // increment first
int temp = i; // store value of i
i = temp; // asign to i

This is because with ++i, first i is increased and afterwards its value is evaluated.

--
--
You received this message because you are subscribed to the Google
Groups "Technical Discussion" group.
To post to this group, send email to
newidea_or...@googlegroups.com
To unsubscribe from this group, send email to
newidea_or_techn...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/newidea_or_technical?hl=en

---
You received this message because you are subscribed to the Google Groups "Technical Discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to newidea_or_techn...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

vijay kumar

unread,
Jun 18, 2015, 8:14:54 AM6/18/15
to newidea_or...@googlegroups.com
Thank you guy's for raised question here. because I get refresh mind when i was trying to get answer .

Thanks shailendra for given nice explanation

Regards,
Vijay

 


Nishant

unread,
Jun 18, 2015, 8:16:03 AM6/18/15
to newidea_or...@googlegroups.com
What is 1.0/0.0 ?

Regards,

NISHANT GUPTA / Master of Computer Applications
8050041001/ ccsC...@gmail.com

Facebook Twitter Google Plus Linkedin

-- If you could reason with Religious people, there would be no religion.

Ankur Gupta

unread,
Jun 18, 2015, 9:03:38 AM6/18/15
to newidea_or...@googlegroups.com
Still not convincing.... this looks logically which is true.
But This is operator overloading that is being done.
So there must be some function that is getting called which should return the value at run time that is actually updating the value.
So if that is returning incremented value then it should give 1 but here is overriding its value. 
So my question how its actually taking place while execution.s

        Ankur Gupta         
==================
Beyond  The Out Thinking

Shailendra shail

unread,
Jun 18, 2015, 9:33:03 AM6/18/15
to newidea_or...@googlegroups.com, ankurg...@gmail.com
If you can understand below you will be able to judge 

i = 6;
System.out.println(i++); //6 (i = 7, prints 6)
or 

i = 6;
temp = i++
System.out.println(temp); //6 (i = 7, prints 6)
now replace temp with i :). 
moreover in java ++ is an operator(java doesn't support operator overloading) and it's having native implementation.


@Nishant
For your Questiong :answer is : infinity (Now you can better explain why it is so?

To unsubscribe from this group, send email to

For more options, visit this group at
http://groups.google.com/group/newidea_or_technical?hl=en

---
You received this message because you are subscribed to the Google Groups "Technical Discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to newidea_or_technical+unsub...@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

--
--
You received this message because you are subscribed to the Google
Groups "Technical Discussion" group.
To post to this group, send email to

To unsubscribe from this group, send email to

For more options, visit this group at
http://groups.google.com/group/newidea_or_technical?hl=en

---
You received this message because you are subscribed to the Google Groups "Technical Discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to newidea_or_technical+unsub...@googlegroups.com.

Nishant

unread,
Jun 18, 2015, 9:33:53 AM6/18/15
to newidea_or...@googlegroups.com, ankurg...@gmail.com
Answer is Double.INFINITY ;) 
and it does not throw ArithmeticException


Regards,

NISHANT GUPTA / Master of Computer Applications
8050041001/ ccsC...@gmail.com

Facebook Twitter Google Plus Linkedin

-- If you could reason with Religious people, there would be no religion.



To unsubscribe from this group, send email to

For more options, visit this group at
http://groups.google.com/group/newidea_or_technical?hl=en

---
You received this message because you are subscribed to the Google Groups "Technical Discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to newidea_or_techn...@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

--
--
You received this message because you are subscribed to the Google
Groups "Technical Discussion" group.
To post to this group, send email to

To unsubscribe from this group, send email to

For more options, visit this group at
http://groups.google.com/group/newidea_or_technical?hl=en

---
You received this message because you are subscribed to the Google Groups "Technical Discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to newidea_or_techn...@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

--
--
You received this message because you are subscribed to the Google
Groups "Technical Discussion" group.
To post to this group, send email to

To unsubscribe from this group, send email to

For more options, visit this group at
http://groups.google.com/group/newidea_or_technical?hl=en

---
You received this message because you are subscribed to the Google Groups "Technical Discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to newidea_or_techn...@googlegroups.com.

Shailendra shail

unread,
Dec 22, 2015, 6:39:21 AM12/22/15
to Technical Discussion
Hi Friends,

Today I got stuck in very basic SQL question. Can any one answer this?

If a table named country and it has only one column named cName. Write a SQL query to show all distinct matches between them. it must not be duplicate.
{ind, pak}, {pak, ind} are same.


Country:cName
===========
india
pak
sa
nz


Then result should be as below (row count fact(n-1) i.e : 6)
+---------+----------+
| team1 | team2 |
+---------+----------+
| pak    | india    |
| sa      | india    |
| nz      | india    |
| sa      | pak     |
| nz      | pak     |
| nz      | sa       |
+---------+----------+
 
Regards,
Shail

Nishant

unread,
Dec 22, 2015, 7:00:45 AM12/22/15
to newidea_or...@googlegroups.com
I currenly only have DERBY and it can be achieved in a single statement like...

select * from test_new a JOIN test_new b on a.cname<b.cname;

Cheers.

Regards,

NISHANT GUPTA / Master of Computer Applications
8050041001/ ccsC...@gmail.com

Facebook Twitter Google Plus Linkedin

-- If you could reason with Religious people, there would be no religion.


--
--
You received this message because you are subscribed to the Google
Groups "Technical Discussion" group.
To post to this group, send email to
newidea_or...@googlegroups.com
To unsubscribe from this group, send email to
newidea_or_techn...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/newidea_or_technical?hl=en

---
You received this message because you are subscribed to the Google Groups "Technical Discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to newidea_or_techn...@googlegroups.com.

Vivek Joshi

unread,
Dec 22, 2015, 7:01:24 AM12/22/15
to newidea_or...@googlegroups.com
One possible solution is :

select * from (select name from country asc) c1 inner join (select name from country asc) c2 where c1.name<c2.name


But there should be some better way of doing this. Anyone?


On Tue, Dec 22, 2015 at 5:09 PM, Shailendra shail <mr.shaile...@gmail.com> wrote:

--

Nishant

unread,
Dec 22, 2015, 7:02:31 AM12/22/15
to newidea_or...@googlegroups.com
Standard ANSI Sql.

select * from test_new a, test_new b where a.cname<b.cname; 



Regards,

NISHANT GUPTA / Master of Computer Applications
8050041001/ ccsC...@gmail.com

Facebook Twitter Google Plus Linkedin

-- If you could reason with Religious people, there would be no religion.


Shailendra shail

unread,
Dec 22, 2015, 7:40:56 AM12/22/15
to Technical Discussion
@Nishant, @Josi,

Perfect.
👍

Shailendra Kumar shail

vijay kumar

unread,
Dec 23, 2015, 1:04:36 AM12/23/15
to newidea_or...@googlegroups.com

Hi Shail
    
             Please try this query. it will be work 

create table country(cname varchar(100))

insert into country values('ind'),('pak'),('aus'),('nz'),('eng'),('rsa'),('sl')

SELECT t1.cname as team1,t2.cname as team2  FROM  country t1 INNER JOIN country  t2 ON  t1.cname > t2.cname;

Thanks &Regards,
Vijayakumar.R


--

Shailendra shail

unread,
Feb 11, 2016, 5:09:17 AM2/11/16
to Technical Discussion
What is wrong in below program? Any guess...
package com.shl.algo;

import com.shl.SNGLNode;

public class ReverseSinglyLinkedList {
 public static void main(String[] args) {
            SNGLNode root=new SNGLNode(10, new SNGLNode(20, new SNGLNode(2, new SNGLNode(5))));
            System.out.println(root);

             /* gives incorrect result */
            System.out.println(reverse(root));
            System.out.println(reverse(reverse(root)));
               
            /* gives correct result */
            SNGLNode reverse=reverse(root);
           System.out.println(reverse);
           System.out.println(reverse(reverse));

        }

        private static SNGLNode reverse(SNGLNode root) {
               SNGLNode curr=root;
            SNGLNode prev=null;
            SNGLNode next=null;
            while(curr!=null){
                     next=curr.next;
                curr.next=prev;
                prev=curr;
                     curr=next;
             }
              return prev;
   }
}

package com.shl;

public class SNGLNode {
      int info;
      public SNGLNode next;
      public SNGLNode(int info){
         this.info=info;
      }
      public SNGLNode(int info,SNGLNode next){
         his.info=info;
         this.next=next;
      }
      public int getInfo() {
         return info;
      }
      public void setInfo(int info) {
         this.info = info;
      }
      public SNGLNode getNext() {
         return next;
      }
      public void setNext(SNGLNode next) {
          this.next = next;
      }
      @Override
      public String toString() {
          return "[" + info + "] -> " + this.next;
       }
}

Ankur Gupta

unread,
Feb 12, 2016, 2:45:11 AM2/12/16
to newidea_or...@googlegroups.com
Your logic is somehow correct but when you change your current reference value that is changing your "root" value too.
After System.out.println(reverse(root)); root has value [10]-> null 
Hence reverse or reverse of ([10]-> null ) is [10]->null

What best you can do is clone root and then start using it in different call then it wont get impacted by function calls  

        Ankur Gupta         
==================
Beyond  The Out Thinking

--

Shailendra shail

unread,
Feb 12, 2016, 2:50:15 AM2/12/16
to newidea_or...@googlegroups.com

Nice catch ankur.. 👍

Nishant

unread,
Feb 12, 2016, 3:03:22 AM2/12/16
to newidea_or...@googlegroups.com
The whole point of linked list nodes is to not be associated/composed into each other...


Regards,

NISHANT GUPTA / Master of Computer Applications
8050041001/ ccsC...@gmail.com

Facebook Twitter Google Plus Linkedin

-- If you could reason with Religious people, there would be no religion.


Reply all
Reply to author
Forward
0 new messages