Kamis, 22 Januari 2015

Space Station Sunday: Spaceships That Pass In The Night

Good evening, space fans!  Here's what was up on the ISS this week...




The ISS exterior as of Valentine's Day, after two undockings.
(Image courtesy NASA.gov.)

Europe's "Georges Lemaitre" Automated Transfer Vehicle (ATV) was released from the station on Valentine's Day, carrying a payload of trash from the ISS.  The last in a series of five ATVs, the Lemaitre deorbited (a.k.a. burned up in a glorious fireball) in Earth's atmosphere today.  All together, these ATV missions ferried 34 tons of cargo to the ISS since 2008.  Next, the ESA plans to use their technology to help improve NASA's Orion spacecraft for future deliveries.


A beautiful exit for the ATV.
(Image courtesy NASA.gov.)

Earlier in the week, the SpaceX Dragon cargo craft also departed the station, but with a more prosperous outcome.  It landed on Tuesday off the coast of Long Beach, California and was rescued to obtain its full payload of completed scientific experiments as well as extraneous ISS items.


SpaceX founder Elon Musk tweeted this image, captioned, "Coming home."
(Image courtesy Elon Musk.)

Now that there's a little extra space up in our part of space, Russia plans to launch a Progress 58 resupply ship on Tuesday morning, which will reach the station on the same day.  The Progress 58 will deliver food, fuel, and supplies, despite a temperature of around 18 degrees in the launch zone.


A little snow is no match for a rocket!
The Progress 58 heads to the launchpad in Baikonur, Kazahkstan.
(Image courtesy NASA.gov.)

Meanwhile, back in space, the station looked lovely as ever on Valentine's Day, where pink lights aided an experiment on plant growth.

The ISS interior, showing some scientific love.
(Image courtesy NASA.gov.)
Do plants like mood lighting as much as humans?  Our astronauts intend to find out!
(Image courtesy Butch Wilmore / @AstroButch.)

As for other science of note this week, the ISS crew kept busy as usual.  In addition to preparing for the arrival of the Progress 58, they prepared for two upcoming spacewalks, conducted eye exams with the aid of Earth-based doctors, studied bioelectric cardiac activity, and even worked on new methods of detecting punctures where micro-meteoriods hit the outside of the station (because even small meteorites can do big damage when your ship is travelling at almost 5 miles per second!)

Finally, if you like seeing the ISS everyday but can't always bust out a telescope or a computer, NASA has released a downloadable 2015 ISS calendar packed with history, images, and even moon phases, to make your days on Earth a little more interesting. 

That's all for this week, space fans!  See you next Sunday with news from the Progress's progress!  Watch this space!

Even if you didn't have a Valentine yesterday, remember that Mother Earth still loves you.
More heartwarming Earthly images are available here.
(Image courtesy esa.int.)



Source:http://blog.agupieware.com/2015/02/space-station-sunday-spaceships-that.html

Dial-Up Diagnosis, Part II: Developing The "Sniffphone" App To Sense Cancer


Last week, we learned that HIV is now detectable via a cheap smartphone attachment.  Now, smartphones are getting even more diagnostically intelligent thanks to a new app that can identify cancer via a breath test...

According to Yahoo News, the new "Sniffphone" is in development by Israeli investors.  A simple breathalyzer-type test can detect gases in your breath that might be redolent of something more unpleasant than those fried seaweed snacks you insist don't smell that bad.  Micro and nano-sized sensors take inventory of the hundreds of gases in your breath and send the results to the app, which in turn sends them to a lab.

It rules your life in many other ways, it only makes sense that it would also monitor your health.
(Image courtesy techrj.com.)

With no X-rays or blood tests required, this could be a major medical stepping-stone into diagnostics for the masses.  And since early detection is key to stopping many cancers in their tracks, the phone app could go a long way towards protecting lives.  For those who already may be predisposed to cancer, accurate monitoring of the situation could add another layer of preventative care.

The Sniffphone app's creator, Professor Hossam Haick of the Technion-Israel Institute of Technology, explained the benefits of the invention, saying, "The Sniffphone will be made tinier and cheaper than disease detection solutions currently, consume little power, and most importantly, it will enable immediate and early diagnosis that is both accurate and non-invasive...Early diagnosis can save lives, particularly in life-threatening diseases such as cancer."

While not on the market yet, the project has received a $6 million Euro grant to continue research. According to NIH, more research is needed to make the perfect cancer app, but many have made strides in the field already. Incidentally, the gas-detecting technology used in the breathalyzer was originally invented to detect weapons and explosives. Perhaps in the near future, vigilance of our vapors will bring victory over even more medical villains.

Breathe easy, cancer-prone patients...soon the Sniffphone might be able to call for preventative help.
(Image courtesy scientificamerican.com.)


Source:http://blog.agupieware.com/2015/02/dial-up-diagnosis-part-ii-developing.html

Rabu, 21 Januari 2015

How to Find First and Last element in LinkedList Java - Doubly linked list



In this article you will learn how to get the first and last element of a linked list with the help of getFirst() and getLast() of LinkedList class. If you have programming or even gone to computer science course you probably know what is a linked list? It's a data structure which allows you to store objects in a such a way that you can don't need a big chunk of contiguous memory like another popular data structure array. It work perfectly even if you have a fragmented heap. LinkedList is Java's implementation of this fundamental data structure. There are two types of linked list, singly and doubly linked list, and Java's LinkedList is a doubly linked list. If you are wondering what is difference between a singly and doubly linked list, well in singly linked list you can traverse only in one direction from head to tail, or from first to last element because every node has address of only next node. While in doubly linked list, every node has reference to both previous and next node, thus allows you to traverse in both direction, from head to tail and backwards. You can verify this by yourself by looking at code of java.util.LinkedList in Eclipse, just use shortcut Ctrl + T and type the name, if you have added Java source code in Eclipse, it will open the class. You will find that LinkedList has a private static class called Node, which has reference to both previous and next node.





For those, who can't see the code of LinkedList, here is the snippet of Node class.



private static class Node {
E item;
Node next;
Node prev;

Node(Node prev, E element, Node next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}



You can clearly see that Node has reference to two other nodes, which makes LinkedList a doubly linked list and allows you to traverse in both direction, from first to last and vice-versa.






Getting First and Last Element of LinkedList in Java


Here is our sample Java program to find first and last object from LinkedList in Java. We will be using Java's Collection framework API to get our done. In this example, I have create a  linked list of String to store different programming language.  You can store objects into LinkedList by calling add() method. This method encapsulate data into a private static nested class Node, which represent a node in doubly linked list and keep reference of both previous and next node in linked list. Also this method adds the new element at the end of linked list i.e. on tail, which means last method you add into linked list will be the last element in the LinkedList itself. The angle bracket you see while creating instance of LinkedList is known as diamond operator, added backed in Java 7 and help you to avoid declaring types on right hand side of assignment operator as well. Compiler can now infer it by looking at left hand side. You should use it every time you are using JDK 1.7 to reduce at least a little bit of boiler plate coding.




Doubly linked list in Java







Now coming back to our task, how do we retrieve the first and last element from linked list? Of course we don't know which elements are added, unlike this example, where we know. Since linked list is a sequential data structure, by looking at how you add element you can guess which one is first and which one is last, but this example is more for situation, where you receive a linked list from other part of your application and need to find first and last element.



LinkedList has getFirst() and getLast() method to retrieve first and last element from LinkedList in Java. I would have liked just first() and last() method but anyway.



import java.util.LinkedList;

/**
* Java program to find first and last element of linked list in Java.
*/

public class LinkedListDemo{

public static void main(String args[]) {

LinkedList programmingLanguages = new LinkedList<>();
programmingLanguages.add("Java");
programmingLanguages.add("Perl");
programmingLanguages.add("Ruby");
programmingLanguages.add("Python");
programmingLanguages.add("C");
programmingLanguages.add("C++");
programmingLanguages.add("C#");
programmingLanguages.add("Scala");

// getting first element of linked list in Java
String first = programmingLanguages.getFirst();
System.out.printf("First element of LinkedList is : %s %n", first);

// getting last element from linked list in Java
String last = programmingLanguages.getLast();
System.out.printf("Last element of LinkedList is : %s %n", last);
}

}

Output:
First element of LinkedList is : Java
Last element of LinkedList is : Scala



That's all about how to find first and last node of a linked list in Java. Remember, Java's implementation of linked list data structure is a doubly linked list, which means each node has reference to both previous and next node. You can iterate over LinkedList but iterator doesn't guarantee any order, so beware of that as well.



If you are hungry to know more about linked list in Java, check out these amazing articles :


  • What is difference between LinkedList and ArrayList in Java? (answer)

  • How to find middle element of linked list in Java? (solution)

  • What is difference between array and linked list in data structure? (answer)

  • How to find if linked list has loop in it? (solution)

  • How to find length of singly linked list in Java? (solution)

  • Difference between List, Set and Map in Java? (answer)

  • When to use LinkedList over ArrayList in Java? (answer)

























Source:http://javarevisited.blogspot.com/2015/02/how-to-find-first-and-last-element-of.html

&quot;Like&quot; After Death: Leave A &quot;Legacy Contact&quot; To Manage Your Facebook Postmortem

Like millions of people the world over, perhaps you enjoy reporting the diverse details of your life on Facebook.  But what about...after?  What happens to your e-life when your real one is over?  Better find someone very trustworthy to handle your e-estate...



Rest in PC.
(Image courtesy sickchirpse.com.)

As PC Life reports, there is a new option to harangue people with your selfies, even from beyond the grave (hopefully the selfies were taken pre-demise, otherwise something creepy is going on.)  No, they've not figured out how to update from the afterlife ("OMG, sooo hot here, WTF is with these pitchforks?  -feeling HOT :P")  It's a new Facebook feature called your "legacy contact."

Your legacy contact is like the executor of your will, except only limited to to your Facebook e-existence.  Since 2009, Facebook has allowed pages for the deceased to become memorial pages, but now, should your death occur in an untimely manner where you were unable to share your password, your legacy contact can handle all of your profile traffic.

No, not that legacy.  If you were uploaded to a computer, you could update your profile from the Grid.
(Image courtesy disney.wikia.com.)

Timeline announcements, covers, profile pics, new friend requests, and other things that you personally would have been able to edit or like are now in the hands of your trusted associate.  They don't call it a "legacy" for nothing...you want to make sure your curator is a close confidante.  However, this person won't be able to post as you, nor will they be able to see your private messages.  If you truly trust your contact, an archive of your profile including photos and posts can be downloaded from your account.  You know, in case someone wants to make a book of all your awful haiku or "artistic" brunch photos.

Fruits of earth orbit
sunny-side-up sustenance...
Full life, full belly.
(Image courtesy observer.com.)

You can freak the hell out of your favorite roommate, or give your Valentine a weirdly endearing mission, or just otherwise classify your legacy contact on Facebook by going into the "Security" settings and choosing "Legacy Contact."  An option to send a message is also included, which you'll probably want to use if you've not yet spoken about this with the person to whom you are entrusting your e-eternity.

Of course, if you're more of a scorched-earth type, you can now also tell Facebook to kill off your profile as soon as you've shuffled off the mortal coil.  But who'd want to do that?  Don't you want your choices in stupid cat videos to live on forever?

Modern man dies thrice:  when his heart ceases to beat, when his name is spoken for the last time,
...and when his social media account is deleted forever.
(Image courtesy shamusyoung.com.)


Source:http://blog.agupieware.com/2015/02/like-after-death-leave-legacy-contact.html

Difference between Right shift and Unsigned right shift in Java ( &gt;&gt; and &gt;&gt;&gt; )



There are two types of right shift operator in Java >> and >>>,  former is known as right shift and later is known as right shift with zero fill or simply unsigned right shift operator in Java.  Though both of them are known as bit shift operators and moves bits patterns towards right hand side of a bit sequence, there is subtle difference between them. When we use right shift operator i.e. ">>" it keeps sign bit intact i.e. if original number is negative then it will remain negative even after right shift i.e. first or most significant bit never lost, doesn't matter how many times you shift. On the other hand unsigned right shift operator ">>>" doesn't preserve sign of original number and fills the new place with zero, that's why it's known as unsigned right shift operator or simply right shift with zero fill. Since Java represent negative numbers as 2's complement and all of its integral data types except char is signed, it's very important to remember this subtle difference between signed and unsigned right shift operator. This also means that negative numbers in Java has first or most significant bit (the left most) set, i.e. 1, while for positive number this bit is always zero. All these confusions will remain until you see an example of right shift operator and do it by yourself, so what are we waiting for, let's jump into an example.








Right Shift Operator Example in Java -  >> vs >>>


When we use right shift operator to shift bits, the right most bit of a signed number is lost and a new bit is added on left most position. If number is negative, then right shift operator i.e. >> adds 1 into left most position, otherwise it adds zero, as shown in below example :



// Using right shift operator with negative number in Java
int number = -2;
System.out.println(number);
System.out.println("Before shift : " + Integer.toBinaryString(number));

number = number >>
1; //shifting 1 right bit

System.out.println(number);
System.out.println("After shift : " + Integer.toBinaryString(number));


Output:
-2
Before shift : 11111111111111111111111111111110
-1
After shift : 11111111111111111111111111111111



If you look at carefully, here we are shifting only one bit using right shift operator (number >> 1), which means 0 at left most position from binary representation of -2 will be lost (marked with red color). Remember, int primitive is a 32 bit variable in Java and that's why we are seeing 32 bits here. From output you can see that right most zero is lost and a new bit with value 1 is added into left most position (marked with blue). Why 1? because it's a negative number and its MSB or sign bit is 1. Since >> preserves sign, it is also known as right shift with sign extension.


Difference between signed and unsigned right shift operator in Java





If we repeat same example but with unsigned right shift operator >>> in Java then we will see a different result, because >>> operator doesn't preserve sign and always adds zero into left most position. Here is an example of unsigned right shift operator in Java :



/**
* Java Program to demonstrate difference between singed right shift ">>"
* and unsigned right shift operator ">>>" in Java
*
* @author Javin Paul
*/

public class RightShiftWithoutSignDemo{

public static void main(String args[]) {

// Using unsigned right shift with negative number in Java
// we can use binary literals from JDK 1.7 to assign
// binary values to an integer, 0b is for binary, similar to 0x of hexadecimal
int number = 0b1111_1000_1111_1010_1111_1000_1111_1010;

System.out.println("Before unsigned right shift : " + Integer.toBinaryString(number));
System.out.println("number in decimal format : " + number);

number
= number >>> 1; //shift 1 bit using right shift without sign

System.out.println("After unsigned right shift : " + Integer.toBinaryString(number));
System.out.println("number in decimal format : " + number);

}

}

Output :
Before unsigned right shift : 11111000111110101111100011111010
number in decimal format
: -117769990
After unsigned right shift : 1111100011111010111110001111101
number in decimal format
: 2088598653



You can see clear difference in the output of signed and unsigned right shift operator in Java. Behavior of right shift operator is predictable as divide by two but that's not true for right shift with zero fill operator i.e. >>>, because it can change a negative number into positive one.



By the way, when you run this program in Eclipse, you may think that unsigned right shift operator ">>>" is not working properly because you will see that sign bit is still "1", well I did until I see the decimal output which denotes a positive number. Then I carefully investigated bit pattern and find out that after shifting we only have 31 bit, because Integer.toBinaryString() has not printed leading zeros. Since it took me some time to realize I have highlighted this fact by color coding bits in a group of four, you can see in output the first group has only 3 bits because leading zero is not printed.



Now let's see how these two operator works with positive numbers in Java. As per theory, since positive number's sign bit is always zero, both of these operators should produce same result.



/**
* Java Program to demonstrate difference between singed right shift ">>"
* and unsigned right shift operator ">>>" in Java
*
* @author Javin Paul
*/

public class BitShiftDemo{

public static void main(String args[]) {

// Using right shift and unsigned right-shift with positive number in Java
// we can use binary literals from JDK 1.7 to assign
// binary values to an integer, 0b is for binary, similar to 0x of hexadecimal
int a = 0b10000;
int b = 0b10000;

System.out.println("Before applying unsigned right shift ('>>>'), a : " + a);
System.out.println("Before applying right shift ('>>'), b : " + b);

a = a >> 1; //shift 1 bit using right shift with sign extension
b = b >>> 1; //shift 1 bit using right shift without sign

System.out.println("After applying unsigned right shift ('>>>'), a : " + a);
System.out.println("After applying right shift ('>>'), b : " + b);

}

}
Output
Before applying unsigned right shift ('>>>'), a : 16
Before applying right shift ('>>'), b : 16
After applying unsigned right shift ('>>>'), a : 8
After applying right shift ('>>'), b : 8



You can see in output that for positive input both ">>" and ">>>" produces same output, which is also logical because sign bit for positive integers in Java is always zero. So right shift operator preserves sign bit and keep positive number as positive.





That's all about difference between right shift and unsigned right shift operator in Java. Right shift ">>" keeps the sign extension while shifting bit patterns, but right shift without sign doesn't keep the original sign bit intact, it fills with zero. Which means after using ">>>" a negative number can turned into positive number. For positive inputs, both signed and unsigned right shift will produce same result but for negative numbers they will produce different result. Also remember, ">>" is equal to divide by 2 e.g. ">> 1" will divide number by two, ">>2" will divide number twice by two e.g. by 4. It is well known fast way to divide a number by two in Java.




If you want to know more about magic of bitshift and bitwise operator in Java, You will find following articles interesting too :


  • How to Swap Two Number without using Temp variable? (solution)

  • How to check if an Integer is power of Two in Java? (solution)

  • How to count number of Set bits (1s) in Java Integer? (solution)

  • What is difference between bitwise and logical operator in Java? (answer)

  • How to add two numbers without using arithmetic operator? (solution)

  • How to check if a number is even or odd in Java? (solution)


























Source:http://javarevisited.blogspot.com/2015/02/difference-between-right-shift-and.html

Get Loopy: Elon Musk&#39;s Hyperloop Poised To Revolutionize Transportation

Elon Musk has been on fire lately.  Two wild dreams of his - the SpaceX private aerospace company and Tesla motors - have overcome tremendous adversity to become useful, sustainable, forward-thinking modern businesses.  Now, Musk is about to hit the futuristic trifecta: his supersonic vacuum-tube transport device, the Hyperloop, is poised to become a reality . . .



Swoop out with the 'Loop out.
(Image courtesy capitalbay.com.)

On paper, it almost seems like something out of a video game.  Large tubes stretching across the land (initially slated for trials in California) would shoot passengers from, say, Los Angeles to San Francisco, speeding along at 750 miles per hour, dwarfing other forms of transportation and indeed, revolutionizing the way we think about all travel across the vastness of America.  That L.A.-San Fran skip?  20 minutes.  New York City to Philly?  Barely enough time for you to update your social media that you're heading in, Hyperloop-style.

Though it is still in the planning stages, as Forbes reported today, the Hyperloop is official.  Musk's team at Hyperloop Technologies have the funds, the brains, and the support both public and political to create these high-tech hamster tubes for humans.  Referred to by Musk as "the fifth mode" (of man-made transport, after boats, trains, motor vehicles, and planes), the Hyperloop would have the speed of a plane, a price point lower than a train, and no emissions to further perturb our environment.

Musk also said that if the Concorde, a railgun, and an air hockey table had a three-way,
the Hyperloop would be its love child.   Seriously.
(Image courtesy redorbit.com)

Much like Japan's famed maglev trains, the Hyperloop works via a series of continuously-placed linear induction motors, which create a "magnetic river" to propel the payload.  Travelling in a near-vacuum, the Hyperloop vehicles will experience little drag, and will require lesser maintenance than other forms of transport.  A giant compressor fan on the front of the vehicle pushes air away from the nose, enabling the tremendous speed:  zero to 750 m.p.h. in under a minute.

While Musk is busy making SpaceX and Tesla the best they can be, one of his close associates, Brogan BamBrogan, is slated to head the test construction of a Hyperloop track.  BamBrogan, a brilliant aerospace engineer who worked closely on SpaceX's flagship Falcon and Dragon projects, became interested by the project due to its capacity to improve many aspects of the shipping trade.  Should the project be a success on land, an underwater "cargoloop" might even be feasible across oceans.

An artist's rendering of buoys helping to anchor undersea Hyperloop tunnels.  We hope there'll be windows.
(Image courtesy forbes.com.)

Questions and prospective problems abound.  For one, the speed might not be tolerable to all passengers.  Cities would currently have difficulty supporting a new form of transport entering their turf.  And the large amount of power required is more than arrays of solar panels can handle - making coal a likely candidate for some of the power.  Yet, the Hyperloop team isn't dissuaded, because they plan to rely on ingenuity...as BamBrogan says, "I need to hire people who are really good at figuring out what they don't know."

This is the future, and some of our greatest minds are happy to be surging ahead into the hyper-unknown.  For an American transportation system whose methods date back hundreds of years now, it's time for an upgrade (we love you, railroads, but this is just much more intelligent.)  On top of the extreme functionality, there's another critical element to the Hyperloop hype:  this is innovation made massively manifest, and that is very, very inspiring.  If our entire transportation system can be so vastly improved, what else in our lives could stand to be razed and replaced with the realities that we now only dream can happen?

Or as Hyperloop Tech board member Peter Diamandis puts it, “It’s time to stop doing photo apps and start doing something for the planet."

In winter, the Hyperloop could get you safely and quickly from Manhattan to Maine for a nice ski day
...no shoveling required!
(Image courtesy forbes.com.)


Source:http://blog.agupieware.com/2015/02/get-loopy-elon-musks-hyperloop-poised.html

Selasa, 20 Januari 2015

Do Androids Dream Of Electric Sheep? Farmers And Internet Enthusiasts Do...For Their Wi-Fi

Like it or hate it (although you probably still secretly like it, at least a little bit), the internet is a major force in modern human life.  Yet we hyper-connected humans continue to forget that there are wide swaths of this planet that slip through the net of the World Wide Web.  Some propose to remedy this with signal-beaming satellites, or even drones, but now, a new and ecologically-interesting idea has manifested: using sensors placed on animals to spread connectivity.  Can we turn a herd into a hotspot?

It's about time we replaced the old dial-up style of sheep.
(Image courtesy marilynstevens.com.)

According to The Atlantic, some scientists are seriously into the idea.  Placing wi-fi sensors on animals like sheep or even reindeer could allow them to traverse rural areas (for reindeer, to venture further beyond where many humans are comfortable living) and spread the signal.  In addition to helping the information superhighway get a few more on-ramps, it could allow farmers to monitor things like pollution, flooding, or even keep tabs on the flock themselves (e-shepherding!)  This type of technological exploration could expand not only our knowledge of the natural world, but also expand all knowledge for the far-flung residents therein.

Thanks to the vastness but also relative modernity of Australia, experiments with such sensors are now being carried out there with sheep.  The small sensors, which are embedded in ear tags and are light enough not to perturb the animal, can operate independently but can also help form mesh networks.  This kind of rudimentary internet also serves to spread information (as the sensors "talk" to each other to recognize their presence and location) and can operate as a whole even if singular elements fail (because wild dogs often do some non-technological sensing of their own for a sheep-snack.)

This could be one big fuzzy mesh network.
(Image courtesy news.bbcimg.co.uk.)
Greg Cronin, an Australian professor of animal welfare, explained that such attacks on sensor-bearing sheep could improve the hardships of shepherding, theorizing, â€œIf you could pick the right sensor that identified behaviors that changed when sheep were under attack, it could trigger an alarm for the farmer.” While the technology is still undergoing trials, Cronin was enthusiastic about its eventual results. “We know we can do it but we still have to do the hard work to prove it,” he said.  According to the BBC, the idea has gained traction in rural Wales as well, including sensors that would be placed on inanimate set locations (such as rivers) to improve knowledge of overall farm conditions.

So, maybe your toaster isn't able to Tweet yet, and perhaps your pet piranha isn't getting far enough away to require a tracking device.  But for this early inception of the Internet Of Things (well, Internet Of Creatures, at least), man and beast might be able to share information in harmony.  Just don't give the sheep options to upload selfies every time they get a haircut.

"@BleatBox - Looking mad fly today.  Hit me up on Tinder."
(Image courtesy fr.pinterest.com.)




Source:http://blog.agupieware.com/2015/02/do-androids-dream-of-electric-sheep.html

Constructor vs Init method in Servlet - JEE Interview Question



Can we have Constructor in Java Servlet? or Why do we need constructor in Servlet if there is already an init() method for initializing Servlet, or what is difference between init() method and constructor in Servlet are couple of questions I have seen in various Java web developer interviews. All of these questions are related to role of constructor and init() method in Servlet implementation class. Though I had shared few thoughts on this, when I wrote top 10 Servlet questions for Java programmers,  I thought to cover it in more detail here. In this article, I will try to answer each of these question in detail. Key thing to remember is that Servlet are special in the sense that their life cycle is managed by web container like Tomcat and Jetty. They are responsible for creating instances of Servlet and destroying them when they don't have enough resource or need to support so many instances of Servlets. Let me first answer the question, Can we create constructor in Servlets? and then I will answer why you should be using init() method for Servlet initialization by describing difference between constructor and init() method.






Can we define Constructor in Servlet?


Short answer of this question, Yes, Servlet implementation classes can have constructor but they should be using init() method to initialize Servlet because of two reasons, first you cannot declare constructors on interface in Java, which means you cannot enforce this requirement to any class which implements Servlet interface and second, Servlet require ServletConfig object for initialization which is created by container as it also has reference of ServletContext object, which is also created by container.



Servlet is an interface defined in javax.servlet package and HttpServlet is a class and like any other class in Java they can have constructor, but you cannot declare constructor inside interface in Java. If you don't provide an explicit constructor than compiler will add a default no argument constructor in any Servlet implementation class. Another reason that you should not initialize Servlet using constructor because Servlets are not directly instantiated by Java code, instead container create there instance and keep them in pool. Since containers from web servers like Tomcat and Jetty uses Java Reflection for creating instance of Servlet, presence of no argument constructor is must. So, by any chance if you provide a parametric constructor and forget to write a no argument constructor, web container will not be able to create instance of your Servlet, since there is no default constructor. Remember Java compiler doesn't add default no argument constructor, if there is a parametric constructor present in class. That's why it's not advised to provide constructor in Servlet class. Now let's see some difference between Constructor and init method in Java Servlet










Difference between Constructor and init method in Servlet


In real world application, you better use init() method for initialization, because init() method receives a ServletConfig parameter, which may contain any initialization parameters for that Servlet from web.xml file. Since web.xml provides useful information to web container e.g. name of Servlet to instantiate, ServletConfig instance is used to supply initialization parameter to Servlets. You can configure your Servlet based upon settings provided in ServletConfig object e.g. you can also provide environment specific settings e.g. path of temp directory, database connection parameters (by the way for that you should better leverage JNDI connection pool) and any other configuration parameters. You can simply deploy your web application with different settings in web.xml file on each environment. Remember, init() method is not chained like constructor, where super class constructor is called before sub class constructor executes, also known as constructor chaining.




Can Servlet define constructor in Java





That's all on this post about difference between constructor and init method of Servlet. We have seen that container uses web.xml to get Servlet's name for initialization and uses Java Reflection API, primarily class.newInstance() method to create instance of Servlet, which means Servlet class must need a default no argument constructor. We have also seen that why Servlet cannot have user defined constructor, mainly because Servlet as interface cannot guarantee it and web container creates instance of Servlet and has access to Context and Config object which is not accessible to developer. Always prefer init() method for initializing Servlet than constructor, because ServletConfig object is supplied to init() method with configuration parameters.






If you like this Java Web developer Interview question and hungry for more don't forget to check following questions as well :


  • What is difference between Struts 1 and Struts 2 MVC framework? (answer)

  • What is difference between forward() and sendredirect() method? (answer)

  • How to avoid double submission of form data in Servlet? (answer)

  • What is load-on-startup tag do in web.xml? (answer)

  • What is JSESSIONID in Java Web application? (answer)

  • How many bean scope is available in Spring framework? (answer)

  • Difference between Setter and Constructor injection in Spring? (answer)

  • What is difference between Web and Application Server? (answer)

  • Difference between GET and POST HTTP request? (answer)

  • What is difference between URL encoding and URL Rewriting? (answer)

  • Difference between include directive and include action in JSP? (answer)

  • How to define application wide error page in JSP? (answer)

  • What is difference between ServletConfig and ServletContext? (answer)

  • How to escape XML metacharacters in JSP? (answer)


























Source:http://javarevisited.blogspot.com/2015/02/constructor-vs-init-method-in-servlet.html

Moon Loot! Neil Armstrong&#39;s Widow Finds Stashbag Of Apollo 11 Parts

It's not uncommon to have elements of your job wind up following you home...maybe some pens from the office, a cupcake from the bakery, or a limited-edition craft brew bottle from the bar (or maybe two.)  But recently, a whole new level of work-treasure was unearthed (unmooned?) when Neil Armstrong's widow discovered a cache of original Apollo 11 equipment...stowed in a bag at the back of a closet.

"Time to conquer the moon.  But first, a selfie."
Armstrong, pictured near some of the power cables found in his moon-stash.
(Image courtesy NASA.gov.)

As reported by gizmodo.com, the amazing and historically rich find had been either forgotten or kept a secret by Armstrong, who died in 2012.  His wife Carol reported the find to Alan Needell, the curator of the Apollo collection at the Smithsonian Air And Space Museum, and it was instantly recognized to be of "priceless historical value", according to NASA.

Known as the "McDivitt Purse", the bag was a readily-available container kept accessible inside the lunar Eagle module, where it was used to keep small parts from floating away in micro-gravity.  "The Purse" was named for Apollo 9 commander Jim McDivitt, who had emphasized the importance of a stowable bag for for the front of the spacecraft.  The one-of-a-kind collection is now being prepared for display by the Smithsonian.

Allen Wrench?  Maybe on Earth.  Offplanet, that's the door key to a moonship!
(Image courtesy NASA.gov.)

Inside, all manner of Apollo artifacts had been preserved by Armstrong.  Power cables, hand tools, a valve cover, a mounting bracket, and other everyday-type items were in the collection, but the crown jewel of the space stuff was a 16-mm film camera (plus accessories!) that was used to record the descent of the Eagle onto the surface of the moon.

The original Apollo 11 footage (left) as compared to footage from the modern unmanned LRO (Lunar Reconnaissance Orbiter.)  Because moon movies are always awesome. 

Also present was a safety strap that was photographed in use for Buzz Aldrin's EVA ("Extravehicular Activity"...a common term for astronauts, which in this case specifically meant WALKING ON THE FREAKING MOON.)  You know...so he wouldn't get too excited in that 1/6th gravity and just bounce away.

Buzz Aldrin, rocking the waist tether on descent from the Eagle.  Just moon things.
(Image courtesy gizmodo.com.)

By the way, if you swoon for some moon, you can check out the LRO's sharp, zoomable moon imagery right here.  Thanks to NASA, more info on the overall LRO project, which is run from the Goddard Spaceflight Center in Maryland, can be found here.  Take your own lunar recon voyage from the comfort of Earth!

Sure, it may just be an orbiting chunk of rock that's mostly comprised of what Buzz Aldrin called "magnificent desolation"...but it's OUR chunk of orbiting rock.  And in an age where we can use a smartphone (that contains more computing power than the Eagle had) to check out close-up snaps of a celestial body, it's cool to recall that even some small steps like helmet straps, power cables, and bits of hardware were critical to making that "giant leap for mankind" come to pass.

One small stash for a man...
(Image courtesy gizmodo.com.)


Source:http://blog.agupieware.com/2015/02/moon-loot-neil-armstrongs-widow-finds.html

How to Implement linked list in Java with JUnit test Example



In this article we will learn two things, how to implement linked list from scratch in Java and how to write unit test using JUnit framework. Though Java has LinkedList class, which is implementation of doubly linked list, its good to know how to implement singly linked list in Java, mostly to practice coding interview questions. Coming to back to writing unit test, from time to time, I have said that a Java programmer must write unit tests. IMHO, unit testing is the best development practice to improve code quality. Fortunately Java eco system has luxury of great unit testing frameworks in form of JUnit and TestNG, and every Java developer should take advantage of this. Writing unit test is one of the best programming practice along with code review. It's natural and I had experienced it myself that unit test, not only provides code coverage, but also present unique opportunities for code refactoring. Many times, while writing unit tests, I have discovered better names for my methods and refactored large methods into smaller ones. JUnit tests also helps to organize code and evaluate encapsulation. There is a good chance of you discovering that a particular field or method is exposing implementation detail, and should be abstracted in public method. What all this means is, you, a Java developer, must write unit tests. Since it always helps to start smaller, this JUnit tutorial will present another simple JUnit example to show how to write unit test in Java. In this JUnit tutorial, we will implement linked list in Java and we will write unit test cases for linked list. For those, who are not familiar with linked list, it's one of the fundamental data structure to store objects, like array, which is also use to store object. By the way, there are many difference between linked list and array data structure, which is subject of another blog post, but main difference is in the way objects are stored. array needs contiguous memory, while linked list doesn't need that.








Basics of linked list data structure in Java


Before writing an implementation of linked list data structure, let's revise some terminology. There are two kinds of linked list, singly and doubly linked list. Singly linked list allows you to traverse in one direction, mostly forward, while doubly linked list allows you to traverse in both direction, forward and backward. Since we will implement a singly linked list, we will keep discussion limited with that. linked list store data in form of nodes, which contains data and reference to next node. First node of linked list is called head and last node is called tail. A linked list is said empty if it doesn't contain any node i.e. head points to null. In this JUnit tutorial, we will create a singly linked list with three methods isEmpty(), length() and append(). As name suggest isEmpty() will return true, if linked list is empty, length() will return number of nodes in linked list, and append() is used to append a node at tail. After that, we will write unit tests for this linked list class. By the way, here is a good example of how singly linked list look like :






Singly Linked List Implementation in Java


/**
* A Simple linked list implementation in Java to demonstrate unit testing.
* JUnit tests will be created to test this singly linked list.

* @author Javin Paul
*/

public class SinglyLinkedList {
private Node head; // Head is first node in linked list

public boolean isEmpty(){
return length() == 0;
}

public void append(String data){
if(head == null){
head = new Node(data);
return;
}
tail().next = new Node(data);
}

private Node tail() {
Node tail = head;

// Find last element of linked list known as tail
while(tail.next != null){
tail = tail.next;
}
return tail;

}

public int length() {
int length = 0;
Node current = head; // Starts counting from head - first node
while(current != null){
length ++;
current = current.next;
}
return length;
}


// Node is nested class because it only exists along with linked list
// Node is private because it's implementation detail
private static class Node {
private Node next;
private String data;

public Node(String data) {
this.data = data;
}

@Override
public String toString() {
return this.data;
}
}
}



When you run these unit test as shown here, you will see following output, which is self explanatory. Had any test failed or an error occurred e.g. an unexpected exception, JUnit would have shown that in this output.



Testsuite: SinglyLinkedListTest
Tests run: 1, Failures: 0, Errors: 0, Time elapsed: 0.828 sec


Simple JUnit Example - Unit test for Linked List in Java



Now, there are couple of approaches to write Unit tests in Java. Some programmer prefer to write unit test based on functions e.g. testAppend(), testIsEmpty() or testLength(), and this is also default approach used by IDE like Netbeans and Eclipse. By the way, you can also combine small tests into a complete one, by testing use cases e.g. testing a fresh linked list without any element, testing a linked list with some elements etc. In this JUnit example, I have combined test of all three methods into one. Though it's not complete, but it test one use case. You can still add more test cases to test append() with different input e.g. null. Any way let's have a look at our JUnit test case.



import org.junit.Test;
import static org.junit.Assert.;

/**
* JUnit test cases for linked list data structure in Java.
* This class has just one method to test behavior of a newly created linked list
*
* @author Javin Paul
*/

public class SinglyLinkedListTest {

@Test
public void testNewLinkedList(){
SinglyLinkedList singly = new SinglyLinkedList();
assertTrue(singly.isEmpty()); // linked list should be empty
assertEquals(0, singly.length()); // length of linked list should be zero

singly.append("ABC");
assertFalse(singly.isEmpty()); // linked list should not be empty
assertEquals(1, singly.length()); // length of linked list should be 1

}
}



I have just kept one method testNewLinkedList(), annotated with @Test annotation. This is the minimum requirement for writing unit test for Java programs. of course you can use other JUnit 4 annotations like @Before, @After, @BeforeClass or @AfterClass to do some setup and cleanup work, for this JUnit example, we don't need that. If you notice, I have also put comments around tests to make test cases more obvious, One of the code comment best practice to follow while writing unit tests. You can use this example to further learn writing unit test, I would suggest implement few more methods like delete() and start writing test cases for that. Working with linked list not only helps you to understand unit testing better, but also improves your data structure concept, as linked list forms a good chunk of data structure interview questions.





That's all on this simple JUnit example of implementing singly linked list in Java and writing unit test using JUnit. Follow the principle of  start small and improve step by step. In order to develop unit testing habit, you can also create empty test method, while understanding requirement and coding, and mark them with @Ignore annotation, to avoid failing tests. Just like coding, unit testing is also an art, which gets better with practice and constant improvement.



If you love unit testing and You will also fined following Java Unit testing Tutorials useful :


  • 5 Great books to Learn JUnit and Unit testing in Java (list)

  • JUnit best practices for Java Programmers (best practices)

  • How to test exceptions in JUnit 4? (solution)

  • What is difference between Mock and Stub object? (answer)

  • JUnit testing tips - Constructor is called before executing test methods (tips)

  • What is difference between Maven, ANT and Jenkins? (answer)

  • 10 tips to become a better Software Programmer (tips)

  • Why Static code analysis is Important? (opinion)

























Source:http://javarevisited.blogspot.com/2015/02/simple-junit-example-unit-tests-for-linked-list-java.html