Books Related to Java Technology

Sunday, January 25, 2009

Core JAVA Interview Questions & Answers-1





  1. What is the most important feature of Java?
    Java is a platform independent language.
  2. What do you mean by platform independence?
    Platform independence means that we can write and compile the java code in one platform like (Windows) and we can execute the class in any other supported platform like (Linux, Solaris etc).
  3. Is JVM platform independent?
    JVM is not platform independent. It is a platform specific run time implementation provided by the vendor.
  4. What is a JVM?
    JVM is Java Virtual Machine which is a run time environment for the compiled java class files.
  5. Difference between JRE/JVM/JDK? To See in Details Click on this Link:- http://javasks.blogspot.com/2009/01/difference-between-jre-jvm-and-jdk.html
  6. What is Externalizable? - Externalizable is an Interface that covers Serializable Interface. It sends data into Streams in Compressed Format. It has two methods, that is: writeExternal(ObjectOuput out) and readExternal(ObjectInput in).
  7. What is a pointer and does Java support pointers?
    Pointer is a reference deal to a memory location. Improper treating of pointers leads to memory escapes and reliability issues hence Java doesn't support the usage of pointers.
  8. Does Java support multiple inheritance?
    Java doesn't support multiple inheritance.
  9. Is Java a pure object oriented language?
    Java is not a pure object oriented language because it uses primitive data types.
  10. What is difference between Path and Classpath?
    Path and Classpath are operating system level environment variables. Path is used define where the system can find the executables (.exe) files and Classpath is used to specify the location .class files.



For More Details: http://www.worldinfosoft.com/interviewquestions/corejavainterview.html

Core JAVA Interview Questions & Answers-2

  1. Can there be an abstract class with no abstract methods in it? - Yes
  2. Can an Interface be final? - No
  3. What are local variables?
    Local variables are those which are declared within a block of code like methods. Local variables should be initialized before accessing them.
  4. Can an Interface have an inner class? - Yes.
     public interface xyz{
    static int i=0;
    void ss();

    class abc{
    abc(){
    int j;
    System.out.println("In side the interface");
    };

    public static void main(String abc[]){
    System.out.println("Interface is in");
    }
    }
    }
  5. Can we define private and protected modifiers for variables in interfaces? - No
  6. What modifiers are allowed for methods in an Interface? - Only public and abstract modifiers are allowed for methods in interfaces.
  7. What is a local, member and a class variable? - Which variable declared within a method that is called “local” variables, which variable declared within the class (not within any methods) are called “member” variables (global variables) and which variables declared within the class (not within any methods and are defined as “static”) are called class variables.
  8. What are the different identifier states of a Thread? - The different identifiers of a Thread are: R - Running or runnable thread, S - Suspended thread, CW - Thread waiting on a condition variable, MW - Thread waiting on a monitor lock, MS - Thread suspended waiting on a monitor lock
  9. What are some alternatives to inheritance? - Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often better than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn’t force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is more difficult to re-use (because it is not a subclass).
  10. What is instance variables?
    Instance variables are those variable which is defined at the class level. Instance variables need not be initialized before using them as they are automatically initialized to their default values.
For More: http://worldinfosoft.com/interviewquestions/corejavainterview.html

Core JAVA Interview Questions & Answers-3

  1. What is constant variable in Java?
    The constant variable should be declared as static and final. So only one copy of the variable exists for all instances of the class and the value can't be changed.
  2. Should a main method be mandatory declared in all java classes?
    No it is not required. main method should be defined only if the source class is a java application.
  3. What is the return type of the main method?
    Main method doesn't return anything therefore it declared void.
  4. Why is the main method declared static?
    main method is called by the JVM yet before the instantiation of the class hence it is declared as static.
  5. What is the argument of main method?
    The main method accepts an array type of String object as an argument.
  6. Can main method be overloaded?
    Yes. You can have any number of main methods with different method signature and implementation in the class.
  7. Can a main method be declared final?
    Yes. Any inheriting class will not be able to have it's own default main method.
  8. Why isn’t there operator overloading? - Because C++ has proven by example that operator overloading makes code almost impossible to maintain. In fact there very nearly wasn’t even method overloading in Java, but it was thought that this was too useful for some very basic methods like print(). Note that some of the classes like DataOutputStream have unoverloaded methods like writeInt() and writeByte().
  9. How do I convert a numeric IP address like 192.168.10.204 into a hostname like javasks.blogspot.com?
     String hostname = InetAddress.getByName("192.168.10.204").getHostName();
  10. Why do threads block on I/O? - Threads block on I/O (that is enters in the waiting state) so that other threads may execute while the I/O operation is performed.
For More: http://worldinfosoft.com/interviewquestions/corejavainterview.html

Core JAVA Interview Questions & Answers-4

  1. What is synchronization and why is it important? - With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often leads to significant errors.
  2. Is null a keyword? - No, The null value is not a keyword.
  3. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters? - Unicode requires 16 bits and ASCII require 7 bits. while the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.
  4. What are wrapped classes? - Wrapped classes are classes that allow primitive types to be accessed as objects.
  5. What is a native method? - A native method is a method that is implemented in a language other than Java.
  6. What is the catch or declare rule for method declarations? - If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.
  7. What is the range of the char type? - The range of the char type is 0 to 2^16 - 1.
For More: http://worldinfosoft.com/interviewquestions/corejavainterview.html

Friday, January 23, 2009

Difference Between jre jvm and jdk


JDK (Java Development Kit)

JDK= JDK tools + JRE

JRE = JVM + Java Packages Classes(like util, math, lang, awt,swing etc)+runtime libraries.

JDK contains tools required to develop the Java programs, and JRE to run the programs. The tools include compiler (javac.exe), Java application launcher (java.exe), Appletviewer, etc…

JAVA Compiler converts java code into byte code. and java application launcher opens a JRE, loads the class, and invokes its main method.

If you want to write and compile your own programs, you need JDK. If you just want to run your java programs, JRE is sufficient. JRE is targeted for execution of Java files

You can create a Java file (with the help of Java packages), compile a Java file and run a java file. JDK is mainly targeted for java development.


JRE (Java Runtime Environment)
Java Runtime Environment contains JVM, class libraries, and other supporting files. It does not contain any development tools such as compiler, debugger, etc. Actually JVM runs the program, and it uses the class libraries, and other supporting files provided in JRE. If you want to run any java program, you need to have JRE installed in the system.


JVM(Java Virtual Machine)
The Java Virtual Machine provides a platform-independent way of executing code, programmers can concentrate on writing application, without having to be concerned with how or where it will run.

JDK Tools and Utilities

Basic Tools:
  • javac
  • java
  • javadoc
  • apt
  • appletviewer
  • jar
  • jdb
  • javah
  • javap
  • extcheck
Security Tools:
  • keytool
  • jarsigner
  • policytool
  • kinit
  • klist
  • ktab

Internationalization Tools:
  • native2ascii
Remote Method Invocation (RMI) Tools:
  • rmic
  • rmiregistry
  • rmid
  • serialver

Java IDL and RMI-IIOP Tools:
  • tnameserv
  • idlj
  • orbd
  • servertool

Java Deployment Tools:
  • pack200
  • unpack200

Java Plug-in Tools:
  • htmlconverter

Java Web Start Tools:
  • javaws



For more details you can visit:
http://www.worldinfosoft.com

This is a one of the best tutorial site, where you can find lots of example with full description of code and you can also prepare of your interview from this site WORLDINFOSOFT.COM.

Saturday, January 17, 2009

Insert & Retrieve Image using Servlet

This article show to you how to insert blob type image into mysql database table by using servlet and how to retrieve the image from table and display it on the browser. In this example servlet is used because it dynamically process the request and generate a response for java programming language. The API of the java servlet allow to software developer to add dynamic content to a web server using java. The main advantage of java servlet is, it can be executed to handle request and response objects and it can run independently.

Now, you follow these steps to insert and retrieve image from database table:

1. Create table in your database follow this query:


CREATE TABLE `picture` (
`id` int(10) NOT NULL auto_increment,
`image` blob,
PRIMARY KEY (`id`)
)

2. create a servlet to insert the image:



import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class InsertImage extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost:3306/test";
Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(connectionURL, "root", "");
PreparedStatement ps = con.prepareStatement("INSERT INTO pictures VALUES(?,?)");
File file = new File("C:/images/5.jpg");
FileInputStream fs = new FileInputStream(file);
ps.setInt(1,1);
ps.setBinaryStream(2,fs,fs.available());
int i = ps.executeUpdate();
if(i!=0){
pw.println("image inserted successfully");
}else{
pw.println("problem in image insertion");
}
} catch (Exception e){
System.out.println(e);
}
}
}


3. create web.xml file in WEB-INF folder of your tomcat server and put this code:


<servlet>
<servlet-name>InsertImage</servlet-name>
<servlet-class>InsertImage</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>InsertImage</servlet-name>
<url-pattern>/InsertImage</url-pattern>
</servlet-mapping>



4. create one more servlet for retrieve image from database table






import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RetreiveImage extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost:3306/test";
java.sql.Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=DriverManager.getConnection(connectionURL,"root","");
Statement st1=con.createStatement();
ResultSet rs1 = st1.executeQuery("select image from pictures where id='1'");
String imgLen="";
if(rs1.next()){
imgLen = rs1.getString(1);
System.out.println(imgLen.length());
}
rs1 = st1.executeQuery("select image from pictures where id='1'");
if(rs1.next()){
int len = imgLen.length();
byte [] rb = new byte[len];
InputStream readImg = rs1.getBinaryStream(1);
int index=readImg.read(rb, 0, len);
System.out.println("index"+index);
st1.close();
response.reset();
response.setContentType("image/jpg");
response.getOutputStream().write(rb,0,len);
response.getOutputStream().flush();
}
} catch (Exception e){
e.printStackTrace();
}
}
}


5. put this code in to your web.xml file:



<servlet>
<servlet-name>RetreiveImage</servlet-name>
<servlet-class>RetreiveImage</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RetreiveImage</servlet-name>
<url-pattern>/RetreiveImage</url-pattern>
</servlet-mapping>



6. Compile both servlet file into classes folder by command prompt as:

E:\apache-tomcat-6.0.14\webapps\sandeep\WEB-INF\classes> javac InsertImage.java

and

E:\apache-tomcat-6.0.14\webapps\sandeep\WEB-INF\classes> javac RetreiveImage.java


7. Run your server by startup.bat file


8. Open your browser and type on url address:

http:\\localhost:8080\sandeep\InsertImage

then you will got a success message

9. and then run the RetreiveImage servlet to display your image on browser by

http:\\localhost:8080\sandeep\RetreiveImage

10. Finally you will see the image on your browser


For more details you can visit: http://www.worldinfosoft.com

This is a one of the best tutorial site, where you can find lots of example with full description of code and you van also prepare of your interview from this site WORLDINFOSOFT.COM.

Monday, January 5, 2009

JDBC Insert Query Example




import java.io.*;
import java.sql.* ;

class JDBCInsert{
public static void main( String args[] ){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbName","root", "root") ;
Statement stmt = conn.createStatement() ;
int rows = stmt.executeUpdate("INSERT INTO tableName VALUES (4, 'sandeep')");
System.out.println(rows + " Rows modified") ;
stmt.close() ;
conn.close() ;
} catch(SQLException se) {
System.out.println("SQL Exception:"+se) ;
} catch(Exception e){
System.out.println(e) ;
}
}
}

JDBC Update Query Example



import java.io.*;
import java.sql.* ;

class JDBCUpdate{
public static void main( String args[] ){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbName","root", "root") ;
Statement stmt = conn.createStatement() ;
int rows = stmt.executeUpdate("UPDATE tableName SET columnName='' WHERE columnName=''") ;
System.out.println(rows + " Rows modified") ;
stmt.close() ;
conn.close() ;
} catch(SQLException se) {
System.out.println("SQL Exception:"+se) ;
} catch(Exception e){
System.out.println(e) ;
}
}
}

Sunday, January 4, 2009

JDBC Prepared Statement Example


import java.io.*;
import java.sql.*;
public class JDBCPreparedStatement {
public static void main ( String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "root");
PreparedStatement stmt = c.prepareStatement("select * from tableName");
ResultSet rs = stmt.executeQuery();
while(rs.next()){
System.out.println(rs.getInt(1) + " (" + rs.getString(2) + ")");
}
} catch(SQLException e){
System.err.println(e);
}
}
}

MySQL Create Database

  • In this example we are creating a databse table for establishing the connection with MySQL database by using the JDBC driver. A database is a large collection of data or information stored in our computer in a specified manner. It helps us for accessing, managing and updating the data easily. A RDBMS (Relational Database Management System) is a type of DBMS (Database Management System) which stores the data in the form of tables. So, we can view and use the same database in many different ways.

The following example Shows to you how to create a database in MYSQL:


import java.io.*;
import java.sql.*;

public class CreateDatabase{
public static void main(String[] args) {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbname = "test";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";
Connection con = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection (url+dbname,user,pass);
try{
Statement st = con.createStatement();
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Database name:");
String database = bf.readLine();
st.executeUpdate("CREATE DATABASE "+database);
System.out.println("Dtabase Created Successfully");
} catch (SQLException s){ System.out.println("SQL Exception!");
}
} catch (Exception e){ e.printStackTrace();
}
}
}

Data Retrieval Process of JDBC

There are the following steps are used by jdbc to retrieve the data
  1. A JDBC driver would be loaded
  2. Using the DriverManager a database Connection object would be created
  3. Using the Connection object a Statement object would be created
  4. Using the Statement object a SQL Select statement would be executed
  5. SQL select statement returned a ResultSet
  6. The ResultSet would be used to returned the rows and examine the data.
This example illustrates how to create a connection from database table and how to access row of the table:

import java.io.*;
import java.sql.*;

public class JDBCMysqlConnection {
public static void main( String args[]) {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbname = "test";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";

try {
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url+dbname,user,pass);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from tableName");
while (rs.next()){
System.out.println("Name= " + rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
con.close();
}
}
}