Java Concepts
The String class represents character strings. All string literals in Java programs, such as “abc”, are implemented as instances of this class.
Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared
There are two ways to create a String object in Java:
Using the new operator. For example,
String str = new String ("Hello").
Using a string literal or constant expression. For example,
String str="Hello"; (string literal)
str1 == str2 = false.
str1.equals (str2) = true.
when you use String a=new String(”Hello”);
a String object is created out of the String literal pool, even if an equal string already exists in the pool.
when you use String str="Hello";
To cut down the number of String objects created in the JVM, the String class keeps a pool of strings. Each time your code create a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool. Java can make this optimization since strings are immutable and can be shared without fear of data corruption.
String objects created with the new operator do not refer to objects in the string pool but can be made to using String’s intern() method. The java.lang.String.intern() returns an interned String, that is, one that has an entry in the global String pool. If the String is not already in the global String pool, then it will be added.
String buffers:
A string buffer implements a mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.
String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.
String buffers are used by the compiler to implement the binary string concatenation operator +. For example, the code:
x = “a” + 4 + “c”
is compiled to the equivalent of:
x = new StringBuffer().append(”a”).append(4).append(”c”)
.toString()
which creates a new string buffer (initially empty), appends the string representation of each operand to the string buffer in turn, and then converts the contents of the string buffer to a string. Overall, this avoids creating many temporary strings.
In general, if sb refers to an instance of a StringBuffer, then sb.append(x) has the same effect as sb.insert(sb.length(), x).
Method overloading:
- overloaded methods can have the same name but must have different parameter lists
- parameter lists are considered different if the order of the arguments are different
- a subclass method can overload a superclass method
Super class:
test(int i, long j);
Sub class
test(long j, int i);
Overloading constructors
- you can overload constructors within the same class
class SuperCtor {
SuperCtor(){}
SuperCtor(int i) {} // compiles ok
}
Polymorphism:
Polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface.
Parametric polymorphism
Using parametric polymorphism, a function can be written generically so that it can handle values identically without depending on their type.
Subtyping polymorphism
Some languages like Java employ the idea of subtypes to restrict the range of types that can be used in a particular case of parametric polymorphism. In these languages, subtyping polymorphism (sometimes referred to as dynamic polymorphism) allows a function to be written to take an object of a certain type T, but also work correctly if passed an object that belongs to a type S that is a subtype of T.
Ad-hoc polymorphism
ad-hoc polymorphism to refer to polymorphic functions which can be applied to arguments of different types, but which behave differently depending on the type of the argument to which they are applied (also known as function overloading).
Overloading allows multiple functions taking different types to be defined with the same name; the compiler or interpreter automatically calls the right one. This way, functions appending lists of integers, lists of strings, lists of real numbers, and so on could be written, and all be called append—and the right append function would be called based on the type of lists being appended.
This differs from parametric polymorphism, in which the function would need to be written generically, to work with any kind of list.
Reflection API
The Reflection API allows Java code to examine classes and objects at run time. The new reflection classes allow you to call another class’s methods dynamically at run time. With the reflection classes, you can also examine an instance’s fields and change the fields’ contents.
The Reflection API consists of the java.lang.Class class and the java.lang.reflect classes: Field, Method, Constructor, Array, and Modifier. The first three of these classes represent the corresponding members of classes and interfaces. The Array class provides methods for creating, accessing, and modifying arrays. The last class provides methods for decoding modifiers (such as static and public) returned for classes and their components.
Method toExecuteMethod = this.getClass().getMethod( methodToExecute, parameterClasses );
String methodReturns = (String)toExecuteMethod.invoke(this, new Object[] { req, res } );
Collection
A collection is a group of data manipulate as a single object.
Collections are primarily defined through a set of interfaces
The Iterator Interface
Selects each element in a collection, Hides the underlying collection.
Collections in Java are organised around the following interfaces:
A set is a collection without duplicates.
A list is a collection which may have duplicates.
A map is an assignment of values to keys. Maps are not collections, but are related to them
———————————————-
Interface myCol = new ImplClass();
myCol.add(…);
myCol.add(…);
myCol.remove(…);
Iterator it = myCol.iterator();
while (it.hasNext())
{
Item i = (Item) it.next();
// do something with i
// possible: it.remove();
}
—————————————-
Collections
- automatically grown to size;
- only contain objects, not primitive datatypes.
- have many convenient methods, such as iterator().
Sorted collection implementations need to know how objects should be ordered. A class which implements the Comparable interface must have a compareTo method, which tells how objects of the class are ordered:
int compareTo (Object arg)
returns a negative, zero or positive integer according to whether the calling object is less, equal or greater than arg.
TreeSet is an implementation of the SortedSet interface, which keeps items in an ordered tree.
Thread:
A thread is a single sequential flow of control within a program. The thread behaviors include starting, sleeping, running, yielding, and having a priority. There are a number of situations where you might want to explicitly use threads to improve the performance, responsiveness, or organization of your programs. These include:
· Making the user interface more responsive when performing long tasks
· Performing asynchronous or background processing
There are two ways to create a thread. One is to subclass Thread and override the run() method; The other one is to implement the Runnable interface.
Subclassing Thread and overriding run() Method
The following is an example of creating a thread by subclassing the Thread class:
import java.lang.*;
public class MyThread extends Thread
{
public MyThread (int count) {
this.count = count;
}
private int count = 0;
public void run()
{
.... /*put all the code here that you want this
thread to accomplish */
}
}
The run() method is where the meat is, it contains the code to implement the logic that this thread class is designed to do.
The proper way to start this kind of threads is to call the start() method of the class:
MyThread t = new MyThread(5);
t.start();
Implementing the Runnable interface
The following is an example of creating a thread by implementing the Runnable interface:
class MyRunnable implements Runnable
{
public MyThread (int count) {
this.count = count;
}
private int count = 0;
public void run()
{
.... /*put all the code here that you want this
thread to accomplish */
}
}
The proper way to start this kind of threads is to create an instance of the Runnable class, and pass the reference to the Thread constructor, then call the start() method of the Thread:
MyRunnable r = new MyRunnable(5);
new Thread(r).start();
You should not invoke the run() method directly. If you call the run() method directly, it will simply execute in the caller’s thread instead of as its own thread. Instead, you need to call the start() method, which schedules the thread with the JVM. The JVM will call the corresponding run() method when the resources and CPU is ready.
The JDBC API makes it possible to do three things:
1. Establish a connection with a database or access any tabular data source
2. Send SQL statements
3. Process the results
Applications and applets can access databases via the JDBC API using pure Java JDBC technology-based drivers, as shown in this figure:
Left side, Type 4: Direct-to-Database Pure Java Driver
This style of driver converts JDBC calls into the network protocol used directly by DBMSs, allowing a direct call from the client machine to the DBMS server and providing a practical solution for intranet access.
Right side, Type 3: Pure Java Driver for Database Middleware
This style of driver translates JDBC calls into the middleware vendor’s protocol, which is then translated to a DBMS protocol by a middleware server. The middleware provides connectivity to many different databases.
Left side, Type 1: JDBC-ODBC Bridge plus ODBC Driver
This combination provides JDBC access via ODBC drivers. ODBC binary code — and in many cases, database client code — must be loaded on each client machine that uses a JDBC-ODBC Bridge. Sun provides a JDBC-ODBC Bridge driver, which is appropriate for experimental use and for situations in which no other driver is available.
Right side, Type 2: A native API partly Java technology-enabled driver
This type of driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine.
The fundamental steps involved in the process of connecting to a database and executing a query consist of the following:
· Import JDBC packages.
· Load and register the JDBC driver.
· Open a connection to the database.
· Create a statement object to perform a query.
· Execute the statement object and return a query resultset.
· Process the resultset.
· Close the resultset and statement objects.
· Close the connection.
————————————————–
import java.sql.*;
import oracle.jdbc.driver.*;
import oracle.sql.*;
//Load and register Oracle driver
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver
Or
Class.forName(”oracle.jdbc.driver.OracleDriver”);
//Establish a connection
Connection conn = DriverManager.getConnection(URL, username, passwd);
Connection conn = DriverManager.getConnection
(”jdbc:oracle:thin:@training:1521:Oracle”,”oratest”, oratest”);
//Create a Statement object
Statement sql_stmt = conn.createStatement();
//Create a ResultSet object, execute the query and return a resultset
ResultSet rset = sql_stmt.executeQuery
(”SELECT empno, ename, sal, deptno FROM emp ORDER BY ename”);
//Process the resultset, retrieve data in each row, column by column
while (rset.next())
{
str = rset.getInt(1);
}
rset.close();
sql_stmt.close();
conn.close();
The following code illustrates the use of exception handlers in JDBC:
try {
catch (SQLException e) { System.out.println(”ERR: “+ e.getMessage())}
———————————————————————
The static methods can not be overridden!
If a subclass defines a static method with the same signature as a static method in the superclass, the method in the subclass hides the one in the superclass.
Technically, all parameters in Java are pass-by-value.
All primitives are pass-by-value, period. When a primitive value is passed into a method, a copy of the primitive is made.
Main method
In order to invoke a main method from the command-line, it is now mandatory to declare the main method as public. If the main method has any access level other than public, it will no longer run from the command-line.
What is a most-specific method?
Resolving a method name at compile time is more complicated than resolving a field name because of the possibility of method overloading. Invoking a method at run time is also more complicated than accessing a field because of the possibility of instance method overriding.
Determining the method that will be invoked by a method invocation expression involves several steps:
Determine Class or Interface to Search
Determine Method Signature
What are the forward reference rules?
Using an instance variable before its declaration is called a forward reference. If an instance variable tries to forward reference another instance variable during initialization, the result in a compile-time error.
class Program {
int i = j; // compile-time error: incorrect forward reference
int j = 1;
}
Why always override hashcode() if overriding equals()?
In Java, every object has access to the equals() method because it is inherited from the Object class. However, this default implementation just simply compares the memory addresses of the objects. You can override the default implementation of the equals() method defined in java.lang.Object. If you override the equals(), you MUST also override hashCode().
Otherwise a violation of the general contract for Object.hashCode will occur.
public int hashCode()
Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.
The general contract of hashCode is:
1. Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer.
2. If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result
The default implementation of equals() method checks to see if the two objects have the same identity. Similarly, the default implementation of the hashCode() method returns an integer based on the object’s identity and is not based on the values of instance (and class) variables of the object.
The two instances of CustomerID are logically equal according to the class’s equals method. Because the hashCode() method is not overridden, these two instances’ identities are not in common to the default hashCode implementation. Therefore, the Object.hashCode returns two seemingly random numbers instead of two equal numbers. Such behavior violates “Equal objects must have equal hash codes” rule defined in the hashCode contract.
When is an object eligible for garbage collection?
An object is eligible for garbage collection when there are no more root set of references to that object. References that are held in a variable are usually dropped when the variable goes out of scope.
An executing Java program consists of a set of threads, each of which is actively executing a set of methods (one having called the next). Each of these methods can have arguments or local variables that are references to objects. These references are said to belong to a root set of references that are immediately accessible to the program.
All objects referenced by this root set of references are said to be reachable by the program in its current state and must not be collected. Also, those objects might contain references to still other objects, which are also reachable, and so on.
http://sreeraj.sulekha.com/blog/post/2008/07/java-concepts.htm
| Print article | This entry was posted by shivani on July 15, 2008 at 10:04 am, and is filed under Computers, Education and Training. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |







