Core Java [My Notes]

why java does not global variables or functions?

         All the code in Java program is encapsulated within classes therefore Java does not have global variables or functions.

JAVA supports the following variables:

  1. INSTANCE – Normal variable

2.CLASS- Variable which declared static

3.LOCAL- Variable  active within method

Where static Baseclass [Static Variable] =>First Derived Class [Private Variable]

Access Specifier:

Public – public classes, methods, and fields can be accessed from everywhere

Private – Use Var/Method within the same class

Default – It means that all the other classes in the current package have access to the friendly member, but to all the classes outside of this package the member appears to be private.

Protected – protected methods and fields can only be accessed within the same class to which the methods and fields belong, within its subclasses, and within classes of the same package, but not from anywhere else.

Friendly – [It means that all the other classes in the current package have access to the friendly member, but to all the classes outside of this package the member appears to be private.] ller to

The following table summarizes the access level permitted by each specifier.

Situation public protected default private
Accessible to class

from same package?

yes yes yes no
Accessible to class

from different package?

yes no, unless it is a subclass no no

Note the difference between the default access which is in fact more restricted than the protected access. Without access specifier (the default choice), methods and variables are accessible only within the class that defines them and within classes that are part of the same package. They are not visible to subclasses unless these are in the same package. protected methods and variables are visible to subclasses regardless of which package they are in.

OOPS Concept:

1.Encapsulation:

Wrapping of data’s and methods in to a single entity. here we cant see the details of the object. but can use the object.

  • Data Hiding:

Can’t see the object. In Java there are four different terms used for hiding data constructs and these are public, private, protected and package.

2.Inheritance:

Ability of a new class to be created, from an existing class by extending it.

3.Polymorphism:

Same variable Different forms.

a.Method Overloading:

        Same name but different argument types.

    b.Method Overriding:

        Same name and same argument type.[Object Re-usability]
    c.Operator Overloading:

        The operator overloading like”=”, “==”,”&&”,”&” (less commonly known as ad-hoc polymorphisms).

4.Abstraction:

Only relevant details will be collected and remove other details. Use by extends keyword

    • Interface:

Use by implements. used to achieve multiple inheritance.

5.Class:

Which holds behaviour of method and objects. it bind both member fn/var.

6.Object:

Entity of class.Particular instance of class.

7.Method:

Which holds certain action of a class by using the objects.

8.Package:

A package is a name-space for organizing classes and interfaces in a logical manner.

AWT & SWING:

AWT: [Abstract Windows Toolkit]

In this section, you will learn about thejava.awt.*; package available with JDK. AWT stands for Abstract Windowing Toolkit. It contains all classes to write the program that interface between the user and different windowing toolkits. You can use the AWT package to develop user interface objects like buttons, checkboxes, radio buttons and menus etc

Awt Controls:

  1. Canvas:[ lller to Work Area]

As the name indicates a Canvas is a region where you can draw things such as circles, triangles, ovals or any other shape. Basically it is a graphical component that represents a region. It has got a default method which is paint() method.

  1. Checkbox
  2. Label
  3. Scrollbar
  4. TextField

Swing:

  • Rich and glossy look.
  • Plug-gable look and feel, Native OS Support.
  • Look & fell on Native OS basis. so it will be light weight than AWT.
  • It’s a part of Java Foundation Class.

Swing Java consists of

  • Look and feel
  • Accessibility
  • Java 2D
  • Drag and Drop, etc
  • Swing, which is an extension library to the AWT, includes new and improved components that enhance the look and functionality of GUIs. Swing can be used to build Standalone swing gui Apps as well as Servlets and Applets.
  • JPanel is Swing’s version of the AWT class Panel and uses the same default layout, FlowLayout. JPanel is descended directly from JComponent.
  • JFrame is Swing’s version of Frame and is descended directly from that class. The components added to the frame are referred to as its contents; these are managed by the contentPane. To add acomponent to a JFrame, we must use its contentPane instead.
  • JInternalFrame is confined to a visible area of a container it is placed in. It can be iconified , maximized and layered.
  • JWindow is Swing’s version of Window and is descended directly from that class. Like Window, it uses BorderLayout by default.
  • JDialog is Swing’s version of Dialog and is descended directly from that class. Like Dialog, it uses BorderLayout by default. Like JFrame and JWindow,JDialog contains a rootPane hierarchy including a contentPane, and it allows layered and glass panes. All dialogs are modal, which means the current thread is blocked until user interaction with it has been completed. JDialog class is intended as the basis for creating custom dialogs; however, someof the most common dialogs are provided through static methods in the class JOptionPane.

Components:

  • JLabel, descended from JComponent, is used to create text labels.
  • JButton: The abstract class AbstractButton extends class JComponent and provides a foundation for a family of button classes, including,
  • JTextField allows editing of a single line of text. New features include the ability to justify the text left, right, or center, and to set the text’s font.
  • JPasswordField (a direct subclass of JTextField) you can suppress the display of input. Each character entered can be replaced by an echo character.This allows confidential input for passwords, for example. By default, the echo character is the asterisk, *.
  • JTextArea allows editing of multiple lines of text. JTextArea can be used in conjunction with class JScrollPane to achieve scrolling. The underlying
  • JScrollPane can be forced to always or never have either the vertical or horizontal scrollbar;
  • JButton is a component the user clicks to trigger a specific action.
  • JRadioButton is similar to JCheckbox, except for the default icon for each class. A set of radio buttons can be associated as a group in which only one button at a time can be selected.
  • JCheckBox is not a member of a checkbox group. A checkbox can be selected and deselected, and it also displays its current state.
  • JComboBox is like a drop down box. You can click a drop-down arrow and select an option from a list. For example, when the component has focus,pressing a key that corresponds to the first character in some entry’s name selects that entry. A vertical scrollbar is used for longer lists.
  • JList provides a scrollable set of items from which one or more may be selected. JList can be populated from an Array or Vector. JList does not support scrolling directly, instead, the list must be associated with a scrollpane. The view port used by the scroll pane can also have a user-defined border. JList actions are handled using ListSelectionListener.
  • JTabbedPane contains a tab that can have a tool tip and a mnemonic, and it can display both text and an image.
  • JToolbar contains a number of components whose type is usually some kind of button which can also include separators to group related components within the toolbar.
  • JMenubar can contain several JMenu’s. Each of the JMenu’s can contain a series of JMenuItem ’s that you can select. Swing provides support forpull-down and popup menus.

Layout:

  • FlowLayout when used arranges swing components from left to right until there’s no more space available. Then it begins a new row below it and moves from left to right again. Each component in a FlowLayout gets as much space as it needs and no more.
  • BorderLayout places swing components in the North, South, East, West and center of acontainer. You can add horizontal and vertical gaps between the areas.
  • GridLayout is a layout manager that lays out a container’s components in a rectangular grid. The container is divided into equal-sized rectangles,and one component is placed in each rectangle.
  • GridBagLayout is a layout manager that lays out a container’s components in a grid of cells with each component occupying one or more cells,called its display area. The display area aligns components vertically and horizontally, without requiring that the components be of the same size.

http://www.javabeginner.com/toc.htm

Thread:

Threads allow the program to perform multiple tasks simultaneously. Process speed can be increased by using threads because the thread can stop or suspend a specific running process and start or resume the suspended processes. Multitasking or multiprogramming is delivered through the running of multiple threads concurrently. If your computer does not have multi-processors then the multi-threads really do not run concurrently.

      • Every thread in Java is created and controlled by the java.lang.Thread class.A Java program can have many threads, and these threads can run concurrently, either asynchronously or synchronously.
      • The following figure shows the methods that are members of the Object and Thread Class.

Thread Creation

There are two ways to create thread in java;

  • Implement the Runnable interface (java.lang.Runnable)
  • By Extending the Thread class (java.lang.Thread)

LIFE STATES:

    1. New
    2. Runnable
    3. Running
    4. Blocked
    5. Dead
  • All thread are preemptive but not time sliced
  • Threads in the queue according to the priority
  • Execution of Thread in JVM by FIFO
  • Thread setPriority(1-10) / MIN/MAX/NORM/Priority
  • Thread must be in try and catch
  • Every program run as a single thread.

To Check Thread Status

    • isAlive() – To check the thread is execute/not
    • yeild() -Give chance for other runnable thread for execution from the queue

Thread Structure:

  • Init:

It will initialize the thread

  • Runnable:

It will Move the thread to Queue

  • Running:

It will in JVM and running.

  • Dead:

Thread will be destroyed when it completes the operation.

  • Wait:

Thread will goto wait condition when the resource is not available and when we explicitly define the sleep timing.

  • Notify:

It will retrive from one thread from waiting state to queue.

  • Notify all:

It will retrieve all the threads which are from waiting state will take to Queue.

Synchronization:

It process of monitoring the resource that is used by any process r not. If resource is hold then it will left the process to wait.

Synchronization in TWO Ways:

  • Whole Resource as Synchronized

It will synchronized the whole resource.It will keeps for long period by wherever we use the synchronized method so it will be synchronized in the place that we use.

  • Make Block as Synchronized

It will synchronized the block.It will allow the user to synchronized the method where ever we need to be synchronized. Apart form the the sync. it will remain as a normal method.

Interface:

  • Interface has been done by implements keyword.  
  • All methods of interface must to be public.
  • Interface also define constants
  • All interface variable refer to an object that implements interface.
  • instanceof used to check whether the object implements an interface.
  • Methods in interface are automaticaly public, fields are always public static final.
  • A build in interface is java called cloneable.    

    Example:Swingconstants NORTH,SOUTH,EAST,WEST. We use only NORTH instead of Swingconstants.NORTH.

Cloning:

  • clone – create something new based on something that exists.
  • copying – copy from something that exists to something else (that also already exists).

Shallow Copy / Deep Copy :

       

    • Shallow copy only makes a copy of an object at the root level [Immutable]
    • Deep copy will produce a copy of an object and all its child objects.[Muttable]

Interface Drawback:

    • It wont have instance fields
    • Methods r never implemented in interface

Implementing Interface[ 2 Steps]:

  • Declare the class that intent to implement the given interface
  • Define all the methods in interface.

Comparable – Which compare the object and return the integer as 1/-1

Inner Class / Nested Class:

  • Inner class is nothing but class within the class
  • Non-static nested classes are called inner classes.
  • Objects that are instances of an inner class exist within an instance of the outer class
  • It’s complex because of it’s security and access control.
  • Inner class can access private variable of outer class.
  • There are two types of nested class
    • Static Nested Class
    • Non-Static Nested Class/Inner Class

   

There are four kinds of inner class in Java. Static inner classes are the easiest kind to understand because they have nothing to do with instances of the containing class.

    1. Static Inner Class

A static inner class is a class declared as a static member of another class

    1. Instance Inner Class

An instance inner class is a class declared as an instance member of another class

    1. Local Inner Class

If an inner class has been defined within a code block (typically within the body of a method), then such an inner class is called a local inner class. A local inner class is not a member of the enclosing class and hence it can not have any access specifier. A local inner class will have access to all the members of the enclosing class and it’ll have access to the local final variables in the scope it’s defined.

Example: a typical local inner class

public class EnclosingClass{

public methodName(){

//…definition of the local inner class

class LocalInnerClass {

}

}

    1. Anonymous Inner Classes

If an inner class has been declared without a name and

within a code block (typically within the body of a method) then such an inner class is called an anonymous inner class. Since such an inner class doesn’t have a name associated, so it’ll be accessible only at the point where it is defined.

Example: a very common usage of an anonymous inner class

public class GUI extends JFrame{

public void buildComponents(){

button1 = newJButton();

button1.addActionListener(new java.awt.event.ActionListener(){

public void actionPerformed(java.awt.event.ActionEvent ae){

}

});

}

}

Some More in Detail:

Nested Classes in Java:

A nested class is a class defined inside the definition (body) of another enclosing class. A nested class can be of two types – static or non-static. A nested class is treated as a member of the enclosing class. A static nested class is not very tightly integrated with the enclosing class and it lives its own independent life as well i.e., a static nested class can be instantiated like any other class from just about anywhere. They are defined inside the definition of an enclosing class just to get a logical grouping of the classes, which in turn increases readability and provides better packaging convenience.

A static nested class can’t directly access the members of the enclosing class. Like any other top-level class it needs to access the members of the enclosing class via object references only.

Example: a static nested class

class EnclosingClass{

static class StaticNestedClass{

//…definition of the static nested class

}

}

A static nested class is accessed using the enclosing class name as follows:

EnclosingClass.StaticNestedClass staticNestedObjectRef = new EnclosingClass.StaticNestedClass();

Inner Classes in Java

A non-static nested class is called an inner class and it’s tightly integrated with the enclosing class unlike a static nested class. An inner class instance can’t exist independent to the enclosing class instance. An inner class instance always exist within the instance of the enclosing class. Since, it’s always associated with the enclosing class instance and it has direct access to all the members of the enclosing class – even the private members.

Example: an inner class

class EnclosingClass

{

class InnerClass{

//…definition of the inner class

}

}

Since, an instance of an inner class always exists within an instance of the enclosing class, hence we must instantiate the enclosing class first and then on that instance we can instantiate the inner class:-

EnclosingClass enclosingObjectRef = new EnclosingClass();

EnclosingClass.InnerClass innerObjectRef = enclosingObjectRef.new InnerClass();

Can an Inner Class declare static members?

No. Because any instance of an inner class is always associated with an instance of the enclosing class.

Can we have private or protected access for classes in Java?

Yeah… but only for nested classes and not for top-level classes. Nested classes are treated as members of the enclosing classes and hence we can specify any of the four access specifiers – private, package, protected, or public. We don’t have this luxury with top-level classes – they can only be declared public or package.

JDBC:

  • JDBC[Java DataBase Connectivity] developed because in java ODBC [Open Database Connectivity] is not supported.
  • JDBC is an API[Appliaction Protocol Interface] of java.

Queries Types:

  • DDL [Data Definition Language  ] – create,alter,drop,truncate.
  • DML [Data Manipulation Language] – insert,update,delete.
  • DQL  [Data Query Language]- select.
  • DCL [Data Control Language]- grant,revoke.

Types of SQL Statements [ By Oracle.com]

The tables in the following sections provide a functional summary of SQL statements and are divided into these categories:

  • Data Definition Language (DDL) Statements
  • Data Manipulation Language (DML) Statements
  • Transaction Control Statements
  • Session Control Statements
  • System Control Statement
  • Embedded SQL Statements

Types

There are commercial and free drivers available for most relational database servers. These drivers fall into one of the following types:

  • Type 1 that calls native code of the locally available ODBC driver.

1.Only in stationary system not in N/W

  1. Very Fast
  • Type 2 that calls database vendor native library on a client side. This code then talks to database over network.

1.Native API provided by the vendor

  1. Only in Standalone system.
  • Type 3, the pure-java driver that talks with the server-side middleware that then talks to database.

1.Require Client & Server driver

  1. Using native API
  2. Support DB in N/W
  • Type 4, the pure-java driver that uses database native protocol.
  1. Vastly Used Driver.
  2. Platform Independent.

STEPS:

    • Load the Driver.

class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

    • Connect & Establish the connection.

Connection con=DriverManager.getConnection(jdbc:odbc:datasourcename);

    • Execute/Update/Statement Query.

statement.executeUpdate(“Query”)

        1. execute() – DDL
        2. executeUpdate() – DML
        3. executeQuery() – DQL

Prepare Statement:

      • Prepared statement is a template. That used to insert data’s into DB dynamically instead of Hard Coded values.
      • It used to reduce complexity to avoid concatenation complexity.
      • It will execute only once.
      • It allow user for write code and pass many data’s according to the placeholders “?”

PreparedStatement = connection.PrepareStatement(“Query”) ;

BATCH:

It’s used for inserting operation. Its similar to a script file that we execute it all the queries at a time.

Steps:

    • CreateBatch();

1.Statemet

2.Prepare Statement

    • addBatch();
    • ExecuteBatch();

Connection Pooling:

      • Its a process of reusing the pre-created connection.
      • No need to create new connection. It will reuse the created connection according to the request from the client.

Ex: for 20 users we create 5 connection and reuse it.

JNDI – Java Naming Direcctory Interface

Wrapper Class:

    Wrapper class is a wrapper around a primitive data type. It represents primitive data types in their corresponding class instances e.g. a boolean data type can be represented as a Boolean class instance. All of the primitive wrapper classes in Java are immutable i.e. once assigned a value to a wrapper class instance cannot be changed further.

Wrapper Classes are used broadly with Collection classes in the java.util package and with the classes in the java.lang.reflect reflection package.

Following table lists the primitive types and the corresponding wrapper classes:

Primitive Wrapper
boolean  java.lang.Boolean
byte  java.lang.Byte
char  java.lang.Character
double  java.lang.Double
float  java.lang.Float
int  java.lang.Integer
long  java.lang.Long
short  java.lang.Short
void  java.lang.Void

In Java 5.0 version, additional wrapper classes were introduced in the java.util.concurrent.atomicpackage. They provide atomic operations for assignment, addition and increment. These classes act like variables  and cannot be used as a substitute for the regular wrapper classes. Few of these new wrapper classes like AtomicInteger and AtomicLong are the subclasses of the Number Classes.

Primitive Wrapper
boolean  AtomicBoolean
int  AtomicInteger
long  AtomicLong
V  AtomicReference<V>

Features Of the Wrapper Classes

Some of the sound features maintained by the Wrapper Classes are as under :

  • All the methods of the wrapper classes are static.
  • The Wrapper class does not contain constructors.
  • Once a value is assigned to a wrapper class instance it can not be changed, anymore.

Wrapper Classes : Methods with examples

There are some of the methods of the Wrapper class which are used to manipulate the data. Few of them are given below:

  1.  add(int, Object): Learn to insert an element at the specified position.
  2.  add(Object): Learn to insert an object at the end of a list.
  3.  addAll(ArrayList): Learn to insert an array list of objects to another list.
  4.  get(): Learn to retrieve the elements contained with in an ArrayList object.
  5.  Integer.toBinaryString(): Learn to convert the Integer type object to a String object.
  6.  size(): Learn to get the dynamic capacity of a list.
  7.  remove(): Learn to remove an element from a particular position specified by a  index value.
  8.  set(int, Object): Learn to replace an element at the position specified by a  index value.

Collections:

  • It’s store the collection of object in same (or) different type into a single object.
  • A collection is simply an object that groups multiple elements into a single unit. It is also called as a container sometimes. It is used to store, retrieve, manipulate, and communicate aggregate data.
  • It’s available in java.util.*;

Types:

  • Set –  Will not allow duplicate values [Hash set, Tree set]
  • List – Allow duplicate Values [Linked List, Array]
  • Map – Store both set & List values. Associate values with key [Tree & Hash Map]
  • All are interfaces.

Advantages of collections framework:

  1. It provides a standard interface for collections that fosters software reuse and also provides algorithms to manipulate them.
  2. It provides useful data structures and algorithms that reduces programming effort due to which we need not to write them ourselves.
  3. It provides high-performance implementations of useful data structures and algorithms that increases the performance.
  4. Collection is resizable and can grow.

Disadvantages of collections framework:

  1. It must cast to correct type.
  2. It can’t be done compile-time type checking.

Boxing & Unboxing:

  • Boxing & unboxing is the process of converting a primitive value into an object oriented wrapper class (boxing), or converting a value from an object oriented wrapper class back to the primitive value (unboxing).
  • For example, in java, you may need to convert an int value into an Integer (boxing) if you want to store it in a Collection because primitives can’t be stored in a Collection, only objects. But when you want to get it back out of the Collection you may want to get the value as an int and not anInteger so you would unbox it.
  • Autoboxing can be problematic if not used carefully. The classic is to end up with a NullPointerException and not be able to track it down.

Java Collections Interview Questions

What is HashMap and Map?

Map is Interface and Hashmap is class that implements this interface.

What is the significance of ListIterator?

Or

What is the difference b/w Iterator and ListIterator?

Iterator : Enables you to cycle through a collection in the forward direction only, for obtaining or removing elements

ListIterator : It extends Iterator, allow bidirectional traversal of list and the modification of elements

Difference between HashMap and HashTable? Can we make hashmap synchronized?

  1. 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 doesn’t allow nulls).
  2. HashMap does not guarantee that the order of the map will remain constant over time.
  3. HashMap is non synchronized whereas Hashtable is synchronized.
  4. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn’t.

Note on Some Important Terms

1)Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.

2)Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object “structurally”, a concurrent modification exception will be thrown. It is possible for other threads though to invoke “set” method since it doesn’t modify the collection “structurally”. However, if prior to calling “set”, the collection has been modified structurally, “IllegalArgumentException” will be thrown.

HashMap can be synchronized by

Map m = Collections.synchronizeMap(hashMap);

What is the difference between set and list?

A Set stores elements in an unordered way and does not contain duplicate elements, whereas a list stores elements in an ordered way but may contain duplicate elements.

Difference between Vector and ArrayList? What is the Vector class?

Vector is synchronized whereas ArrayList is not. The Vector class provides the capability to implement a growable array of objects. ArrayList and Vector class both implement the List interface. Both classes are implemented using dynamically resizable arrays, providing fast random access and fast traversal. In vector the data is retrieved using the elementAt() method while in ArrayList, it is done using the get() method. ArrayList has no default size while vector has a default size of 10. when you want programs to run in multithreading environment then use concept of vector because it is synchronized. But ArrayList is not synchronized so, avoid use of it in a multithreading environment.

What is an Iterator interface? Is Iterator a Class or Interface? What is its use?

The Iterator is an interface, used to traverse through the elements of a Collection. It is not advisable to modify the collection itself while traversing an Iterator.

What is the Collections API?

The Collections API is a set of classes and interfaces that support operations on collections of objects.

Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.

Example of interfaces: Collection, Set, List and Map.

What is the List interface?

The List interface provides support for ordered collections of objects.

How can we access elements of a collection?

We can access the elements of a collection using the following ways:

1.Every collection object has get(index) method to get the element of the object. This method will return Object.

2.Collection provide Enumeration or Iterator object so that we can get the objects of a collection one by one.

What is the Set interface?

The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.

What’s the difference between a queue and a stack?

Stack is a data structure that is based on last-in-first-out rule (LIFO), while queues are based on First-in-first-out (FIFO) rule.

What is the Map interface?

The Map interface is used associate keys with values.

What is the Properties class?

The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used.

Which implementation of the List interface provides for the fastest insertion of a new element into the middle of the list?

  1. Vector
  2. ArrayList
  3. LinkedList
  4. None of the above

ArrayList and Vector both use an array to store the elements of the list. When an element is inserted into the middle of the list the elements that follow the insertion point must be shifted to make room for the new element. The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of the links at the point of insertion. Therefore, the LinkedList allows for fast insertions and deletions.

How can we use hashset in collection interface?

This class implements the set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the Null element.

This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets.

What are differences between Enumeration, ArrayList, Hashtable and Collections and Collection?

Enumeration: It is series of elements. It can be use to enumerate through the elements of a vector, keys or values of a hashtable. You can not remove elements from Enumeration.

ArrayList: It is re-sizable array implementation. Belongs to ‘List’ group in collection. It permits all elements, including null. It is not thread -safe.

Hashtable: It maps key to value. You can use non-null value for key or value. It is part of group Map in collection.

Collections: It implements Polymorphic algorithms which operate on collections.

Collection: It is the root interface in the collection hierarchy.

What is difference between array & arraylist?

An ArrayList is resizable, where as, an array is not. ArrayList is a part of the Collection Framework. We can store any type of objects, and we can deal with only objects. It is growable. Array is collection of similar data items. We can have array of primitives or objects. It is of fixed size. We can have multi dimensional arrays.

Array: can store primitive            ArrayList: Stores object only

Array: fix size                            ArrayList: resizable

Array: can have multi dimensional

Array: lang                                ArrayList: Collection framework

Can you limit the initial capacity of vector in java?

Yes you can limit the initial capacity. We can construct an empty vector with specified initial capacity

public vector(int initialcapacity)

What method should the key class of Hashmap override?

The methods to override are equals() and hashCode().

What is the difference between Enumeration and Iterator?

The functionality of Enumeration interface is duplicated by the Iterator interface. Iterator has a remove() method while Enumeration doesn’t. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as using Iterator we can manipulate the objects also like adding and removing the objects.

So Enumeration is used when ever we want to make Collection objects as Read-only.

String:

    • “==” is used to determine is the two variable in same memory location.
    • equals()  is used to determine the values in the string variable is same or not.

I/O Stream:

Byte Streams:

    • Input Stream
    • Output Stream
    • File Input Stream
    • File Output Stream
    • Byte Array Input Stream
    • Byte Array Output Stream
    • Filtered Byte Stream
    • Buffered Byte Stream
    • Sequence Input Stream
    • PrintStream
    • Data Input/Output Stream
    • Random Access file

Character Stream:

    • Reader
    • Writer
    • FileReader
    • FileWriter
    • CharArray Reader
    • CharArray Writer
    • Buffered Reader/ Writer
    • Pushback Reader
    • PrintWriter

Serialization:

    • Serialization is the process of saving an object in a storage medium (such as a file, or a memory buffer) or to transmit it over a network connection  in binary form.
    • The serialized objects are JVM independent and can be re-serialized by any JVM. In this case the “in memory” java objects state are converted into a byte stream.
    • This type of the file can not be understood by the user.
    • It is a special types of object i.e. reused by the JVM (Java Virtual Machine). This process of serializing an object is also called deflating or marshalling an object.
    • The object to be serialized must implement java.io.Serializable class.
    • Serialization is the process of converting a set of object instances that contain references to each other into a linear stream of bytes, which can then be sent through a socket, stored to a file, or simply manipulated as a stream of data.

RMI: [It’s an out dated concept its used rarely in modern programming]

    The RMI application comprises of the two separate programs, a server and a client. A typical server program creates some remote objects, makes references to these objects accessible, and waits for clients to invoke methods on these objects. The RMI application provides the mechanism by which the server and the client communicate and pass information back and forth. The RMI distributed application uses the RMI Registry to obtain a reference to a remote object. The server calls the registry to associate a name with a remote object. The client looks up the remote object by its name in the server?s registry and then invokes a method on it

.

Stubs and Skeletons

RMI uses a standard mechanism (employed in RPC systems) for communicating with remote objects: stubs and skeletons. A stub for a remote object acts as a client’s local representative or proxy for the remote object. The caller invokes a method on the local stub which is responsible for carrying out the method call on the remote object. In RMI, a stub for a remote object implements the same set of remote interfaces that a remote object implements.

When a stub’s method is invoked, it does the following:

1) initiates a connection with the remote JVM containing the remote object,

2) marshals (writes and transmits) the parameters to the remote JVM,

3) waits for the result of the method invocation,

4) unmarshals (reads) the return value or exception returned, and

5) returns the value to the caller.

The stub hides the serialization of parameters and the network-level communication in order to present a simple invocation mechanism to the caller.

In the remote JVM, each remote object may have a corresponding skeleton (in Java 2 platform-only environments, skeletons are not required).

The skeleton is responsible for dispatching the call to the actual remote object implementation.

When a skeleton receives an incoming method invocation it does the following:

1) unmarshals (reads) the parameters for the remote method,

2) invokes the method on the actual remote object implementation, and

3) marshals (writes and transmits) the result (return value or exception) to the caller.

  • A client SOAP Engine contains the stubs objects. The server SOAP Engine contians the skeleton objects.

Steps In Stub and Skeleton:

  1. When a client business object makes a web service call, at a lowever-level the stub object communicates with the skeleton on the server.
  2. The web service code on the server connects to the other application.
  3. The other application executes some process or function.
  4. The other application returns some value to the web service code on the server.
  5. The skelton on the sever sends value to stub object from client.
  6. The stub object on client returns value to client business object.
  7. The End

Applet :

    Applet is java program that can be embedded into HTML pages. Java applets runs on the java enables web browsers such as mozila and internet explorer. Applet is designed to run remotely on the client browser, so there are some restrictions on it. Applet can’t access system resources on the local computer. Applets are used to make the web site more dynamic and entertaining.

Advantages of Applet:

  • Applets are cross platform and can run on Windows, Mac OS and Linux platform
  • Applets can work all the version of Java Plugin
  • Applets runs in a sandbox, so the user does not need to trust the code, so it can work without security approval
  • Applets are supported by most web browsers
  • Applets are cached in most web browsers, so will be quick to load when returning to a web page
  • User can also have full access to the machine if user allows

Disadvantages of Java Applet:

  • Java plug-in is required to run applet
  • Java applet requires JVM so first time it takes significant startup time
  • If applet is not already cached in the machine, it will be downloaded from internet and will take time
  • Its difficult to design and build good user interface in applets compared to HTML .

Life Cycle:

    Applet runs in the browser and its lifecycle method are called by JVM when it is loaded and destroyed. Here are the lifecycle methods of an Applet:

init(): This method is called to initialized an applet

start(): This method is called after the initialization of the applet.

stop(): This method can be called multiple times in the life cycle of an Applet.

destroy(): This method is called only once in the life cycle of the applet when applet is destroyed.

What is serialization ?

Serialization is the process of writing complete state of java object into output stream, that stream can be file or byte array or stream associated with TCP/IP socket.

What is Externalizable Interface ?

Externalizable interface is a subclass of Serializable. Java provides Externalizable interface that gives you more control over what is being serialized and it can produce smaller object footprint. ( You can serialize whatever field values you want to serialize)

This interface defines 2 methods: readExternal() and writeExternal() and you have to implement these methods in the class that will be serialized. In these methods you’ll have to write code that reads/writes only the values of the attributes you are interested in. Programs that perform serialization and deserialization have to write and read these attributes in the same sequence.

Explain garbage collection ?

Garbage collection is an important part of Java’s security strategy. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects from the memory. The name “garbage collection” implies that objects that are no longer needed by the program are “garbage” and can be thrown away. A more accurate and up-to-date metaphor might be “memory recycling.” When an object is no longer referenced by the program, the heap space it occupies must be recycled so that the space is available for subsequent new objects. The garbage collector must somehow determine which objects are no longer referenced by the program and make available the heap space occupied by such unreferenced objects. In the process of freeing unreferenced objects, the garbage collector must run any finalizers of objects being freed

How you can force the garbage collection ?

Garbage collection automatic process and can’t be forced. We can call garbage collector in Java by calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected.

what is a collection ?

Collection is a group of objects. java.util package provides important types of collections. There are two fundamental types of collections they are Collection and Map. Collection types hold a group of objects, Eg. Lists and Sets where as Map types hold group of objects as key, value pairs Eg. HashMap and Hashtable.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s