Sie sind auf Seite 1von 22

Some interesting facts that all programmers should

know about Java


Java, the long-lasting programming language, remains immensely popular and for many
good reasons. In fact, many programmers swear by the stability of Java. Java is the go-to
language for millions of software developers. Java emerged as a tech juggernaut because
of its unique portability and its capability of operating similarly on any hardware or
operating system.

Its secure, simple and robust, so with these attractive qualities in mind, here are some
facts about Java which you probably did not know

Java was called Oak at the beginning


Original name for Java was Oak. Java legend has it that a big oak tree that grew outside
the developer James Goslings window. It was eventually changed to Java by Suns
marketing department when Sun lawyers found that there was already a computer
company registered as Oak.

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.

Java was invented by accident


James Gosling was working at Sun Labs, around 1992. Gosling and his team was
building a set-top box and started by cleaning up C++ and wound up with a new
language and runtime. Thus Java or Oak came into being

Its pays to learn Java


The median salary of a Java developer is $83,975.00. Yes, it pays to be a Java developer
and programmers are milking it. There are about 9 million Java developers in the world.

Java is second most popular language after C


Though many would argue that Java is all time favourite among developers, it is second
most popular programming language after C. Java is ranked #2 in popularity among
programming languages, according to the programming languages popularity tracking
website, tiobe.com.

JUnit Testing Framework


The JUnit Testing Framework is currently the top used Java technology. Its stability and
popularity can be deduced from the fact that almost 4 out of 5 Java developers or 70 %
developers out there used JUnit Testing Framework.

Java is the go to tool for enterprises


95 percent of enterprises use Java for programming. That is hell lot more than C and
other languages put together.

Current Java version


Javas latest major release is the Platform Standard Edition 8. Its features include
improved developer productivity and app performance through reduced boilerplate code,
improved collections and annotations.

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.

Java and Android


Java practically runs on 1billion plus smartphones today because Googles Android
operating system uses Java APIs.

Final is not final in Java


Final actually has four different meanings in Java.

1) final class- The class cannot be extended

2) Final method- the method cannot be overridden

3) final field- The field is a constant

4)final variable- the value of the variable cannot be changed once assigned

Here are some additional facts about Java


Java vs Google
Oracle is fighting a big courtroom battle with Google over the use of Java in Android
operating system. If Oracle wins the lawsuit, it stands to make a cool $8.8 billion. The
courtroom battle headed for second hearing recently after the federal court ruled in favour
of Oracle and told Google to approach district court for further ruling.

Top Ten Things Every Java Programmer Should Know


These are in no particular order, but these are things that all Java programmers should
probably know.

1. Who Invented Java, and when?


James Gosling, at Sun Labs, around 1992; the group was building a set-top box
and started by "cleaning up" C++ and wound up with a new language and
runtime.
2. What does Java stand for?
Java is not an acronym (not even Just Another Vague Acronym :-)). The language
was first named Oak, after the tree outside James' window. The lawyers found a
computer company called Oak so, legend has it, the gang went out to the local
cafe to discuss names and wound up naming it Java; the "0xCafeBabe" magic
number in the class files was named after the Cafe where the Java team used to go
for coffee.
3. What is the JLS?
JLS is The Java Language Specification. Every developer should buy or
download (free) this specification and read it, a bit at a time.
4. How do changes get into Java?
JCP (Java Community Process).
5. Why is there no printf-like function in Java?
Actually there are! This was fixed in Java 5; see Java Cookbook (2nd Edition)
Chapter 9. Java 5 (J2SE 1.5) includes printf (and scanf), String.format(), and lots
more.
6. What is the GOF book?
The Gang Of Four book is entitled Design Patterns, by Erich Gamma, Richard
Helm, Ralph Johnson and John Vlissides. This is a very good book. You should
read it. Not when you're just learning Java, but when you've let it sink in for about
six months.
7. What other Java book do I need?
o Most of the O'Reilly Java books.
o Effective Java, by Joshua Bloch
o Java Developer's Almanac
o My Java Cookbook (see below)
8. What is the Java Cookbook?
That's my own book of Java recipes (for the programming language, not the
coffee, but some bookstores still wind up listing it under Cooking).
9. What other Java sites do I need to know about?
o java.sun.com, Sun's main technology site
o java.net, a collaborative site (run by Sun)
o java.com, an advocacy/news site (run by Sun)
o developer.java.sun.com, Sun's main developer site
o www.javalobby.org, independent advocacy group
o www.javaworld.com, Java news
o www.theserverside.com, Java Review
o https://darwinsys.com//java/, my own Java site
10. What else do I need to know?

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.

5 Facts about the Java String

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

where we need to write instead:

Hide Copy Code


str = 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.

2. String is the Most Popular Class in the JVM


Its interesting to know the most used types in a project, indeed these types must be well
designed, implemented and tested. And any change to them could impact the whole
project.

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

Here are the methods added during 9 years:

Only 3 constructors and 5 methods was added.


Deprecated Methods

Only one constructor was deprecated since 2004.

4. String is Designed to Optimise the Memory Usage


Strings receive special treatment in Java, because they are used frequently in a program.
Hence, efficiency (in terms of computation and storage) is crucial.

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:

Hide Copy Code


String s1 = "Hello"; // String literal
Hide Copy Code
String s2 = new String("Hello"); // String object

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.

5. String is Designed to Optimise the CPU Usage


We can enumerate two cases of CPU optimisation:

Execute minimal of code whenever it's possible:


Lets take as example the toLowerCase(Locale locale) method, and here are
the first lines of its implementation:

Hide Copy Code

public String toLowerCase(Locale locale) {


if (locale == null) {
throw new NullPointerException();
}

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.

isEmpty instead of equals(): isEmpty was introduced in Java 6 which is


faster than equals(), because it simply compares the length of the string
which is stored in the String object with zero:

Hide Copy Code

public boolean isEmpty() {


return 0 == count;
}

What are the concepts every Java programmer must


know?
I will start with a simple one.

Consider the following code:


String s = "Arijit";
String t = "Arijit";
if (s == t) {
System.out.println("s and t point to same string");
}
else {
System.out.println("s and t point to different string");
}

If you execute the above program, you would find the following output:

s and t point to same string

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 the other languages I mentioned above, the == operator is overloaded to compute /


evaluate the entity on both sides, so it would result in s and t point to same string.

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

private static void log(Object a) {


System.out.println(a);
}

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.

4) The short-hand for-loop is shown below:


for(MyClass myObject : myObjects) {

/* 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.

That was all I could think of in a jiffy. If I recall more, I


would update this answer. I am open to others'
suggestions as well. I am relatively new to Java, and
others would know more than I do.
/*
Edit 1: As Burak Aktas mentioned in comments,
perhaps point 5 is not a good idea. Feel free to ignore
it.
*/

P.S.: In the interest of full disclosure, I work at Oracle.


Everything I have posted above, is my own personal
opinion, and not that of Oracle.

What are the top 10 things a beginner should definitely


know about Java?
1. Java is an Object Oriented Programming language
2. Java programs run on a special software called Java Virtual Machine
3. Java Virtual Machine is supported by many operating system, and this is what makes
Java cross-platforms, meaning that you can "write once and run anywhere"
4. To install Java Virtual Machine, you need to download and install Java Runtime
Environment (JRE)
5. However, to have tools to develop Java applications, you need to download and install
Java Development Kit (JDK). The lastest version is 8. If you download JDK, you don't
need to download JRE because it is already in JDK.
6. The most popular Java IDEs are Eclipse and Netbeans. Both are free.
7. With Java, you can build desktop applications, games, web sites, embedded systems.
Those can have versions on mobiles as well.
8. Java has 4 platforms:
Java Standard Edition: contains all core libraries and functionalities
Java Enterprise Edition: contains frameworks and libraries to build applications that
are used mostly in enterprises
Java Micro Edition: contains frameworks and libraries to build applications that runs
on micro devices like mobiles, tablets
Java FX: contains graphic libraries to build rich client applications that operate
consistently across diverse platforms
9. Most of the high layers in the famous mobile OS Android is build on Java, so learn
Java if you want to build android applications
10. The best source to learn Java is where it is invented: The Java Tutorials

What are the most important Java concepts a fresher


should master in order to compete for a Java
interview, and also become a good Java developer
later?

10 Java Concepts you must know before appearing for


technical interviews
There are a lot of questions that crawl into our minds a few days before the interviews.
You can bet this post will not answer any of those but it will surely help you revise with
the 10 java concepts you must know before appearing for a technical interview. The first
thing that you must know is that the interviewer is trying to know whether you
understand the concepts so mugging up definitions will not help. It is very important to
make the interviewer understand that you know how the concepts are inspired by real life
so it will be good for you if instead of stating a definition, you provide him with an
example and explain the concept in your own words. Even if you are giving him a
previously read example, state it as if you are making it up right at that moment. Also,
prepare a good programming example with every concept. This way it will help you get a
complete grasp of every concept and it will also increase your confidence level as you
will be better prepared to answer a lot of follow up questions. Click here if you want to
find out the 10 C programs frequently asked in interviews.

#1: Class and Object


Yes, I cheated a bit. There are actually more than 10 concepts but I wrote 10 as it sounded
better. Anyway coming back to the topic, you must be knowing what is class and object
but dont hurry to state the definition. Rather pause a bit and start out with an example.
All human beings belong to a class Humans. Both me and you are objects of the type
Humans. You can shamelessly state this example or give a better example but in either
case, dont let him know that you have previously prepared it. One good thing about this
example is that it involves the interviewer. This provides an additional feeling that you
made up the example at that moment. It can be best followed up with a small definition
such as A Class is a blueprint for an Object. The answer is not yet complete. Follow it up
with a program. If you are not provided with a paper, explain the program in your own
words. There is a class Dog which has an instance variable name and a method bark().
Now we create an object of the class Dog and assign a name tom to it.

Dog tom = new Dog();

An answer like this will definitely impress any interviewer.

#2: Abstraction and Encapsulation


As I told before start off with an example. I dont know why I just love the car example
from Herbert Schildt so I will give you that example here. Here is what you need to say
you see a car is a complex object with several thousand parts but we ignore the
complexity by ignoring the details as to how the cars internal mechanisms work together.
Instead, we know how to handle the steering, brakes, clutch and so on Even in the java
programs, we use several methods which are already defined. We just use them without
knowing what they actually do. This is known as abstraction.

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.

#4: Method Overriding


This is a popular follow-up question to inheritance. Again dont start with the definition.
Instead, control your urges and start out with an example. We use the previous example
where Humans inherit the eat() from Mammal and also from Animal. You see humans
does not eat like other mammals do, they use their hands to eat. So the contents of
Humans eat() will not be the same as Animals or Mammals eat(). So we can change the
contents of eat() in the Human class as per our requirement. This is known as method
overriding. Now whenever the eat() is called on a Human object, the newly defined eat()
in the Human class will be called not the previously defined Animals eat(). If you get a
pen and paper write a small program to illustrate it.

class Animal {
public void eat() {
System.out.println("Animals eat");
}
}
class Mammal extends Animal {
public void breastFeeding() {
System.out.println("Mammals breastfeed");
}
}

class Human extends Mammal {


//extends eat() from Animal
//overridden method
public void eat() {
System.out.println("Humans eat with their hands");
}
}

public class AnimalTest {


public static void main(String[] args){
Animal animal = new Animal();
animal.eat(); //will call the eat() of Animal class
Human man = new Human();
man.eat(); //will call the eat() of Human class
}
}

Output :
Animals eat
Humans eat with their hands

A common follow up question to overriding is Dynamic Method Dispatch. Again no


definition only examples. Rewrite the AnimalTest class to:

public class AnimalTest {


public static void main(String[] args){
Animal animal = new Animal();
Mammal mammal = new Mammal();
Human man = new Human();
Animal newAnimal = animal;
newAnimal.eat(); //will call Animal's eat()
newAnimal = mammal;
newAnimal.eat(); //will call Animal's eat()
newAnimal = man;
newAnimal.eat(); //will call Human's eat()
}
}

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().

Animal[] animals = new Animal[3];


animals[0] = new Human();
animals[1] = new Dog();
animals[2] = new Cat();
animals[0].eat(); //will call the Human's eat()
animals[1].eat(); //will call the Dog's eat()
animals[2].eat(); //will call the Cat's 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.*;

#7: Garbage Collection


Each time an object is created, Java allocates memory in a space called the Heap. As the
size of the heap is fixed, when more objects are created, free space will be needed to
create the new objects. Therefore old and unused objects must be removed from the heap.
This process is garbage collection and it is quite similar to the process how we throw
away the unused objects that are not used in our houses. But there is a difference between
the two. You decide what objects you want to throw out of the house but in this case,
Java Virtual Machine decides it for you. When the JVM sees that an object can never be
used again then that object is eligible for garbage collection. And then when you are
running low on memory, the Garbage Collector will run and remove all those
unreachable objects and free up space, so that new objects can be created. For example:

Dog d = new Dog(); //creates a new Dog object (say Object 1)


d = new Dog(); //creates another Dog object (say Object 2)

Now there is no reference variable which is pointing to Object 1. So Object 1 is eligible


for garbage collection. When the system will run low on memory, the garbage collector
will run and remove Object 1.

#8: Interfaces and Abstract Class


Lets start with an example. Here again, we consider the Animal example with a few
modifications.

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?

abstract public class Animal {


public abstract void sleep();
public void eat() {
//eat statements
}
}
And a 100% abstract class is an Interface. All the methods in an interface are abstract.
We could have made the Animal an interface if we made the eat() abstract as well.

public interface Animal {


public abstract void sleep();
public abstract void eat();
}

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.

#9: Exception Handling

In real life, there are certain things which have a


risk involved with it. We still try those things out even knowing the risk involved with it.
In case the risk turns into reality, we must know how to handle the problems. In Java, the
problem is the exception and the way we use the try/catch block to handle the exception
is Exception Handling.

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

Arent there times when you


have a lot of pending work and you wish that you can be in two places at once. Well, Java
allows you to be superman. You can actually be in two places at the same time, watch TV
while you are reading this article using java. But how? Here is where threads come into
the picture. Making a thread is very simple. There is a Java class Thread. Make an object
of the Thread class and start the thread. But what will the thread do if you do not mention
it? There are multiple ways to make a thread but here we will discuss only one way.
There is an interface Runnable which you have to implement in your class and override
the run() method.

class MyRunnableClass implements Runnable {


public void run() {
//write the thread's job here
System.out.println("Inside the new thread");
}
}

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.

Das könnte Ihnen auch gefallen