Showing posts with label Java Frequently Asked Questions. Show all posts
Showing posts with label Java Frequently Asked Questions. Show all posts

Tuesday, 29 March 2011

Basic Java Questions -1



What are the benefits of using Java Or Why JAVA?

The main benefits of using Java include the following:

1) Java programming language is very simple and object-oriented. It’s easy to learn and taught in many colleges and universities.

2) As mentioned above,Java application run inside a Java Virtual Machine and now all major operating systems are able to run Java including Windows,Mac OS and UNIX.

3) Write one and run anywhere,a java application runs on all java platforms

4) Java technologies have been improved by community involvement. This means it is suitable for most types of applications especially complex systems that are used widely in network and distributed computing

5) Java is also secure. Only Java applications that have permission can access the resources of the main computer. This means that the main computer is protected from virus attackers and hackers.

What is ClASSPATH?
CLASSPATH is an argument set on the Command Line or through Environment Variable, that tells the JVM where to look for the user defined classes and packages in Java Program.

What is JDK?
Java Development Kit (JDK) essentially a Java Platform, consisting of the API classes, a Java Compiler and the JVM Interpreter. JDK is used to compile java applications and applets.

What is Bytecode?
Bytecode is the form of instructions that the JVM executes. Bytecodes are the machine language of the JVM

What is Java Debugger?
Java Debugger helps in finding and fixing the bugs in Java Language programs. It is denoted as jdb.

What is Javadoc?
Sun Microsystems has provided a computer software tool known as Java doc. This tool is used to generate API documentation into HTML format from java source code.

What is Java Compiler?
Java Compiler (javac) is a computer program or set of programs which translates java source code into java bytecode. Once the bytecode is generated, it can run on any platform using Java Interpreter(JVM).

Whts is JVM or Java Interpreter?
Java virtual Machine is an implementation of the JVM Specification, interprets complied java binary code (java bytecode) for a computers processors so that it can perform a java programs instructors.
JVM is a piece of software that is responsible for running java programs.

What are the major differences between C++ and Java?
-Java doesn't support pointers.
-Java doesn't include structures or unions.
-Java doesn't support operator overloading.
-All the code in a java program is encapsulated within one or more classes.
-Java doesn't support mutliple inheritance.
-Java doesn't have destructors.
- It is not possible to declare unsigned integers in java.
In java,, objects are passed by reference only. In C++ objects may be passed by value or reference.

Typical Java Development Environment

There are 5 phases in java development environment.
  1. Editor : Program is created in an editor and stored on disk in a file ending with .java
  2. Compiler:  creates bytecodes and stores them on a disk in a file ending with .class
  3. Class Loader: Class loader reads .class files containing bytecodes from disks and put those bytecodes in memory.
  4. Bytecode Verifier: Bytecode verifier confirms that all bytecodes are valid and do not violate java's security restrictions.
  5. JVM: To execute the program, JVM reads bytecodes and translates them into a language that the computer can understand.
EDIT=>>COMPILE=>> LOAD=>>VERIFY=>>EXECUTE


BYTECODE: Bytecode is the form of instructions that the JVM executes. They are the machine language of the JVM.


Java Inheritance

Classes in Java code exist in hierarchies. Classes above a given class in a hierarchy are superclasses of that class. That particular class is a subclass of every class higher up. A subclass inherits from its superclasses. The class Object is at the top of every class's hierarchy. In other words, every class is a subclass of (and inherits from) Object.

For example, suppose we have an Adult class that looks like this:

public class Adult {
  protected int age = 0;
protected String firstname = "firstname";
protected String lastname = "lastname";
protected String gender = "MALE";
protected int progress = 0;
public Adult() { }
public void move() {
System.out.println("Moved.");
}
public void talk() {
System.out.println("Spoke.");
}
}

Our Adult class implicitly inherits from Object. That's assumed for any class, so you don't have to type extends Object in the class definition. But what does it mean to say that our class inherits from its superclass(es)? It simply means that Adult has access to the exposed variables and methods in its superclasses. In this case, it means that Adult can see and use the following from any of its superclasses (we have only one at the moment):
• public methods and variables
• protected methods and variables
• Package protected methods and variables (that is, those without an access specifier), if the superclass is in the same package as Adult.


Defining a class hierarchy:

Suppose we have another class called Baby. It looks like this:

public class Baby {
protected int age = 0;
protected String firstname = "firstname";
protected String lastname = "lastname";
protected String gender = "MALE";
protected int progress = 0;
public Baby() {
}
public void move() {
System.out.println("Moved.");
}
public void talk() {
System.out.println("Spoke.");
}
}

Our Adult and Baby classes look very similar. In fact, they're almost identical. That kind of code duplication makes maintaining code more painful than it needs to be. We can create a superclass, move all the common elements up to that class, and remove the code duplication. Our superclass could be called Person, and it might look like this:

public class Person {
protected int age = 0;
protected String firstname = "firstname";
protected String lastname = "lastname";
protected String gender = "MALE";
protected int progress = 0;
public Person() {
}
public void move() {
System.out.println("Moved.");
  }
public void talk() {
System.out.println("Spoke.");
}
}

Now we can have Adult and Baby subclass Person, which makes those two classes pretty simple at the moment:

public class Adult {
public Adult() 
{
}
}

public class Baby {
public Baby() 
{
}
}

Java Abstraction

The technique of choosing common features of objects and methods is known as abstracting. It also involves with concealing the details and highlighting only the essential features of a particular object or a concept. In an OO context, abstraction refers to the act of generalizing data and behavior to a type higher up the hierarchy than the current class. When you move variables or methods from a subclass to a superclass, you're abstracting those members. 

Those are general terms, and they apply in the Java language. But the language also adds the concepts of abstract classes and abstract methods. An abstract class is a class that can't be instantiated. For example, you might create a class called Animal. It makes no sense to instantiate such a class: In practice, you'd only want to create instances of a concrete class like Dog. But all Animals have some things in common, such as the ability to make noise. Saying that an Animal makes noise doesn't tell you much. The noise it makes depends on the kind of animal it is. How do you model that? You define the common stuff on the abstract class, and you force subclasses to implement concrete behavior specific to their types. You can have both abstract and concrete classes in your hierarchies.

Using abstraction: 

Our Person class contains some method behavior that we don't know we need yet. Let's remove it and force subclasses to implement that behavior polymorphically. We can do that by defining the methods on Person to be abstract. Then our subclasses will have to implement those methods.

public abstract class Person 
{
     ...
     abstract void move();
     abstract void talk();
}

public class Adult extends Person 
{
   public Adult(){
   }
   public void move() 
   {
     System.out.println("Walked.");
   }
   public void talk() 
   {
     System.out.println("Spoke.");
   }
}

public class Baby extends Person {
    public Baby() {
    }
    public void move() {
      System.out.println("Crawled.");
    }
    public void talk() {
      System.out.println("Gurgled.");
    }
}

What have we done in this listing?
• We changed Person to make the methods abstract, forcing subclasses to implement them.
• We made Adult subclass Person, and implemented the methods.
• We made Baby subclass Person, and implemented the methods.
When you declare a method to be abstract, you require subclasses to implement the method, or to be abstract themselves and pass along the implementation responsibility to their subclasses. You can implement some methods on an abstract class, and force subclasses to implement others. That's up to you. Simply declare the ones you don't want to implement as abstract, and don't provide a method body. If a subclass fails to implement an abstract method from a superclass, the compiler will complain. Now that both Adult and Baby subclass Person, we can refer to an instance of either class as being of type Person.

Java Encapsulation

Remember, an object is a self-contained thing that contains data elements and actions it can perform on those data elements. This is an implementation of a principle known as information hiding. The idea is that an object knows about itself. If another object wants facts about the first object, it has to ask. In OOP terms, it has to send the object a message to ask for its age. In Java terms, it has to call a method on the object that will return the age. Encapsulation ensures that each object is distinct, and that programs are conversations among objects. The Java language lets a programmer violate this principle, but it's almost always a bad idea to do so.

Encapsulation is the concept of hiding the implementation details of a class and allowing access to the class through a public interface. For this, we need to declare the instance variables of the class as private or protected. 

The client code should access only the public methods rather than accessing the data directly. Also, the methods should follow the Java Bean's naming convention of set and get. 

Encapsulation makes it easy to maintain and modify code. The client code is not affected when the internal implementation of the code changes as long as the public method signatures are unchanged. For instance: 

public class Employee
   private float salary; 
   public float getSalary() 
   { 
     return salary; 
   } 
   public void setSalary(float salary) 
   { 
     this.salary = salary; 
   } 
}

Here's an encapsulation starter rule of thumb:

-> Mark instance variables private.
-> Mark getters and setters public.

Class and Object

CLASS : A Class is a specification/blueprint/prototype/template of Object
Specification : Requirement of an object i.e specifying or describe about something.
Prototype : Non functional form of real thing.They will not function like real things but they just show how the object looks.
  • Class is just describing about how an object looks.
  • It is a collection of data & methods.
  • It is not an object, but its used to construct them.It tells the JVM how to make about object of a particular type.
  • Java classes consists of attributes & behaviours.
  • Attributes: represent the data is unique to an instance of a class. These are non-local variables that are not declared within method bodies.
  • Behaviour: are methods that operate on the data to perform useful tasks.
  • Class syntax: use the following syntax to declare a class in java contents of someclassname.java
[public][abstract/final] class someclassname [extends some parent class][implements some interface]
{
// variable & methods are declared within curly braces
}
Here is an example of a HorseClass.Horse is a subclass of mammal & it implements the Hoofed interface.
public class Horse extends Mammal implements Hoofed
{
// horse variables and methods go here
}
Note :
  • A class can have public or default(no modifier) visibility.
  • It must have the class keyword & class must be followed by a legal identifier.
  • It may optionally extend one parent class.By default,it will extend java.lang.Object.
  • Each java source file may contain only one public class.A source file may contain any number of default visible classes.
  • Finally, the source file name must match the public class name & it must have a .java suffix

OBJECT : Objects are the physical instantiations of classes. They are living entities within a program that has independent lifecycles and that are created according to the class that describes them. Just as many buildings can be built from one blueprint, many objects can be instantiated from one class.
An object is a self-contained bunch of code that knows about itself and can tell other objects about itself if they ask it questions that it understands. An object has data members (variables) and methods, which are the questions it knows how to answer (even though they may not be worded as questions). The set of methods that an object knows how to respond to is its interface. Some methods are open to the public, meaning that another object can call (or invoke) them. That set of methods is known as the object's public interface. When one object invokes a method on an another object, that's known as sending a message, or a message send. That phrase is certainly OO terminology, but most often in the Java world people tend to say, "Call this method" rather than, "Send this message."
  • Things an object knows about itself are called Instance variables. They represent an objects state(data) and can have unique values for each object of that type.
  • Things an object can do are called Methods that operate on that data.

Conceptual object example:
Suppose we have a Person object. Each Person has a name, an age, a race, and a gender. Each Person also knows how to speak and walk. One Person can ask another Person how old it is, or could tell another Person to start (or stop) walking. In programming terms, you would create a Person object and give it some variables (like name and age). If you created a second Person object, it could ask the first how old it is, or tell it to start walking. It would do those things by calling methods on the first Person object. When we start writing code in the Java language, you'll see how the language implements the concept of an object. Generally, the concept of an object remains the same across the Java language and other OO languages, though it gets implemented differently from language to language. The concepts are universal. Because that's true, OO programmers, regardless of the language they're programming in, tend to speak differently from procedural programmers. Procedural programmers often talk about functions and modules. OO programmers talk about objects, and they often talk about those objects using personal pronouns. It's not uncommon to hear one OO programmer say to another, "This Supervisor object here says to the Employee object, 'Give me your ID,' because he needs it to assign tasks to the Employee." Procedural programmers might think this way of talking is strange, but it's perfectly natural for OO programmers. In their programming world, everything's an object (with some notable exceptions in the Java language), and programs are objects interacting (or "talking") with each other.

What is Java Compiler & Interpreter

Java Compiler:
To commence with Java programming, we must know the significance of Java Compiler. When we write any program in a text editor like Notepad, we use Java compiler to compile it. A Java Compiler javac is a computer program or set of programs which translates java source code into java byte code.
The output from a Java compiler comes in the form of Java class files (with .class extension). The java source code contained in files end with the .java extension. The file name must be the same as the class name, as classname.java. When the javac compiles the source file defined in a .java files, it generates bytecode for the java source file and saves in a class file with a .class extension.

Once the byte code is generated it can be run on any platform using Java Interpreter (JVM). It interprets byte code (.class file) and converts into machine specific binary code. Then JVM runs the binary code on the host machine.


Java Interpreter:

We can run Java on most platforms provided a platform must has a Java interpreter. That is why Java applications are platform independent. Java interpreter translates the Java bytecode into the code that can be understood by the Operating System. Basically, A Java interpreter is a software that implements the Java virtual machine and runs Java applications. As the Java compiler compiles the source code into the Java bytecode, the same way the Java interpreter translates the Java bytecode into the code that can be understood by the Operating System.
When a Java interpreter is installed on any platform that means it is JVM (Java virtual machine) enabled platform. It (Java Interpreter) performs all of the activities of the Java run-time system. It loads Java class files and interprets the compiled byte-code.

What is Java Virtual Machine

JVM is the main component of Java architecture and it is the part of the JRE (Java Runtime Enviroment) . It provides the cross platform functionality to java. This is a software process that converts the compiled Java byte code to machine code. Byte code is an intermediary language between Java source and the host system. Most programming language like C and Pascal converts the source code into machine code for one specific type of machine as the machine language vary from system to system . Mostly compiler produce code for a particular system but Java compiler produce code for a virtual machine .

JVM provides security to java. The programs written in Java or the source code translated by Java compiler into byte code and after that the JVM converts the byte code into machine code for the computer one wants to run. JVM is a part of Java Run Time Environment that is required by every operating system requires a different JRE .

The architecture of the JVM is as follows. Firstly we write the simple java program(source code) the java compiler converts the source code into the bytecode , after that JVM reads this bytecode and converts this into the machine code.

What is Java ?


Java is a programming language originally developed by Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities. It was used for the project set top box, was created by James Gosling in 1991. It is the modified from the language Oak. Oak was unsuccessful in the market. So Sun modified this language and changed its name to Java. Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of computer architecture.

Java is a :

1. Simple:
  • Has a small set of language constructs.
  • Derives its syntax from C & C++.
  • Is free from pointers.
  • Uses garbage collection.
2. Object Oriented:
  • Supports the basic notion of OO: Abstraction, Modualrity, Encapsulation, Hierarchy, Typing, Concurrency, Persistence.
  • Almost Everything is an Object.
3. Distributed:
  • Works on variety of Platforms.
  • Provides support for: Networking, Internet, Remote Objects.
4. Interpreted:
  • The Java Compiler generates byte code for JVM.
  • A Java Interpreter is needed to execute the bytecode.
5. Robust:
  • Exception & Error Handling.
  • Multi-Tasking.
  • Memory Protection and Management.
  • Allows Modular Development.
  • Extensive compile-time checking.
6. Secure:
  • Java security comprises two parts: security inside the Java Virtual Machine (JVM) and security outside the JVM.
7. Architecture Neutral:
  • Bytecode can run on any JVM or on any platform.
  • "Write once, run anywhere".
  • JDK Implementations on any platform.
8. Portable:
  • The bytecodes can be run on virtual machines(VM) above different operating systems such as MacOS, Windows 95/NT/CE, Solaris, OS2, etc,.
  • It can also run directly on hardware.

9. High Performance:
  • Mutli-Threading allows more than one task in a program.
  • With JIT compilers the intrepreted code compiles at run time and gives almost native code speed.
10. Dynamic:
  • Java has been built to support the development of dynamically extendable systems.
  • Objects can live on the internet.
  • Java provides dynamic linking of the binary code at runtime.