Set - 3

Question 41 :

Can one create a method which gets a String and modifies it?

Answer :

No. In Java, Strings are constant or immutable; their values cannot be changed after they are created, but they can be shared. Once you change a string, you actually create a new object. For example:

String s = "abc"; //create a new String object representing "abc"
s = s.toUpperCase(); //create another object representing "ABC"


Question 42 :

Why is multiple inheritance not possible in Java?

Answer :

It depends on how you understand "inheritance". Java can only "extends" one super class, but can "implements" many interfaces; that doesn't mean the multiple inheritance is not possible. You may use interfaces to make inheritance work for you. Or you may need to work around. For example, if you cannot get a feature from a class because your class has a super class already, you may get that class's feature by declaring it as a member field or getting an instance of that class. So the answer is that multiple inheritance in Java is possible.


Question 43 :

What's the difference between constructors and other methods?

Answer :

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.


Question 44 :

What is the relationship between synchronized and volatile keyword?

Answer :

The JVM is guaranteed to treat reads and writes of data of 32 bits or less as atomic.(Some JVM might treat reads and writes of data of 64 bits or less as atomic in future) For long or double variable, programmers should take care in multi-threading environment. Either put these variables in a synchronized method or block, or declare them volatile.


Question 45 :

This class (IncrementImpl) will be used by various threads concurrently; can you see the inherent flaw(s)? How would you improve it?

Answer :

public class IncrementImpl { 
	private static int counter = 0; 
	public synchronized void increment() { 
		counter++; 
	} 
	public int getCounter() { 
		return counter; 
	} 
}

The counter is static variable which is shared by multiple instances of this class. The increment() method is synchronized, but the getCounter() should be synchronized too. Otherwise the Java run-time system will not guarantee the data integrity and the race conditions will occur. The famous producer/consumer example listed at Sun's thread tutorial site will tell more. 
one of solutions

public class IncrementImpl { 
	private static int counter = 0; 
	public synchronized void increment() { 
		counter++; 
	} 
	public synchronized int getCounter() { 
		return counter; 
	} 
}