Day: November 27, 2015

Java interview questions

Category : Java Programming

The Toptal Engineering Blog has published a great post called
8 Essential Java Interview Questions” on there you can submit your Java interview questions, answers and hire freelancers,
and they were happy to share with us these questions. If you would like to like them on Facebook click on the link Toptal on Facebook
8 Essential Java Interview Questions
Click on the question to see the answer

The main distinction between fail-fast and fail-safe
iterators is whether or not the collection can be modified while it is being iterated.
Fail-safe iterators allow this; fail-fast iterators do not.


Of the three, LinkedList is generally going to give you the best performance. Here’s why:

ArrayList and
Vector each use an array to store the elements of the list.
As a result, when an element is inserted into (or removed from) the middle of the list, the elements that follow must all be shifted accordingly.
Vector is synchronized, so if a thread-safe implementation is
not needed, it is recommended to use ArrayList rather than Vector.


In Java, Strings are immutable
and are stored in the String pool. What this means is that, once a String is created, it stays in the pool in memory until being garbage collected.
Therefore, even after you’re done processing the string value (e.g., the password), it remains available in memory for an indeterminate period of time thereafter
(again, until being garbage collected) which you have no real control over. Therefore, anyone having access to a memory dump can potentially extract the sensitive data and exploit it.


A single ThreadLocal
instance can store different values for each thread independently. Each thread that accesses the get() or set() method of a
ThreadLocal instance is accessing its own, independently initialized copy of the variable. ThreadLocal i
nstances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or transaction ID).
The example below, from the ThreadLocal Javadoc,
generates unique identifiers local to each thread. A thread’s id is assigned the first time it invokes ThreadId.get() and remains unchanged on subsequent calls.

public class ThreadId {
			// Next thread ID to be assigned
			private static final AtomicInteger nextId = new AtomicInteger(0);
				// Thread local variable containing each thread's ID
			private static final ThreadLocal<Integer> threadId =
				new ThreadLocal<Integer>() {
					@Override protected Integer initialValue() {
						return nextId.getAndIncrement();
				}
			};

			// Returns the current thread's unique ID, assigning it if necessary
			public static int get() {
				return threadId.get();
			}
		}
		


In Java, each thread has its own stack, including its own copy of variables it can access.
When the thread is created, it copies the value of all accessible variables into its own stack. The volatile
keyword basically says to the JVM “Warning, this variable may be modified in another Thread”.

In all versions of Java, the volatile keyword guarantees global ordering on reads and writes
to a variable. This implies that every thread accessing a volatile field will read the variable’s current value instead of (potentially) using a cached value.

In Java 5 or later, volatile reads and writes establish a happens-before
relationship, much like acquiring and releasing a mutex.

Using volatile may be faster than a lock, but
it will not work in some situations. The range of situations in which volatile is
effective was expanded in Java 5; in particular, double-checked locking now works correctly.

One common example for using volatile is for a flag to terminate a thread. If you’ve started a thread, and you want to be able to safely interrupt it from a different thread, you can have the thread periodically check a flag (i.e., to stop it, set the flag to true). By making the flag volatile, you can ensure that the thread that is checking its value will see that it has been set to true without even having to use a synchronized block. For example:

public class Foo extends Thread {
		private volatile boolean close = false;
		public void run() {
			while(!close) {
				// do work
			}
		}
		public void close() {
			close = true;
			// interrupt here if needed
		}
	}
	


sleep() is a blocking operation that keeps a hold on the monitor / lock of the shared object for the specified number of milliseconds.

wait(), on the other hand, simply pauses the thread until either (a) the specified number of milliseconds have elapsed or
(b) it receives a desired notification from another thread (whichever is first), without keeping a hold on the monitor/lock of the shared object.

sleep() is most commonly used for polling, or to check for certain results, at a regular interval. wait() is generally used in
multithreaded applications, in conjunction with notify() / notifyAll(), to achieve synchronization and avoid race conditions.


Here is an example of a typical recursive function, computing the arithmetic series 1, 2, 3…N. Notice how the addition is performed after
the function call. For each recursive step, we add another frame to the stack.

public int sumFromOneToN(int n) {
	  if (n < 1) {
		return n;
	  }

	  return n + sumFromOneToN(n - 1);
	}
	

Tail recursion occurs when the recursive call is in the tail position within its enclosing context –
after the function calls itself, it performs no additional work. That is, once the base case is complete,
the solution is apparent. For example:

public int sumFromOneToN(int n, int a) {
	  if (n < 1) {
		return a;
	  }

	  return sumFromOneToN(n - 1, a + n);
	}
	

Here you can see that a plays the role of the accumulator – instead of computing the sum on
the way down the stack, we compute it on the way up, effectively making the return trip unnecessary,
since it stores no additional state and performs no further computation. Once we hit the base case, the work is done – below is that same function, “unrolled”.

public int sumFromOneToN(int n) {
	  int a = 0;

	  while(n > 0) {
		a += n--;
	  }
	  
	  return a;
	}
	

Many functional languages natively support tail call optimization, however the JVM does not. In order
to implement recursive functions in Java, we need to be aware of this limitation to avoid
StackOverflowErrors. In Java, iteration is almost universally preferred to recursion.


This can be done using Thread.UncaughtExceptionHandler.

Here’s a simple example:

// create our uncaught exception handler
	Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
		public void uncaughtException(Thread th, Throwable ex) {
			System.out.println("Uncaught exception: " + ex);
		}
	};

	// create another thread
	Thread otherThread = new Thread() {
		public void run() {
			System.out.println("Sleeping ...");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				System.out.println("Interrupted.");
			}
			System.out.println("Throwing exception ...");
			throw new RuntimeException();
		}
	};

	// set our uncaught exception handler as the one to be used when the new thread
	// throws an uncaught exception
	otherThread.setUncaughtExceptionHandler(handler);

	// start the other thread - our uncaught exception handler will be invoked when
	// the other thread throws an uncaught exception
	otherThread.start();
	


The Ten Commandments

Category : 1956

The 1950’s was a decade home to many epics. Perhaps one of the best ones produced was 1956’s The Ten Commandments. This film fits the definition of an epic very well. It will fill you up with awe, with amazement, and with wonder due to the use of gigantic set pieces, colorful costume designs, a bombastic score, and storytelling that many of us know about (especially if you’re from Christianity or Jewish heritage). The film runs at a lengthy three hours and forty minutes, which is common for epics during the golden age of epics. Despite the lengthy film, I felt the movie had a good pace to it. It did not seem like a long movie, and I was almost disappointed when the credits appeared. When that happens in a 3+ hour film, you know you have a good film on your hands.

This film is based off historical events or to be more specific, the tale of Moses from his birth to his death. In Ancient Egypt, Pharoah Ramses I decreed all newborn Hebrew males shall die. However, a newborn male named Moses (Charlton Heston) was cast away in the Nile in a reed basket. He was saved by pharaoh’s daughter, Bithiah (Nina Foch), and he grew up in court of the pharaoh’s brother, Seti (Cedric Hardwicke). Moses made a name to himself and became a favorite to take the throne after Seti. But once Moses’s heritage is revealed, everything changes. Moses is cast from Egypt, where he marries and raises a family. He is commanded by God to return to Egypt so he can free the Hebrew people from slavery. However, Seti’s son, Rameses (Yul Brynner) does all he can to stop Moses.

There are just many scenes in the movies to goggle at. I am very impressed on how the story was told, and I can understand why the movie became a classic. Some of my favorite scenes are the parting of the Red Sea, where Moses splits the Red Sea so his people can cross the sea and be saved from Rameses, who was chasing them down. Another powerful scene I loved was when Yahweh was speaking to Moses on the top of Mount Sinai, issuing Moses the Ten Commandments while all his people were sinning at the base of the mountain. Just seeing God as a ball of fire, speaking with a commanding holy voice gave me the chills. Despite this being a film released in 1956, I believe the special effects hold up fairly well. The parting of the Red Sea is incredible, and it is amazing how that scene was done without the use of any CGI.

I have previously reviewed a movie from Cecil B. DeMille, which was released nine years previously in 1947 called Unconquered. That movie showed DeMille had a good hand in making entertaining epics. He really succeeds on the grand scale, as proved by the success of this film. The acting was also consistent and everyone seemed to have a fun time. Sometimes the acting would be downright silly, but there is no denying the fun the cast had. Charlton Heston is no stranger to epics, and I loved his performance here as Moses. Maybe towards the end when he becomes a whole new person he got a little silly, but overall he did a good job. Yul Brynner is good as Moses’s fiercest rival, Rameses, He created a memorable villain, who feels betrayed by his father that he would give power to Moses and not him. Anne Baxter does a good job as Nefretiri who was Mose’s love interest. Baxter did good, but sometimes her seductiveness would feel out of place in the film. Finally, I must mention Edward G. Robinson as Dathan, the man who was in charge of the slaves. I felt he gave a light, comedic touch to a man in what otherwise would be a sinister character.

Overall, The Ten Commandments is a great epic that holds up very well, nearly sixty years after its original release. The film does justice to the story, as told in the Bible. It’s obvious the film takes a stance against slavery, and its fun to see Moses outdo Rameses, The special effects are pretty cool, but get ready to be blown away by the Red Sea scene. This sweeping epic is a grand, fun movie. Not only does it enlighten people on the story of Moses and what he did for his people, but it also is fun, silly, and entertaining. The movie does a little into stretching the imagination, but its fun to watch and one of the best epics of all time.

My Grade: A


On the Waterfront

Category : 1954

https://www.youtube.com/watch?v=xSImMMMf5nA

“You don’t understand! I coulda had class. I coulda been a contender. I coulda been somebody instead of a bum, which is what I am.”

Ah, the earnest dialogue spoken by Marlon Brando in one of the most famous scenes in the history of cinema. Brando sitting in the taxi with his brother, Charley (Rod Steiger) trying to explain his reasoning why he opposes Johnny Friendly, Hoboken’s most powerful man with a gun pointed to his face. This scene is so earnest, so powerful, delivered perfectly by Brando, who does fantastic by showing a sweet, gentle side to his nature despite performing the tough-guy act. As the great critic Roger Ebert quotes, “What other actor, when his brother draws a pistol to force him to do something shameful, would put his hand on the gun and push it away with the gentleness of a caress?”

Before we get too much ahead of ourselves, I should at least point out this movie I’m reviewing is On the Waterfront, arguably one of the greatest movies ever made. It is special in many ways, but it is unanimously praised in how it changed the landscape of acting. The casting of Marlon Brando helped dearly. He changed how things were in a film. He made acting less predictable and did things never done before in cinema. He provided such texture to his role and in each scene he is in, you can see how he manages the line between gentleness and tough-guy act. Director Elias Kazan made a point not only Brando’s acting was better than most, it was also more influential than most. He brought such a tenderness to his character and he won Best Actor at the Academy Awards in 1954, which he wholeheartedly deserved.

I really found the plot interesting, and there is actually truth behind the plot. Terry Malloy (Marlon Brando) is a young man who tends to his pigeons and works on the docks for a corrupt boss of the unions, Johnny Friendly (Lee J. Cobb), while he dreams to be a boxer. One day, he witnesses a murder committed by some thugs of Friendly’s. Terry becomes close with the sister of the victim, Edie Boyle (Eve Marie Saint) because he feels responsible for her brother’s death. She introduces him to Father Barry (Karl Malden) who attempts to have Malloy take a stand against Friendly in order to smash the racketeering.

As I mentioned in the above paragraph, this film is based off some truth. The film has an obvious political agenda, based off the HUAC (House Un-American Activities Commission) hearings. The director, Elia Kazan was called to the committee, and he named names. Names who were affiliated with the Communist Party. Critics have commented in the past that this film may have hidden, political motives, because of what he did at those HUAC meetings. I actually believe the film is based off that, but I applaud him in making the film. No one should be afraid to state what they believe in. Another part of history is the longshoremen of the Hoboken docks. Hoboken had trouble in all its racketeering, so that all plays an influential part in the movie.

The main role of any director is to get the best performances he can out of his actors. Well, Kazan was certainly up for the task in this film. Everyone churned in amazing performances. I already gave my love letter to Brando, who previously worked with Kazan in 1951’s A Streetcar for Desire. The film could have turned out to be very different. Frank Sinatra was originally cast as Terry, but the producers went ahead to cast Brando instead. The best move they could have done. This is Eve Marie Saint’s first film role, and she eagerly rises for the challenge. A perfect foil for Brando. Her scene with Brando in the bar as they talked about feelings for each other is another priceless cinematic scene. Another important role was Rod Steiger, who played Terry’s brother, also mixed up with Friendly. That taxi scene was incredible, as Brando and Steiger had amazing chemistry. Despite opposite views, the brothers very much love each other. Karl Malden as Father Barry does a wonderful job, although it feels like his acting is overshadowed by the heavyweights. Finally, Lee J. Cobb as the union boss, Friendly does an excellent job. I loved his final scenes of the movie. His fate is very deserving, and without spoiling much, I was laughing in the face of Friendly’s as the movie came to a close.

Overall, this is just one incredible film. If you were to say that this is the best film of all time, I would have no issue with that. This is one of my favorites , and it’s one of those few films I can find no fault with. From the masterful direction to the skilled direction to the expert  cinematography, there is much to love about the film. This was nominated for twelve Oscars and won eight of them. Brando and Saint took home awards and so did Kazan as director. Cobb, Malden, and Steiger were all nominated. This gripping crime thriller should be a showcase for film professors everywhere. This film changed the perspective of acting and it changed American acting for the better. The film and the muckraking articles that inspired it brought light to crime in the Hoboken streets and perhaps those streets became cleaner in the immediate aftermath. If you love movies, check this film out.

My Grade: A+


Dial M for Murder

Category : 1954

If you are looking for a well-crafted thriller to enjoy, look no further than Alfred Hitchcock’s 1954 masterpiece, Dial M for Murder. On the outside, nothing much seems to happen with the film, but once you see it, well you are in for a surprise. As Hitchcock films goes, this one is more off-beat. However, you can classify the film as one of best films of the legendary director’s career.

If you look at the film from the outside, you are wondering how on earth is this film even good. For starters, most of the film is located in a single apartment room save for exterior shots and a scene at a theater. You need a well-crafted screenplay for single-location movies to work. Also outside of one rather fantastic murder scene, most of the film is talk, talk, and more talk. But this film does work because everyone plays their cards right. The screenplay is well-crafted and despite all the talk, it creates an aura of tension and mystery which builds up over the course of the film, before we reach the shocking ending. The build-up is excellent and it is very much worth it when the end is revealed.  I also like that despite the movie being located in one room 98% of the time, you never get that feel of unintentional claustrophobia. So thanks to the excellent screenplay by Frederick Knott and masterful direction by Alfred Hitchcock, you never really think about that one location.

Now it’s time to describe the plot of the movie, which takes place in London. The wealthy Margot Mary Wendice (Grace Kelly) had a brief love affair with an American author named Mark Halliday (Robert Cummings). Her husband, Tony (Ray Milland), a professional tennis player, was away from home at the time on a tour. However, he quits tennis because he wants to spend more time with Margot, and help a marriage that is crumbling apart. One day, Mark decides to visit the couple from America. During the affair, Mark had written letters to Margot. She insists she destroyed them all, but one letter was stolen. She claimed she was blackmailed, but she never really thought much about that letter. When Tony arrives home, he insists Mark and Margot go to the theater, and he will arrive shortly thereafter. However, he ends up calling an old colleague, Captain Lesgate (Anthony Dawson). Together, they plot the murder of his wife so he can gain her fortune. But complications arise in the form of failed opportunities, the police led by Chief Inspector Hubbard (John Williams), and Tony trying to constantly cover his footsteps so he will not be implicated in any wrongdoing.

Here is a film that is a masterpiece when it comes to delivering acting skills. Ray Milland injects his character with an incredible amount of charm, and his character is often likable even if his motives are not. His simple charm was enough to win me and many, many people over, enough to believe how he would do nothing wrong. Grace Kelly is absolutely magnificent in her role as Margot. During the murder scene, her performance was enough for me to wish she was nominated for an Oscar, which sadly enough she wasn’t. These were the two main attractions of the movies, but there was another great performance to point out. John Williams (no, not the legendary composer), has been a staple of Hitchcock movies, so it is no surprise for him to show up here. I really loved his finesse role as the police detective who figures out this case, piece-by-piece with a remarkable eye.

Hitchcock is one of Hollywood’s most famous auteurs. When one think of his works, usually The Birds, Vertigo, Rear Window, or, Psycho comes to mind. But never count out this underrated film. During the first phase of 3-D phase in the 40’s and 50’s, many films were subjected to 3D treatment. However the faze begin to die out in the mid 1950’s, and this is the last film to use 3D during that phase. I did not have the opportunity to watch the movie in 3D, but it could have been cool. For those who watch Hitchcock films, you should be familiar with him appearing in his movies somehow, someway. In Dial M for Murder, you’ll really have to search to find him and it’s a genius move to see where you’ll find him.

Overall, Dial M for Murder is just pure, classic Hitchcock. It’s one of his underrated films, but there is no denying it is a masterpiece. The premise is a simple one, but Hitchcock turned into a twisting tale that pierces the heart with a load of dread and thrills. It’s a very captivating movie, not only from the direction, but also from charming performances from Milland and Kelly, whom characters are likable. The film is good at talking, but you should be good at watching. I highly recommend this fine thriller that has Hitchcock in top form.

My Grade: A


Free Android Games

Free Android Games
Free fun Android Games

Check out our formulas section