Posts Tagged ‘Java’

* Q1. How could Java classes direct program messages to the system console, but error messages, say to a file?


A. The class System has a variable out that represents the standard output, and the variable errthat represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:


Stream st = new Stream(new FileOutputStream(“output.txt”)); System.setErr(st); System.setOut(st);


* Q2. What’s the difference between an interface and an abstract class?


A. An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.


* Q3. Why would you use a synchronized block vs. synchronized method?


A. Synchronized blocks place locks for shorter periods than synchronized methods.


* Q4. Explain the usage of the keyword transient?
A. This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).

* Q5. How can you force garbage collection?



A. You can’t force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.


* Q6. How do you know if an explicit object casting is needed?


A. If you assign a superclass object to a variable of a subclass’s data type, you need to do explicit casting. For example:


Object a; Customer b; b = (Customer) a;

When you assign a subclass to a variable having a supeclass type, the casting is performed automatically.



* Q7. What’s the difference between the methods sleep() and wait()


A. The code sleep(1000); puts thread aside for exactly one second. The codewait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.


* Q8. Can you write a Java class that could be used both as an applet as well as an application?


A. Yes. Add a main() method to the applet.


* Q9. What’s the difference between constructors and other methods?


A. Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.


* Q10. Can you call one constructor from another if a class has multiple constructors


A. Yes. Use this() syntax.


* Q11. Explain the usage of Java packages.


A. This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.


* Q12. If a class is located in a package, what do you need to change in the OS environment to be able to use it?


A. You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let’s say a class Employee belongs to a package; and is located in the file c:\dev\com\xyz\hr\ In this case, you’d need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:




* Q13. What’s the difference between J2SDK 1.5 and J2SDK 5.0?


A.There’s no difference, Sun Microsystems just re-branded this version.

* Q14. What would you use to compare two String variables – the operator == or the method equals()?

A. I’d use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.

* Q15. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?

A. Yes, it does. The FileNoFoundException is inherited from the IOException. Exception’s subclasses have to be caught first.

* Q16. Can an inner class declared inside of a method access local variables of this method?
A. It’s possible if these variables are final.
* Q17. What can go wrong if you replace && with & in the following code:

String a=null; if (a!=null && a.length()>10) {…}

A. A single ampersand here would lead to a NullPointerException.

* Q18. What’s the main difference between a Vector and an ArrayList

A. Java Vector class is internally synchronized and ArrayList is not.

* Q19. When should the method invokeLater()be used?

A. This method is used to ensure that Swing components are updated through the event-dispatching thread.

* Q20. How can a subclass call a method or a constructor defined in a superclass?
A. Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass’s constructor.

For senior-level developers:

** Q21. What’s the difference between a queue and a stack?
A. Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule
** Q22. You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?

A. Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.
** Q23. What comes to mind when you hear about a young generation in Java?
** Q24. What comes to mind when someone mentions a shallow copy in Java?
A. Object cloning.
** Q25. If you’re overriding the method equals() of an object, which other method you might also consider?
A. hashCode()
** Q26. You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use:
ArrayList or LinkedList?
A. ArrayList
** Q27. How would you make a copy of an entire Java object with its state?
A. Have this class implement Cloneable interface and call its method clone().
** Q28. How can you minimize the need of garbage collection and make the memory use more effective?
A. Use object pooling and weak object references.
** Q29. There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?
A. If these classes are threads I’d consider notify() or notifyAll(). For regular classes you can use the Observer interface.
** Q30. What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?
A. You do not need to specify any access level, and Java will use a default package access level.

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

class ReadAttachment{
public static void main(String [] args)throws Exception{

String host=””;
final String user=””;
final String password=”xxxxx”;//change accordingly

Properties properties = System.getProperties();
properties.setProperty(“”,host );
properties.put(“mail.smtp.auth”, “true”);

Session session = Session.getDefaultInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,password);

Store store = session.getStore(“pop3”);

Folder folder = store.getFolder(“inbox”);;

Message[] message = folder.getMessages();
for (int a = 0; a < message.length; a++) {
System.out.println(“————-” + (a + 1) + “———–“);

Multipart multipart = (Multipart) message[a].getContent();

for (int i = 0; i < multipart.getCount(); i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
InputStream stream = bodyPart.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(stream));

while (br.ready()) {


LOAD THE JAR FILE :  C:\> set classpath=mail.jar;activation.jar;


RUN BY :C:\> java ReadAttachment



Java Developer Kit contains tools needed to develop the Java programs, and JRE to run the programs. The tools include compiler (javac.exe), Java application launcher (java.exe), Appletviewer, etc…


Compiler converts java code into byte code. Java application launcher opens a JRE, loads the class, and invokes its main method.


You need JDK, if at all you want to write your own programs, and to compile the m. For running java programs, JRE is sufficient.


JRE is targeted for execution of Java files


i.e. JRE = JVM + Java Packages Classes(like util, math, lang, awt,swing etc)+runtime libraries.


JDK is mainly targeted for java development. I.e. You can create a Java file (with the help of Java packages), compile a Java file and run a java file



Java Runtime Environment contains JVM, class libraries, and other supporting files. It does not contain any development tools such as compiler, debugger, etc. Actually JVM runs the program, and it uses the class libraries, and other supporting files provided in JRE. If you want to run any java program, you need to have JRE installed in the system


The Java Virtual Machine provides a platform-independent way of executing code; programmers can concentrate on writing software, without having to be concerned with how or where it will run.


If u just want to run applets (ex: Online Yahoo games or puzzles), JRE needs to be installed on the machine.



As we all aware when we compile a Java file, output is not an ‘exe’ but it’s a ‘.class’ file. ‘.class’ file consists of Java byte codes which are understandable by JVM. Java Virtual Machine interprets the byte code into the machine code depending upon the underlying operating system and hardware combination. It is responsible for all the things like garbage collection, array bounds checking, etc… JVM is platform dependent.


The JVM is called “virtual” because it provides a machine interface that does not depend on the underlying operating system and machine hardware architecture. This independence from hardware and operating system is a cornerstone of the write-once run-anywhere value of Java programs.


There are different JVM implementations are there. These may differ in things like performance, reliability, speed, etc. These implementations will differ in those areas where Java specification doesn’t mention how to implement the features, like how the garbage collection process works is JVM dependent, Java spec doesn’t define any specific way to do this.

Tim Cook has pulled a startling coup, getting Larry Ellison to start cooking — if not eating — his own dog food.

The headlines make it sound like Oracle, the inherited owner of Java, has generously stepped in to help protect Mac owners from infections like Flashback. There’s an important backstory, though, that hasn’t hit the headlines.

Although Steve Jobs tried for years to get out from under the Java ball and chain, last week Tim Cook finally coerced Oracle into supplying updates for its own software. It only took 700,000 infected systems to convince Oracle to handle Java on OS X itself.

Steve Jobs dropped Java for the Mac in October 2010, removing it as part of the standard OS X install. The Mac OS X Developer Library post for Oct. 20, says, “The Java runtime ported by Apple and that ships with Mac OS X is deprecated. Developers should not rely on the Apple-supplied Java runtime being present in future versions of Mac OS X.” At the same time, Apple stopped accepting apps for the Mac App Store that relied on the Java Runtime Environment. Apple had never supported Java clients in itsiOS.

On Oct. 21, 2010, the MacRumors forum said that Jobs replied to a concerned Java developer, claiming, “Sun (now Oracle) supplies Java for all other platforms. They have their own release schedules, which are almost always different than ours, so the Java we ship is always a version behind. This may not be the best way to do it.”

Of course, Jobs knew at the time he was blowing smoke — or perhaps a reality distortion field set in. With a few notable exceptions, Java’s owner has never supplied versions “for all other platforms.” Back when Java started, Sun supplied a version of the runtime for Linux because, as the “father of Java” James Gosling says, “there was no one else to do it.” Every other distributor — Microsoft,IBM, Hewlett-Packard, and Apple — rolled its own version, based on Sun’s reference code.

Java 1.0 for Mac OS 9 was released in 1996, the year Apple bought NeXT and Jobs returned to the Apple fold. Jobs knew full well that Apple was developing its own version of Java, just like all the other platform providers.

Microsoft started taking its version of Java far afield, adding its own extensions to the language, and Sun sued in 1997 to get its trademark back. A bitter, extended, and very public court battle ended in January 2001, with Microsoft paying Sun $20 million for its transgressions and Sun taking control of Java updates. Until this last week, Sun had released Java versions only for Linux and Windows. All the other platforms made their own.

The fact is that Jobs had been trying for years to get Sun, then Oracle, to take over Java releases for OS X. Back in 2007, Jobs is quoted as saying, “Java’s not worth building in. Nobody uses Java anymore. It’s this big heavyweight ball and chain.” In 2010, when Jobs dropped Java like a hot cup of coffee, he tried to shame Oracle into supporting it. Since then, Java’s been a neglected stepchild in the Mac world, completely shunned in iOS.

As Gosling says, “In the early days, they [Apple] were insistent on doing the port themselves. They put terrific energy into it. They did a good job. But then, as OS X took hold and Apple was able to convince developers to target their nonportable/proprietary environment, Apple’s fundamental control-freak tendency took over and they put less and less energy into Java.”

Oracle is now distributing Java SE 7 Update 4 for Mac OS X, and that will become the default version on starting May 1. Henrik Stahl, senior director of Java product management at Oracle, says, “Oracle’s JDK and JavaFX release supports OS X Lionon any 64-bit capable Intel-based Mac. … There are community efforts based on OpenJDK to build JDK 7 [and JVM on 32-bit machines] for other configurations, easily found using your favorite search engine. We applaud these efforts! :-)”

Oracle has announced full plans to embrace OS X Lion and later with new updates to the Java Standard Edition and Java Development Kit. (The JDK includes the Java Runtime Environment, JRE, which in turn includes the Java Virtual Machine, JVM. And you thought Microsoft’s terminology was confusing!)

It’s not clear if Oracle will be updating the Java runtime for earlier versions of OS X. That’s particularly troubling because Dr. Web, the site that originally broke the story on the Flashback infections, now says that 25 percent of all Flashback infections come from Macs running OS X 10.5 Leopard, and 63 percent more are from OS X 10.6 Snow Leopard. Only 12 percent of all infections are in OS X 10.7 Lion, and those are the only machines that will be patched with Oracle’s Java SE 7 Update 4. Leopard and Snow Leopard users are left to the “community efforts.” If either Apple or Oracle is concerned about the hundreds of thousands of customers left swinging in the wind, there’s no indication I can find.

In contrast, Apple’s two recent Java patches covered Lion and Snow Leopard. They didn’t cover Leopard.

It seems that Jobs’ desires have finally been fulfilled, with the Java monkey now on Oracle’s back. Cook was at the helm — perhaps actively involved? — when it happened. Apple’s now able to wash its hands of all Java’s faults going forward. Oracle has responsibility for its own product. All it took was 700,000 infections.

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class sendMail
public static final String MAIL_SERVER = “”;
public static final String USERNAME = “Your gmail user name should be here”;
public static final String PASSWORD = “gmail password“;
public static String fromAddress = null;
public static String toAddress = null;

public static void main(String[] args)
fromAddress = “gmail email id”;
String toAddress = “”;
String subject = “This is a test Message”;
String message = “Hello Hows u?”;

Properties properties = System.getProperties();
properties.put(“”, MAIL_SERVER);
properties.put(“mail.smtps.auth”, “true”);

Session session = Session.getInstance(properties);
MimeMessage msg = new MimeMessage(session);

msg.setFrom(new InternetAddress(fromAddress));
msg.addRecipients(Message.RecipientType.TO, toAddress);

Transport tr = session.getTransport(“smtp”);
tr.sendMessage(msg, msg.getAllRecipients());

catch (AddressException ex)
System.out.println(“in addressException”);

catch (MessagingException ex)

System.out.println(“message successfully sent”);