Back to Top

Tuesday, 31 January 2012

JAVA: FileInputStream vs FileReader

Class FileInputStream:
  • It is use for reading stream of data from a file in the form of raw bytes(8-bit).
  • Very useful to read image.
  • It can also read character files.
Hierarchy of Class FileInputStream:
Hierarchy of Class FileInputStream in java


Tuesday, 31 January 2012 by Anijit Sarkar · 4 Read more »

Sunday, 29 January 2012

JAVA: Nested Class

 The class which is defined within another class is called nested class.
It can be divided into 2 types. They are -   static nested class & non-static nested class


Static Nested Class: 
  • Nested class which is declared static is static nested class.
  • Its methods & variables are associated with is mother/outer class.
  • It can be used only through object reference.
  • It is accessed using enclosing class name. Example: MotherClass.StaticNestedClass
  • It interacts with enclosing class or other class like any other top-level class.

Sunday, 29 January 2012 by Anijit Sarkar · 21 Read more »

Saturday, 28 January 2012

JAVA: Difference between throw & throws

throw is used to throw an exception in a program, explicitly.
Whereas,  throws is included in the method's declaration part, with a list of exceptions that the method can possible throw. It is necessary for all exceptions(except for Error & RuntimeException & their sub-classes).


Saturday, 28 January 2012 by Anijit Sarkar · 25 Read more »

Friday, 27 January 2012

JAVA: What are the differences between the String and StringBuffer classes?

String class :
  1. Once an object is created and initialized, it can't be changed because it is Immutable.
  2. String object can be created Implicitly and Explicitly.

StringBuffer class :
  1.  StringBuffer class is mutable(can be modified), length and content can be changed through certain method calls. 
  2. It creates object Explicitly.

Friday, 27 January 2012 by Anijit Sarkar · 1 Read more »

Wednesday, 25 January 2012

JAVA: What is the super class of all classes?

The class Object(java.lang.Object), is the super class of all classes in Java.

Wednesday, 25 January 2012 by Anijit Sarkar · 54 Read more »

Saturday, 21 January 2012

JAVA: What is the difference between error and an exception?

In Java, under Throwable class, there are 2 sub-classes named Exception and Error.

Exception class:
  •  It is used for exceptional conditions that user programs should catch.
  •  It's also the class that you will sub-class to create your own custom exception types.
  •  For example, NullPointerException will be thrown if you try using a null reference.

Saturday, 21 January 2012 by Anijit Sarkar · 5 Read more »

Thursday, 19 January 2012

JAVA: What is a Container?

  • Container is a component which can contain other components inside itself. It is also an instance of a subclass of  java.awt.Container, which extends java.awt.Component
  • An applet is a container. 
  • Containers include windows, frames, dialogs, and panels
  • As a Container itself  is a component, it can contain other containers.
  • Every container has a LayoutManager which helps to determines how different components are placed within the container.


Thursday, 19 January 2012 by Anijit Sarkar · 6 Read more »

Wednesday, 18 January 2012

JAVA: Checked and UnChecked Exception

In Java, there are lots of sub-classes under java.lang.Exception class. we can divide these sub-classes into 2 types on the basis of compile-time checking.
The types are - Checked Exception  & Unchecked Exception.

Checked Exception: 
  • Except RuntimeException( java.lang.RuntimeException) class, all sub-classes of Exception are checked exception.
  • These exceptions need to include in a method's throws list, because these are checked by the compiler during compile time if a method handles or throws these exception. 

Wednesday, 18 January 2012 by Anijit Sarkar · 1 Read more »

JAVA: Wrapper class

  Wrapper class is a special type of class that's  used to make primitive variables into objects, so that the primitives can be included in activities reserved for objects, like as being added to Collections, or returned from a method with an object return value. It simply wraps or encapsulates a single value for the primitive data types. These classes contain methods that provide basic functions such as class conversion, value testing & equality checks and the constructors of wrapper classes, allow objects can create and convert primitives to and from String objects.

     

by Anijit Sarkar · 10 Read more »

Tuesday, 17 January 2012

JAVA: Externalizable interface - uses.

1. Interface Externalizable gives a control over the serialization mechanism.

2. It has two methods readExternal and writeExternal, which are use to customize the serialization process.

Tuesday, 17 January 2012 by Anijit Sarkar · 0 Read more »

JAVA: Serialization-Common usage.

1. An object needs to be serialized, when it's need to be sent over the network.

2. If the state of an object is to be saved, objects need to be serialized.

by Anijit Sarkar · 3 Read more »

Java: What are the methods of interface Serializable?

 Interface Serializable has no methods, it's empty.

by Anijit Sarkar · 0 Read more »

JAVA: How to serialize an object to a file?


      By implementing an interface Serializable in the class whose instances are to be serialized.Then passing the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.

Example: 
   Now, we will see a practical implementation of serialization on an object and we will store the serialized data in a file.
Class SampleClass is a pojo class which implements java.io.Serializable . It contains four String fields, one of which is declared as transient. That means, we can't serialized this field.


Class SampleClass :

package com.interview.question.java;

public class SampleClass implements java.io.Serializable{
     
  /**
    *
    * Sample serialized class.
    *
    * @author http://interviewquestionjava.blogspot.com
    *
    **/
     
      private static final long serialVersionUID = 1L;

      private String strName;
     
      private String strAddress;
     
      private String strUsername;
     
     /**
       *
       * we declared the variable strPassword as transient.
       * So, it will be shield from serialization.
       *
       **/
      private transient String strPassword;

      public String getStrName() {
            return strName;
      }

      public void setStrName(String strName) {
            this.strName = strName;
      }

      public String getStrAddress() {
            return strAddress;
      }

      public void setStrAddress(String strAddress) {
            this.strAddress = strAddress;
      }

      public String getStrUsername() {
            return strUsername;
      }

      public void setStrUsername(String strUsername) {
            this.strUsername = strUsername;
      }

      public String getStrPassword() {
            return strPassword;
      }

      public void setStrPassword(String strPassword) {
            this.strPassword = strPassword;
      }
     
     

}

    Now,  Class SerializeObjectToFile, is used to create an object of SampleClass with some values.
Then we serialized that object to a file name sampleClass.ser.

Class SerializeObjectToFile :


package com.interview.question.java;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class SerializeObjectToFile {

/**
    *
    * This class serialized an Object of SampleClass
    * to a file named sampleClass.ser
    *
    * @author http://interviewquestionjava.blogspot.com
    *
    **/

 public static void main(String[] args) {
 
  SampleClass objSampleClass = new SampleClass();
 
  objSampleClass.setStrName("Ashoka Maurya");
  objSampleClass.setStrAddress("Magadha");
  objSampleClass.setStrUsername("Chakravartin");
  objSampleClass.setStrPassword("Ashokavadana");
 
  try 
  {
   FileOutputStream objFileOutputStream = new FileOutputStream("src/com/interview/question/java/sampleClass.ser");
   ObjectOutputStream objOutputStream = new ObjectOutputStream(objFileOutputStream);
   objOutputStream.writeObject(objSampleClass);
   objOutputStream.close();
   objFileOutputStream.close();
  
   System.out.println("SampleClass is serialized successfully..");
  } 
  catch (IOException e) 
  {
   e.printStackTrace();
  }
 

 }

}


Now, to deserialize this data back to an object please check the post Deserializing an Object from File

by Anijit Sarkar · 3 Read more »

Monday, 16 January 2012

JAVA: What is serialization?

Serialization is the process of writing the state of an object to a byte stream. It's useful when you want to save the state of your program to a persistent storage area, such as a file.

Monday, 16 January 2012 by Anijit Sarkar · 0 Read more »

JAVA : What is Method Overriding?


   When a method in subclass has the same name and type signature as a method in its superclass, the the method in the subclass is called to override the method in the superclass. When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. The version of the method defined by the superclass will be hidden.

by Anijit Sarkar · 2 Read more »

JAVA : What if we have multiple main methods in the same class?

   No the program fails to compile. The compiler says that the main method is already defined in the class.

by Anijit Sarkar · 3 Read more »

JAVA : Can an application have multiple classes having main method?

  Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.

by Anijit Sarkar · 1 Read more »

Sunday, 15 January 2012

JAVA : What is implicit casting?

  Implicit casting is the process of simply assigning one entity to another without any transformation guidance to the compiler. This type of casting is not permitted in all kinds of transformations and may not work for all scenarios.
 
Example
byte i = 1;
short j = i; //Implicit casting

Sunday, 15 January 2012 by Anijit Sarkar · 1 Read more »

JAVA : What if I do not provide the String array as the argument to the method?

  Program compiles but throws a runtime error "NoSuchMethodError".

by Anijit Sarkar · 2 Read more »

JAVA : What if I write static public void instead of public static void?

  Program compiles and runs properly.

by Anijit Sarkar · 0 Read more »

JAVA : What if the static modifier is removed from the signature of the main method?

 Program compiles. But at runtime throws an error “NoSuchMethodError”.

by Anijit Sarkar · 13 Read more »

JAVA : What is final?

  •  A final class can't be extended ie., final class may not be subclassed. 
  •  A final method can't be overridden when its class is inherited. 
  •  You can't change value of a final variable (is a constant).

by Anijit Sarkar · 1 Read more »

JAVA : What is static in java?

  Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.

by Anijit Sarkar · 5 Read more »

JAVA : Access Specifiers in Java

public access

Fields, methods and constructors declared public (least restrictive) within a public class are visible to any class in the Java program, whether these classes are in the same package or in another package.


private access

The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods or constructors declared private are strictly controlled, which means they cannot be accesses by anywhere outside the enclosing class. A standard design strategy is to make all fields private and provide public getter methods for them.


protected access

The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods and constructors declared protected in a superclass can be accessed only by subclasses in other packages. Classes in the same package can also access protected fields, methods and constructors as well, even if they are not a subclass of the protected member’s class.


default access

Java provides a default specifier which is used when no access modifier is present. Any class, field, method or constructor that has no declared access modifier is accessible only by classes in the same package. The default modifier is not used for fields and methods within an interface.

by Anijit Sarkar · 8 Read more »

JAVA : What is an Iterator? How is it differ from enumerations?


    
   Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.
                             

   Iterators differ from enumerations in two ways:
  • Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
  • Method names have been improved.

by Anijit Sarkar · 1 Read more »

JAVA : What is the difference between a while statement and a do while statement?

 A while statement (pre test) checks at the beginning of a loop to see whether the next loop iteration should occur. A do while statement (post test) checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the loop body at least once.

by Anijit Sarkar · 0 Read more »

JAVA : What is the difference between a constructor and a method?

  A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.

  A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

by Anijit Sarkar · 1 Read more »

JAVA : Why there are no global variables in Java?

  Global variables are globally accessible. Java does not support globally accessible variables due to following reasons:
  • The global variables breaks the referential transparency
  • Global variables creates collisions in namespace.

by Anijit Sarkar · 2 Read more »

JAVA : Difference between Vector and ArrayList?

Vector :
  1.               It's synchronized.
  2.               It's slower than ArrayList.
  3.               It's generally used in multithreading programs.

ArrayList :
  1.               It's unsynchronized.
  2.               It's faster than Vector.
  3.               It's generally used in single-thread programs.





by Anijit Sarkar · 24 Read more »

JAVA : Difference between HashMap and HashTable?

 The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.

by Anijit Sarkar · 2 Read more »

JAVA : What is HashMap and Map?

Map is Interface and Hashmap is class that implements that.

by Anijit Sarkar · 0 Read more »

JAVA : Diff between Runnable Interface and Thread class while using threads.

1. If you want to extend the Thread class then it will make your class unable to extend other classes as java is having single inheritance feature whereas If you implement runnable interface, you can gain better object-oriented design and consistency and also avoid the single inheritance problems.

2. Extending the thread will give you simple code structure in comparison to Runnable Interface.

3. Using Runnable Interface, you can run class several times whereas Thread have the start() method that can be called only once.

by Anijit Sarkar · 0 Read more »

JAVA : Explain different way of using thread?

There are 2 ways of using thread -
  1. By implementing runnable interface.
  2. By extending the Thread class. 

by Anijit Sarkar · 9 Read more »

JAVA : What is the Java API?





  An application programming interface (API) is a library of functions that Java provides for programmers for common tasks like file transfer, networking, and data structures.


List of Java APIs:

There are three types of  APIs in Java.
  • the official core Java API, contained in the JDK or JRE, of one of the editions of the Java Platform. The three editions of the Java Platform are Java ME (Micro edition), Java SE (Standard edition), and Java EE (Enterprise edition).
  • optional official APIs that can be downloaded separately. The specification of these APIs are defined according to a Java Specification Request (JSR), and sometimes some of these APIs are later included in the core APIs of the platform (the most notable example of this kind is Swing).
  • unofficial APIs, developed by third parties, but not related to any JSRs.

by Anijit Sarkar · 2 Read more »

JAVA : Describe synchronization in respect to multithreading.

With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. synchronization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors. So, its the mechanism that ensures that only one thread is accessed the resources at a time.


How to achieve synchronization in java?

In java, synchronization can be achieved by using the 
synchronized keyword. 
It can be used in 2 ways.
1. on a method signature: We can declare synchronized keyword in method signature, therefore, that method will be thread safe in multi-threaded environment. That means, only, one thread at a time can access this method.
Below, method execute() is synchronized, so it is can be accessed by one thread at a time.
       
synchronized void execute(){
  // do something
}
       
2. Write synchronized block: Secondly, we can write a synchronized block, and that block will be synchronized.

synchronized(this){
  // do something
}


The above code, will lock the object itself, when this piece of code has been executed by a thread.

by Anijit Sarkar · 28 Read more »

Popular Posts

Subscribe via Email
Subscribe Java Interview Questions via Email
All Rights Reserved JAVA INTERVIEW QUESTIONS | Privacy Policy | Anijit Sarkar