Beruflich Dokumente
Kultur Dokumente
Its secure, simple and robust, so with these attractive qualities in mind, here are some
facts about Java which you probably did not know
Another legend has it that Gosling and his gang of programmers went out to the local
cafe to discuss names and wound up naming it Java. There seems to be some truth in this
as the 0xCafeBabe magic number in the class files was named after the Cafe where the
Java team used to go for coffee.
The Duke
The Java mascot, The Duke was created by Joe Palrang. Palrang is the same guy who
has worked on the Hollywood blockbuster, Shrek.
4)final variable- the value of the variable cannot be changed once assigned
Everything! But nobody can know everything about Java - the subject is now too
vast. Imagine somebody saying that they know everything about every single
Microsoft product and technology. If someone like that calls me, I'm always out.
Introduction
String is one of the fundamentals of Java programming language. It's not a primitive
data type like int, long or double. It's defined in java.lang package and wrappers its
content in a character array.
In this post, we will discover some interesting String facts, that could help in
understanding better the behavior of this popular class.
1. String is Immutable
There is a powerful and simple concept in programming that is really underused:
Immutability.
Basically, an object is immutable if its state doesnt change once the object has been
created. Consequently, a class is immutable if its instances are immutable.
There is one killer argument for using immutable objects: It dramatically simplifies
concurrent programming. Think about it, why is writing proper multithreaded
programming a hard task? Because it is hard to synchronize thread accesses to resources
(objects or others OS things). Why it is hard to synchronize these accesses? Because it is
hard to guarantee that there wont be race conditions between the multiple write accesses
and read accesses done by multiple threads on multiple objects. What if there are no more
write accesses? In other words, what if the state of the objects threads are accessing,
doesnt change? There is no more need for synchronization!
Immutable classes are also well adapted to be key in hashtables. The objects on which the
hash values are computed must be immutable to make sure that the hash values will be
constant in time. Indeed, hash value is computed from the state of the object.
String is immutable. When you think that you are modifying a string, you actually
create a new string object. Often, we forget about it and we would like to write
Hide Copy Code
String str = "foofoo";
str.replace("foo", "FOO");
Of course, doing so comes at the cost of creating multiple string objects in memory
when doing some intensive string computation. In this case, you need to use the
StringBuilder class.
For some modern languages like Scala, immutability is preferred. The default collection
classes are immutable.
Lets analyse the JVM with JArchitect and search for its most popular types. For that, we
can use two metrics:
Type Afferent Coupling (TypeCa): which is the number of types using a specific class.
And heres the result of all popular types according to this metric:
As expected, Object is the most used one, however there's another interesting metric to
search for popular types: TypeRank.
TypeRank values are computed by applying the Google PageRank algorithm on the
graph of types dependencies. A homothety of center 0.15 is applied to make it so that the
average of TypeRank is 1.
Types with high TypeRank should be more carefully tested because bugs in such types
will likely be more catastrophic.
Heres the result of all popular types according to the TypeRank metric:
Using TypeRank metric which is more accurate to search for popular types, String is
more popular than Object in the JVM codebase.
3. String is Stable
Its recommended that the most popular code elements must be stable, indeed any
changes could impact many other types, lets discover if its the case of String, for that
we can compare the JVM 5 released in September 30, 2004 and the last update of JVM 7
released in October 15, 2013.
Added Methods
There are two ways to construct a string: implicit construction by assigning a string
literal or explicitly creating a String object via the new operator and constructor. For
example:
Java has provided a special mechanism for keeping the String literals in a so-called
string common pool. If two string literals have the same contents, they will share the
same storage inside the common pool. This approach is adopted to conserve storage for
frequently-used strings. On the other hand, String objects created via the new
operator and constructor are kept in the heap. Each String object in the heap has its own
storage just like any other object. There is no sharing of storage in heap even if two
String objects have the same contents.
You can refer to this post for more details about the String pool mechanism.
locale is used early in the method body, the JVM throws the
NullPointerException if a pointer is null and its very uncommon to throw
explicitly this exception. However many methods from String use this technique
to avoid executing more code in case of abnormal cases, which could minimize
the CPU usage.
If you execute the above program, you would find the following output:
This is a bit counter-intuitive at first, if you are from C/C++ background. Even if you
have defined two separate String object pointers / references to two different String of
same content, the pointers point to the same object.
/*
Edit 2: It won't be counter-intuitive for someone from PHP/Python/JavaScript
background, because == operator would compare the actual values of the string objects,
not memory references. However, it must be kept in mind, that in this case, it's happening
for a different reason.
In case of Java, they don't just evaluate to the same value, they point to the same darn
Object internally! Case in point, == operator is NOT overloaded in Java, unlike in other
languages. For more discussion about this, see the comment below by Philips George
John.
*/
Since, in Java, String is an immutable object, if your program uses two separate String
object pointers / references to point to exact same string value, internally, JVM allocates
only one String object reference. Not two or more. It keeps track of which String literal is
being referenced.
Let me add a few more, I can think off the top of my head:
1) String objects are immutable. Most String methods return another String, instead of
mutating the original String. So if you apply something like myString.toLowercase(),
it won't modify myString. If you want mutable String, use StringBuilder.
2) All Java classes have Object class as their parent. All Java classes inherit these
methods from Object class:
toString()
hashCode()
equals()
Sure, there are other methods a class inherits from Object class, but these are the most
important ones. System.out.println() would take up any object of any Java class, and
if it's not a primitive type, it would invoke the toString() method of the class. So, feel
free to override the default toString().
3) Run-time polymorphism is useful in Java. Say you are building an ArrayList of various
objects, some of which may or may not be of same class, but somehow linked by
inheritance - you can always instantiate an ArrrayList of super-class, and stuff all your
objects there.
Of course, when you retrieve them from ArrayList, you should do a typecast to the sub-
class, before calling any overridden or new methods on the object.
I use it as follows: I don't like typing down System.out.println() every time I want to
print out something at various check-points. So, I add this code-snippet at the top of my
Java class:
private static void log() {
System.out.println();
}
Now, in my Java code, I can just call log() with the argument, and I won't have to type
down anything. Run-time polymorphism takes care of all possible objects.
I created them as static methods, because I want to be able to call them from static as well
as non-static contexts.
/* Todo Something */
This is just a shorthand version, and what happens behind the scene is something similar
to this:
Iterator<MyClass> myIterator = myObjects.getIterator();
while(myIterator.hasNext()) {
MyClass myObject = myIterator.next();
/*Todo Something */
}
5) Always include a main() method in your Java class for being able to write unit tests.
Continuing with the car example, as you know the gear shift lever enables us to use the
transmission. Now it is a well-defined interface to the transmission. You as a user can
affect the transmission only by shifting the gears and not by doing anything else. Also
shifting gears will not affect anything else other than the transmission. Even in java
programs, a class (containing instance variables and methods) is defined in a way so that
they are wrapped or encapsulated. The other classes can access this class only through the
methods and so cannot arbitrarily change the value of the instance variables. This is
known as encapsulation.
#3: Inheritance
Dont give the example like you have inherited from your father. This might be true in the
real sense but this is not what the interviewer wants to listen from you. Instead, give a
better example of a class inheriting from another class. A good example will be that of
class Mammal which inherits from the class Animal. The Animal class is the super
class and Mammal class is the subclass. Mammals can do all the stuff that an animal can
do like eat, sleep and so on. Other than that a mammal can do some extra stuff which an
animal might not do like breastfeeding their children. Similarly, class Reptile inherits
from class Animal. Reptiles can do all the stuff that the Animal can do. Additionally, it
can crawl which an animal can not do. Another class Human inherits from the class
Mammal. Therefore Human can do both the Animal stuff as well as the Mammal stuff.
The pictorial representation is shown below.
Like the methods, the instance variables are also inherited from the super class to the
subclasses. A superclass can have 1 or more subclasses but a subclass can have only
one superclass. In Java extends keyword is used to implement inheritance.
class Animal {
public void eat() {
System.out.println("Animals eat");
}
}
class Mammal extends Animal {
public void breastFeeding() {
System.out.println("Mammals breastfeed");
}
}
Output :
Animals eat
Humans eat with their hands
Output:
Animals eat
Animals eat
Humans eat with their hands
In Dynamic method dispatch, Java decides at runtime which method to call depending
on the object being referred to and not on the type of the reference variable.
#5: Polymorphism
This is supposed to be the most favourite question of all interviewers. Dont reply with
many forms as this will not create a good impression on the interviewer. Ill continue
with the same Animal example. Let say there are two more classes Dog and Cat who
overrides the eat().
With polymorphism, the reference type can be a superclass of the actual object type.
This means the same Animal array can behave as Human, Dog as well as Cat. Now you
can state your definition of many forms to round it off. The earlier example also serves
as an example of polymorphism.
#6: Packages
This is not as frequently asked as the other questions. I remember when I was a kid I used
to collect different cards WWE cards, Pokemon cards and so on I kept them in
separate boxes so that they dont get mixed up. Similarly, similar classes are grouped
together and kept in packages. To define a package you need to write:
package MyNewPackage;
And that is it. Other than grouping, packages also provide with security. We can restrict
access to classes from other packages. To import another package in your program you
need to write:
import MyNewPackage.*;
As we can see that the Bat and Human class are subclasses of Animal. The eat() and
sleep() are defined in the Animal class and they are inherited in the Bat and Human class
but both the Bat and the Human sleeps in different ways. Bats, unlike Humans, sleeps
upside down. So there is no point in defining the sleep() in the Animal class itself. Then
we can make the method sleep() abstract. Abstract methods are methods without a
body. If a method in a class is abstract then that class should also be made abstract. So
the Animal class should also be made abstract along with the eat(). An abstract class can
never be instantiated. It means we can not create an object of the class Animal. It makes
sense too. We know how a Bat or a Human sleep but how does an Animal sleep?
Similarly, you can not instantiate an interface. One major difference between the two is
an Abstract class is extended but an interface is implemented. In Java, you can extend
from one class but you can implement multiple interfaces. The first non-abstract sub class
of the interface or abstract class must implement or override all the abstract methods.
TRY:
If a code is risky that doesnt mean you should not try it. Keep the risky code inside the
try block and relax.
CATCH:
If an exception is thrown then the exception is caught in the catch block. Usually, the
error is printed in the catch block to notify the user about the possible problem. For
example, if the file you are trying to access is missing you get a FileNotFoundException,
then you might want to notify the user about the problem.
FINALLY:
When an exception is thrown, the lines that follow the statement in the try block is not
executed. So in case, we want to execute certain statements whatever the outcome you
have to keep it in the finally block. The statements inside the finally block get executed
even when a statement in the try block throws an exception.
This example from HeadFirst Java explains the try catch finally block.
try {
turnOvenOn();
x.bake();
} catch (BakingException e) {
e.printStackTrace();
} finally {
turnOvenOff();
}
You have to turn off the oven even if your cake gets burnt and it throws a
BakingException. So you have to keep the turnOvenOff() in the finally block. If the
turnOvenOn() throws a BakingException then the statement x.bake() will not get
executed. The control will immediately fall to the catch block. Only when no exception is
thrown the whole try block gets executed. The finally block always get executed.
#10: Threads
The run() must contain the job what you want the thread to do. Then make an object of
the Thread class and pass an object of the MyRunnableClass in the Threads constructor.
class MyRunnableTest {
public static void main (String[] args) {
System.out.println("Inside main thread");
MyRunnableClass runnable = new MyRunnableClass();
Thread thread = new Thread(runnable);
thread.start();
System.out.println("Inside main thread");
}
}
Now just start the thread. It is interesting to know that main() is also run on a thread
which is started by the JVM. It is the starting point of any Java Application. As you go on
introducing more and more threads they will run independently and you can actually be
in two places at once.
The reality (as it always is) is much different, only a multiprocessor system can do more
than one job at the same time. Java threads actually appear to do several tasks at the same
time but actually, the JVM switches the threads so fast that they appear to execute
simultaneously. You can extend the answer by defining another method of creating a
thread but that is not necessary and most probably the interviewer will move on to the
next question by then.
With the 10 concepts in mind and the ways to answer the question, you are armed to
crack a Java interview. As much as possible avoid the definitions and go for the
examples. Use the E-P-D (Examples-Program-Definition) approach to answer the
questions, Definition being the most unimportant of the lot. Coming to the end of a long
tutorial there is just one thing to say good luck for the interview. If any of the
suggestions has helped you or you have any suggestions, do mention them in the
comments. If you like this post you might also be interested in 10 C programs for
technical interview.