0% found this document useful (0 votes)
16 views8 pages

Java Hashtable and Collections Overview

Uploaded by

kramesh6590
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views8 pages

Java Hashtable and Collections Overview

Uploaded by

kramesh6590
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

 When using a Hashtable, you specify an object that is used as a key and the value

(data) that you want linked to that key.

Constructors : Hashtable() Hashtable(int size)

Methods :
Object put(Object key,Object value) : Inserts a key and a value into the hashtable.
Object get(Object key) : Returns the object that contains the value associated with
key.

boolean contains(Object value) : Returns true if the given value is available in the
hashtable. If not, returns false.
boolean containsKey(Object key) : Returns true if the given key is available in the
hashtable. If not, returns false.
Enumeration elements() : Returns an enumeration of the values contained in the
hashtable.
int size() : Returns the number of entries in the hashtable.

Properties

•Properties is a subclass of Hashtable


• Used to maintain lists of values in which the key is a String and the value is also a
String
• Constructors
Properties()
Properties(Properties propDefault) : Creates an object that uses propDefault for its
default value.
Methods :
String getProperty(String key) : Returns the value associated with key.

Strng getProperty(String key, String defaultProperty) : Returns the value


associated with key. defaultProperty is returned if key is neither in the list nor in the
default property list .
Enumeration propertyNames() : Returns an enumeration of the keys. This includes
those keys found in the default property list.

The Interfaces in Collections Framework

Collection Map
Iterator

Set List SortedMap ListIterator


|
SortedSet

Collection :
 A collection allows a group of objects to be treated as a single unit.
 The Java collections library forms a framework for collection classes.
 The CI is the root of collection hierarchy and is used for common functionality across
all collections.
 There is no direct implementation of Collection Interface.
 Two fundamental interfaces for containers:
• Collection
boolean add(Object element) : Inserts element into a collection

Set Interface: extends Collection Interface. The Class Hash set implements Set
Interface.
 Is used to represent the group of unique elements.
 Set stores elements in an unordered way but does not contain duplicate elements.
 identical to Collection interface, but doesn’t accept duplicates.

Sorted set : extends Set Interface. The class Tree Set implements Sorted set Interface.
 It provides the extra functionality of keeping the elements sorted.
 It represents the collection consisting of Unique, sorted elements in ascending order.
 expose the comparison object for sorting.

List Interface :
 ordered collection – Elements are added into a particular position.
 Represents the sequence of numbers in a fixed order.
 But may contain duplicate elements.
 Elements can be inserted or retrieved by their position in the List using Zero based
index.
 List stores elements in an ordered way.

Map Interface: Basic [Link] classes Hash Map & HashTable implements Map
interface.
 Used to represent the mapping of unique keys to values.
 By using the key value we can retrive the values.
 Two basic operations are get( ) & put( ) .

boolean put(Object key, Object value) : Inserts given value into map with key
Object get(Object key) : Reads value for the given key.

Tree Map Class: Implements Sorted Set Interface.


 The elements are stored in sorted ascending order.
 Using key value we can retrieve the data.
 Provides an efficient means of storing key/value pairs in sorted order and allows rapid
retrivals.

TreeMap tm=new TreeMap( );


[Link]( “Prasad”,new Double(74.6));

The Classes in Collections Framework


Abstract Collection

Abstract List Abstract Set Abstract Map

Abstract Array List Hash Set Tree Set Hash Map Tree
Map
Sequential
List

Linked List
ArrayList
• Similar to Vector: it encapsulates a dynamically reallocated Object[] array
• Why use an ArrayList instead of a Vector?
• All methods of the Vector class are synchronized, It is safe to access a Vector object
from two threads.
• ArrayList methods are not synchronized, use ArrayList in case of no synchronization
• Use get and set methods instead of elementAt and setElementAt methods of vector

HashSet
• Implements a set based on a hashtable
• The default constructor constructs a hashtable with 101 buckets and a load factor of
0.75
HashSet(int initialCapacity)
HashSet(int initialCapacity,float loadFactor)
loadFactor is a measure of how full the hashtable is allowed to get before its capacity is
automatically increased
• Use Hashset if you don’t care about the ordering of the elements in the collection

TreeSet
• Similar to hash set, with one added improvement
• A tree set is a sorted collection
• Insert elements into the collection in any order, when it is iterated, the values are
automatically presented in sorted order

• Maps : Two implementations for maps:

HashMap
 hashes the keys
 The Elements may not in Order.
 Hash Map is not synchronized and permits null values
 Hash Map is not serialized.
 Hash Map supports Iterators.

TreeMap
• uses a total ordering on the keys to organize them in a search tree
• The hash or comparison function is applied only to the keys
• The values associated with the keys are not hashed or compared.

How are memory leaks possible in Java


If any object variable is still pointing to some object which is of no use, then JVM will not
garbage collect that object and object will remain in memory creating memory leak

What are the differences between EJB and Java beans


the main difference is Ejb componenets are distributed which means develop once and
run anywhere. java beans are not distributed. which means the beans cannot be
shared .

What would happen if you say this = null


this will give a compilation error as follows
cannot assign value to final variable this

Will there be a performance penalty if you make a method synchronized? If so,


can you make any design changes to improve the performance
[Link] performance will be down if we use synchronization.
one can minimise the penalty by including garbage collection algorithm, which reduces
the cost of collecting large numbers of short- lived objects. and also by using Improved
thread synchronization for invoking the synchronized [Link] invoking will be faster.

How would you implement a thread pool


public class ThreadPool extends [Link] implements ThreadPoolInt
This class is an generic implementation of a thread pool, which takes the following input
a) Size of the pool to be constructed
b) Name of the class which implements Runnable (which has a visible default
constructor)
and constructs a thread pool with active threads that are waiting for activation. once the
threads have finished processing they come back and wait once again in the pool.
This thread pool engine can be locked i.e. if some internal operation is performed on the
pool then it is preferable that the thread engine be locked. Locking ensures that no new
threads are issued by the engine. However, the currently executing threads are allowed
to continue till they come back to the passivePool

How does serialization work


Its like FIFO method (first in first out)

How does garbage collection work


There are several basic strategies for garbage collection: reference counting, mark-
sweep, mark-compact, and copying. In addition, some algorithms can do their job
incrementally (the entire heap need not be collected at once, resulting in shorter
collection pauses), and some can run while the user program runs (concurrent
collectors). Others must perform an entire collection at once while the user program is
suspended (so-called stop-the-world collectors). Finally, there are hybrid collectors, such
as the generational collector employed by the 1.2 and later JDKs, which use different
collection algorithms on different areas of the heap

How would you pass a java integer by reference to another function


Passing by reference is impossible in JAVA but Java support the object reference so.
Object is the only way to pass the integer by refrence.

What is the sweep and paint algorithm


The painting algorithm takes as input a source image and a list of brush sizes. sweep
algo is that it computes the arrangement of n lines in the plane ... a correct algorithm,

Can a method be static and synchronized


no a static mettod can't be synchronised

Do multiple inheritance in Java


Its not possible directly. That means this feature is not provided by Java, but it can be
achieved with the help of Interface. By implementing more than one interface.

What is data encapsulation? What does it buy you


The most common example I can think of is a javabean. Encapsulation may be used
by creating 'get' and 'set' methods in a class which are used to access the fields of the
object. Typically the fields are made private while the get and set methods are public.
Encapsulation can be used to validate the data that is to be stored, to do
calculations on data that is stored in a field or fields, or for use in introspection (often the
case when using javabeans in Struts, for instance).

What is reflection API? How are they implemented


Reflection package is used mainlyfor the purpose of getting the class name. by using
the getName method we can get name of the class for particular application .
Reflection is a feature of the Java programming language. It allows an executing
Java program to examine or "introspect" upon itself, and manipulate internal properties
of the program.
What are the primitive types in Java
According to Java in a Nutshell, 5th ed
boolean, byte, char, short, long float, double, int
Is there a separate stack for each thread in Java
No
What is heap in Java
JAVA is fully Object oriented language. It has two phases first one is Compilation
phase and second one is interpratation phase. The Compilation phase convert the java
file to class file (byte code is only readable format of JVM) than Intepratation phase
interorate the class file line by line and give the proper result.

In Java, how are objects / values passed around


In Java Object are passed by reference and Primitive data is always pass by value
Do primitive types have a class representation
Primitive data type has a wrapper class to present.
Like for int - Integer , for byte Byte, for long Long etc ...

How all can you free memory


With the help of finalize() method.
If a programmer really wants to explicitly request a garbage collection at some point,
[Link]() or [Link]() can be invoked, which will fire off a garbage collection at
that time.
Does java do reference counting
It is more likely that the JVMs you encounter in the real world will use a tracing
algorithm in their garbage-collected heaps
What does a static inner class mean? How is it different from any other static
member
A static inner class behaves like any ``outer'' class. It may contain methods and fields.
It is not necessarily the case that an instance of the outer class exists even when
we have created an instance of the inner class. Similarly, instantiating the outer class
does not create any instances of the inner class.
The methods of a static inner class may access all the members (fields or methods)
of the inner class but they can access only static members (fields or methods) of the
outer class. Thus, f can access the field x, but it cannot access the field y.

How do you declare constant values in java


Using Final keyword we can declare the constant values How all can you instantiate final
members Final member can be instantiate only at the time of declaration. null

How is serialization implemented in Java


A particular class has to implement an Interface [Link] for implementing
serialization. When you have an object passed to a method and when the object is
reassigned to a different one, then is the original reference lost No Reference is not lost.
Java always passes the object by reference, now two references is pointing to the same
object.
What are the different kinds of exceptions? How do you catch a Runtime
exception
There are 2 types of exceptions.
1. Checked exception
2. Unchecked exception.
Checked exception is catched at the compile time while unchecked exception is
checked at run time.
[Link] Exceptions : Environmental error that cannot necessarily be detected by
testing; e.g. disk full, broken socket, database unavailable, etc.
2. Unchecked exception.
Errors : Virtual machine error: class not found, out of memory, no such method, illegal
access to private field, etc.
Runtime Exceptions :Programming errors that should be detected in testing: index out of
bounds, null pointer, illegal argument, etc.
Checked exceptions must be handled at compile time. Runtime exceptions do not need
to be. Errors often cannot be

What are the differences between JIT and HotSpot


The Hotspot VM is a collection of techniques, the most significant of which is called
"adaptive optimization.
The original JVMs interpreted bytecodes one at a time. Second-generation JVMs added a
JIT compiler, which compiles each method to native code upon first execution, then
executes the native code. Thereafter, whenever the method is called, the native code is
executed. The adaptive optimization technique used by Hotspot is a hybrid approach,
one that combines bytecode interpretation and run-time compilation to native code.
Hotspot, unlike a regular JIT compiling VM, doesn't do "premature optimization"

What is a memory footprint? How can you specify the lower and upper limits of
the RAM used by the JVM? What happens when the JVM needs more memory?
when JVM needs more memory then it does the garbage collection, and sweeps all the
memory which is not being used.

What are the disadvantages of reference counting in garbage collection?


An advantage of this scheme is that it can run in small chunks of time closely
interwoven with the execution of the program. This characteristic makes it particularly
suitable for real-time environments where the program can't be interrupted for very long.
A disadvantage of reference counting is that it does not detect cycles. A cycle is two or
more objects that refer to one another, for example, a parent object that has a reference
to its child object, which has a reference back to its parent. These objects will never have
a reference count of zero even though they may be unreachable by the roots of the
executing program. Another disadvantage is the overhead of incrementing and
decrementing the reference count each time. Because of these disadvantages, reference
counting currently is out of favor.

Is it advisable to depend on finalize for all cleanups


The purpose of finalization is to give an opportunity to an unreachable object to
perform any clean up before the object is garbage collected, and it is advisable.

can we declare multiple main() methods in multiple classes. ie can we have


each main method in its class in our program?
YES
JDBC

How to Interact with DB?


Generally every DB vendor provides a User Interface through which we can easily
execute SQL query’s and get the result (For example Oracle Query Manager for Oracle,
and TOAD ([Link]) tool common to all the databases). And these tools will help
DB developers to create database. But as a programmer we want to interact with the DB
dynamically to execute some SQL queries from our application (Any application like C,
C++, JAVA etc), and for this requirement DB vendors provide some Native Libraries
(Vendor Specific) using this we can interact with the DB i.e. If you want to execute some
queries on Oracle DB, oracle vendor provides an OCI (Oracle Call Interface) Libraries to
perform the same.

About ODBC
What is ODBC
ODBC (Open Database Connectivity) is an ISV (Independent software vendor product)
composes of native API to connect to different databases through via a single API called
ODBC.
Open Database Connectivity (ODBC) is an SQL oriented application programming
interface developed by in collaboration with IBM and some other database vendors.
ODBC comes with Microsoft products and with all databases on Windows OS.
ODBC Architecture
Oracle ODBC SP API Oracle

Front End SQL server SP API SQL


Application ODBC API ODBC
server
“C”
function Sybase ODBC
SP API Sybase
calls

Oracle DSN
Oracle ODBC
My DSN Oracle

SQL Server DSN SQL server ODBC


SQL

Sybase DSN
Sybase ODBC Sybase
Our DSN

Advantages
 Single API (Protocol) is used to interact with any DB
 Switching from one DB to another is easy
 Doesn’t require any modifications in the Application when you want to shift
from one DB to other.
What for JDBC?
As we have studied about ODBC and is advantages and came to know that it
provides a common API to interact with any DB which has an ODBC Service Provider’s
Implementation written in Native API that can be used in your applications.
If an application wants to interact with the DB then the options which have been
explained up to now in this book are:
1. Using Native Libraries given by the DB vendor
2. Using ODBC API
And we have listed there Advantages and Disadvantages.
But if the application is a JAVA application then the above given options are not
recommended to be used due to the following reasons
1. Native Libraries given by DB vendor
a. Application becomes vendor dependent and
b. The application has to use JNI to interact with Native Lib which may cause serious
problem for Platform Independency in our applications.
2. And the second option given was using ODBC API which can solve the 1.a problem
but again this ODBC API is also a Native API, so we have to use JNI in our Java
applications which lead to the 1.b described problem.
And the answer for these problems is JDBC (Java Data Base Connectivity) which provides
a common Java API to interact with any DB.

What is JDBC
As explained above JDBC standards for Java Data Base Connectivity. It is a
specification given by Sun Microsystems and standards followed by X/Open SAG (SQL
Access Group) CLI (Call Level Interface) to interact with the DB.
Java programing language methods. The JDBC API provides database-independent
connectivity between the JAVA Applications and a wide range of tabular data bases. JDBC
technology allows an application component provider to:
 Perform connection and authentication to a database server
 Manage transactions
 Moves SQL statements to a database engine for preprocessing and
execution
 Executes stored procedures
 Inspects and modifies the results from SELECT statements
JDBC API
JDBC API is divided into two parts
1. JDBC Core API
2. JDBC Extension or Optional API
JDBC Core API ([Link] package)
This part of API deals with the following futures
1. Establish a connection to a DB
2. Getting DB Details
3. Getting Driver Details
4. maintaining Local Transaction
5. executing query’s
6. getting result’s (ResultSet)
7. preparing pre-compiled SQL query’s and executing
8. executing procedures & functions
JDBC Ext OR Optional API ([Link] package)
This part of API deals with the following futures
1. Resource Objects with Distributed Transaction Management support
2. Connection Pooling.
These two parts of Specification are the part of J2SE and are inherited into J2EE i.e.
this specification API can be used with all the component’s given under J2SE and J2EE.
JDBC Architecture:
JDBC Application

JDB
C
JDBC Driver SP
S
S AP
P
P

Oracle DB MS SQL Sybase DB


Server DB
In the above show archetecture diagram the JDBC Driver forms an abstraction
layer between the JAVA Application and DB, and is implemented by 3 rd party vendors or a
DB Vendor. But whoever may be the vendor and what ever may be the DB we need not
to worry will just us JDCB API to give instructions to JDBC Driver and then it’s the
responsibility of JDBC Driver Provider to convert the JDBC Call to the DB Specific Call.
And this 3rd party vendor or DB vendor implemented Drivers are classified into 4-Types
namely

You might also like