50 Core Java interview questions and answers

Java interview questions and answers

50 Core Java interview questions and answers

  1. How memory is managed in java?

A: Memory model is common to handle in all languages.It basically defines the possible scenarios and rules that govern multiple threads in a system.In java a memory management model determines if an execution trace of a program is legally allowed by the JVM. Here the execution trace is nothing but the execution path of a thread. The Java specification for JVM model does not force its implementations to follow any particular implementation rules during program execution.It gives the JVM implementer flexibility to provide compiler optimizations, execution path and reorganizations in the execution sequence. But the most important thing is that the memory model which specifies all implementations produce results that can be predicted by a programmer.So even the flexibility is there, but still the execution path can be well predicted by the programmer.The Memory model defines the possible rules for threads, its synchronization and the expected behavior of multi-threaded programs.The responsibility of avoiding data races, dirty reading, deadlock etc in threads are still the responsibility of the programmer.

In Java manual memory allocation and de-allocation has been eliminated and it is the biggest advantage to the programmer community. Memory in Java is automatically garbage collected so you never have to worry about memory corruption or memory leak. Java memory is managed by the memory model implemented by the JVM. The Java Memory model explains synchronization techniques to make sure data corruption does not take place. The following diagram gives an overview on java memory management.

Although, Java Virtual Machine performs automatic garbage collection but you can not forget memory management issues. When the garbage collection will happen is implementation dependent and you do not have any control on it.Some JVMs will wait until all available memory is used up before starting garbage collection and some other run it in a incremental way. As an alternative, Runtime.gc () is included in the core APIs. Invoking this method will ask the JVM to run the garbage collector but still it is not confirmed that JVM will start it immediately.It is only a request to the JVM that you would like the garbage collector to run.But the observation is that most of the JVMs will run the garbage collector shortly after this call.

  1. Are multiple inheritances possible in java?

A: No, multiple inheritance is not possible in java. Interface has been introduced to serve the purpose and it has been derived from Objective C.

The reasons for omitting multiple inheritances from the Java language mostly stem from the “simple, object oriented and familiar” goal. As a simple language, Java’s creators wanted a language that most developers could grasp without extensive training. To that end, they worked to make the language as similar to C++ as possible (familiar) without carrying over C++’s unnecessary complexity (simple).

In the designers’ opinion, multiple inheritance causes more problems and confusion than it solves. So they cut multiple inheritances from the language (just as they cut operator overloading). The designers’ extensive C++ experience taught them that multiple inheritances just weren’t worth the headache.

Instead, Java’s designers chose to allow multiple interface inheritance through the use of interfaces, an idea borrowed from Objective C’s protocols. Multiple interface inheritance allows an object to inherit many different method signatures with the caveat that the inheriting object must implement those inherited methods.






  1. What are the eleven design goals of java?

A:  Following are the eleven design goals of java programming language. Java designers have accomplished the task by keeping these goals in mind.

    • Simple
    • Portable
    • Object Oriented
    • Interpreted
    • Distributed
    • High Performance
    • Robust
    • Multithreaded
    • Secure
    • Dynamic
    • Architecture Neutral

 Why java is called distributed?

A:  Java has an extensive library of routines for handling TCP/IP protocols like HTTP and FTP. So Java applications can open and access objects across the internet via URLs. The network programming using java is strong and easy to use. So java is called distributed.

The distributed nature of Java really shines when combined with its dynamic class loading capabilities. Together, these features make it possible for a Java interpreter to download and run code from across the Internet. This is what happens when a Web browser downloads and runs a Java applet, for example. Scenarios can be more complicated than this, however. Imagine a multi-media word processor written in Java. When this program is asked to display some type of data that it has never encountered before, it might dynamically download a class from the network that can parse the data, and then dynamically download another class (probably a Java “bean”) that can display the data within a compound document. A program like this uses distributed resources on the network to dynamically grow and adapt to the needs of its user.

  1. Why java is called architecture neutral?

A: The Java compiler generates a bytecode instruction which is independent of computer architecture. The bytecode is designed to be both easy to interpret on any machine and easily translated into native machine code on the fly. The following diagram shows the details how it works.

  1. Why java enabled browser is needed to run an applet?

A:  Applet is a java program that works on a web page. So the browser should have the capability to interpret the bytecode and make it work. That is why java enabled browser is required to run an applet embedded in a web page. Actually the browser contains the JVM inbuilt which helps to interpret the byte code and show the output.

  1. What do you mean by ‘Java is a strongly typed language’?

A:  Java is strongly typed means that every variable in java must have a declared type. There are eight primitive types in Java. Four of them are integer types and two are floating-point number types. One is the character type char, used for characters in the Unicode encoding and one is a Boolean type for truth values.

  1. How I/O is managed in java?

A: In java I/O represents Input and Output streams. Streams are used to read from or write to devices such as file or network or console. Java.io package provides I/O classes to manipulate streams. This package supports two types of streams – binary streams which handle binary data and character streams which handle character data. InputStream and OutputStream are high level interfaces for manipulating binary streams. Reader and Writer are high level interfaces for manipulating character streams.

The following figure shows the relationship of different IO classes addressed in this section

  1. How does buffered stream improve performance in java?

A: The default behavior of a stream is to read or write one byte at a time. This causes poor I/O performance because it takes lot of time to read/write byte by byte when dealing with large amounts of data. Java I/O provides Buffered streams to override these byte by byte default behaviors. You need to use Buffered streams (BufferedInputStream and BufferedOutputStream) to buffer the data and then read/write which gives good performance. You need to understand the method’s default behavior and act upon that.

The following figure shows how buffered streams divert the data flow.

  1. How do you measure performance of default behavior and buffering for file reading?

A:  The following code snippet will take similar files to read and write using default reading and buffered reading. And then it will display the time taken by both of them. For testing the code keep the files in local file system as shown below.

 

package com.performance.io;

 

import java.io.*;

public class IOTest {

public static void main(String[] args){

IOTest io = new IOTest();

try{

long startTime = System.currentTimeMillis();

io.readWrite(“c:/temp/test-origin.html”,”c:/temp/test-destination.html”);

long endTime = System.currentTimeMillis();

System.out.println(“Time taken for reading and writing using default behaviour : ”

+ (endTime – startTime) + ” milli seconds” );

 

long startTime1 = System.currentTimeMillis();

io.readWriteBuffer(“c:/temp/test-origin.html”,”c:/temp/test-destination.html”);

long endTime1 = System.currentTimeMillis();

System.out.println(“Time taken for reading and writing using buffered streams : ”

+ (endTime1 – startTime1) + ” milli seconds” );

}catch(IOException e){ e.printStackTrace();}

}

public static void readWrite(String fileFrom, String fileTo) throws IOException{

InputStream in = null;

OutputStream out = null;

try{

in = new FileInputStream(fileFrom);

out = new FileOutputStream(fileTo);

while(true){

int bytedata = in.read();

if(bytedata == -1)

break;

out.write(bytedata);

}

}

catch(Exception e)

{

e.printStackTrace();

}

finally{

if(in != null)

in.close();

if(out !=null)

out.close();

}

}

public static void readWriteBuffer(String fileFrom, String fileTo) throws IOException{

InputStream inBuffer = null;

OutputStream outBuffer = null;

try{

InputStream in = new FileInputStream(fileFrom);

inBuffer = new BufferedInputStream(in);

OutputStream out = new FileOutputStream(fileTo);

outBuffer = new BufferedOutputStream(out);

while(true){

int bytedata = inBuffer.read();

if(bytedata == -1)

break;

out.write(bytedata);

}

}

catch(Exception e)

{

e.printStackTrace();

}

finally{

if(inBuffer != null)

inBuffer.close();

if(outBuffer !=null)

outBuffer.close();

}

}

)

  1. What is collections framework in java?

A: 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, like Lists and Sets. But Map types hold group of objects as key, value pairs like HashMap and Hashtable. Following diagram shows the entire hierarchy of collections framework.

  1. How to extend an array after initialization? 

A: Following example shows how to extend an array after initialization by creating a new array. Here the code is basically appending the new values to an existing array. The arraycopy() method should be used carefully otherwise there may a problem of data loss in the existing array.

public class Main {

public static void main(String[] args) {

String[] names = new String[] { “X”, “Y”, “Z” };

String[] extended = new String[5];

extended[3] = “D”;

extended[4] = “E”;

System.arraycopy(names, 0, extended, 0, names.length);

for (String str : extended){

System.out.println(str);

}

}

}

And the result will be as follows

X
Y
Z
D
E

  1. How to fill (initialize at once) an array?

A: This example will fill (initialize all the elements of the array in one short) an array by using Array.fill (arrayname, value) method and Array.fill (arrayname, starting index, ending index, value) method of Java Util class.

import java.util.*;

public class FillTest {

public static void main(String args[]) {

int array[] = new int[6];

Arrays.fill(array, 100);

for (int i=0, n=array.length; i < n; i++) {

System.out.println(array[i]);

}

System.out.println();

Arrays.fill(array, 3, 6, 50);

for (int i=0, n=array.length; i< n; i++) {

System.out.println(array[i]);

}

}

}

If you run the code then the result will be as follows.

100
100
100
100
100
100
100
100
100
50
50
50








  1. How to multiply two matrices of different dimensions?

A: Following example shows multiplication of two rectangular matrices with the help of two user defined methods multiply ( int [] [] ,int [] []) and mprint(int [] []).

public class Matrix{

public static int[][] multiply(int[][] m1, int[][] m2){

int m1rows = m1.length;

int m1cols = m1[0].length;

int m2rows = m2.length;

int m2cols = m2[0].length;

if (m1cols != m2rows){

throw new IllegalArgumentException(“matrices

don’t match: “+ m1cols + ” != ” + m2rows);

int[][] result = new int[m1rows][m2cols];

for (int i=0; i< m1rows; i++){

for (int j=0; j< m2cols; j++){

for (int k=0; k< m1cols; k++){

result[i][j] += m1[i][k] * m2[k][j];

return result;

)

}

}

}

}

/** Matrix print.

*/

public static void mprint(int[][] a){

int rows = a.length;

int cols = a[0].length;

System.out.println(“array[“+rows+”][“+cols+”] = {“);

for (int i=0; i< rows; i++){

System.out.print(“{“);

for (int j=0; j< cols; j++){

System.out.print(” ” + a[i][j] + “,”);

System.out.println(“},”);

}

}

System.out.println(“:;”);

}

public static void main(String[] argv){

int x[][] ={

{ 3, 2, 3 },

{ 5, 9, 8 },

};

int y[][] ={

{ 4, 7 },

{ 9, 3 },

{ 8, 1 },

};

int z[][] = Matrix.multiply(x, y);

Matrix.mprint(x);

Matrix.mprint(y);

Matrix.mprint(z);

}

}

The code sample will produce the following result

array[2][3]={

{3, 2, 3}

{5, 9, 8}

};

array[3][2]={

{4, 7}

{9, 3}

{8, 1}

};

array[2][2]={

{63, 30}

{165, 70}

};

  1. How to merge two arrays?

A: This example shows how to merge two arrays into a single array by the use of list.Addall(array1.asList(array2) method of List class and Arrays.toString () method of Array class. Be careful when assigning one array to another. Because if the references of the elements of both the arrays then there is chance of cascading effect.

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

public class Main {

public static void main(String args[]) {

String a[] = { “A”, “E”, “I” };

String b[] = { “O”, “U” };

List list = new ArrayList(Arrays.asList(a));

list.addAll(Arrays.asList(b));

Object[] c = list.toArray();

System.out.println(Arrays.toString(c));

}

}

The code sample will produce the following result

[A, E, I, O, U]

  1. How to search the minimum and the maximum element in an array?

A: This example shows how to search the minimum and maximum element in an array by using Collection.max () and Collection.min() methods of Collection class. Although there are some other ways also to find the max and min values from an array but this API is the most efficient one to work with arrays.

import java.util.Arrays;

import java.util.Collections;

public class Main {

public static void main(String[] args) {

Integer[] numbers = { 8, 2, 7, 1, 4, 9, 5};

int min = (int) Collections.min(Arrays.asList(numbers));

int max = (int) Collections.max(Arrays.asList(numbers));

System.out.println(“Min number: ” + min);

System.out.println(“Max number: ” + max);

}

}

The result will be as follows

Min number: 1

Max number: 9

  1. How to reverse an arraylist?

A:  Collections API has a method called reverse (ArrayList). So this is used to reverse an array list. The following example will show you how to use the API to make the code work.

import java.util.ArrayList;

import java.util.Collections;

public class Main {

public static void main(String[] args) {

ArrayList arrayList = new ArrayList();

arrayList.add(“A”);

arrayList.add(“B”);

arrayList.add(“C”);

arrayList.add(“D”);

arrayList.add(“E”);

System.out.println(“Before Reverse Order: ” + arrayList);

Collections.reverse(arrayList);

System.out.println(“After Reverse Order: ” + arrayList);

}

}

The result of the above example would be as follows.

Before Reverse Order: [A, B, C, D, E]

After Reverse Order: [E, D, C, B, A]

  1. How to sort an array and insert an element inside it?

A: The following example shows how to use sort () method and user defined method insertElement () to accomplish the task. The sort () method is used to sort the array from negative to positive value then the customized insertElement () method is used to add additional elements into it.

import java.util.Arrays;

public class MainClass {

public static void main(String args[]) throws Exception {

int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };

Arrays.sort(array);

printArray(“Sorted array”, array);

int index = Arrays.binarySearch(array, 1);

System.out.println(“Didn’t find 1 @ ”

+ index);

int newIndex = -index – 1;

array = insertElement(array, 1, newIndex);

printArray(“With 1 added”, array);

}

private static void printArray(String message, int array[]) {

System.out.println(message

+ “: [length: ” + array.length + “]”);

for (int i = 0; i < array.length; i++) {

if (i != 0){

System.out.print(“, “);

}

System.out.print(array[i]);

}

System.out.println();

}

private static int[] insertElement(int original[],

int element, int index) {

int length = original.length;

int destination[] = new int[length + 1];

System.arraycopy(original, 0, destination, 0, index);

destination[index] = element;

System.arraycopy(original, index, destination, index

+ 1, length – index);

return destination;

}

}

  1. How to sort an array and search an element inside it?

A: The following example shows how to use sort () and binarySearch () method to accomplish the task. The user defined method printArray () is used to display the output.

mport java.util.Arrays;

public class MainClass {

public static void main(String args[]) throws Exception {

int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };

Arrays.sort(array);

printArray(“Sorted array”, array);

int index = Arrays.binarySearch(array, 2);

System.out.println(“Found 2 @ ” + index);

}

private static void printArray(String message, int array[]) {

System.out.println(message

+ “: [length: ” + array.length + “]”);

for (int i = 0; i < array.length; i++) {

if(i != 0){

System.out.print(“, “);

}

System.out.print(array[i]);

}

System.out.println();

}

}

If you run the code then the application will show the result as given below.

Sorted array: [length: 10]

-9, -7, -3, -2, 0, 2, 4, 5, 6, 8

Found 2 @ 5








  1. How to create a banner using Applet?

A:  The following example has used the Thread class and Graphics class to display the banner. The functionality of the thread is to give an effect of animation to the banner. To view the output the applet should be run In a browser which supports applet.

iimport java.awt.*;

import java.applet.*;

public class SampleBanner extends Applet

implements Runnable{

String str = “This is a simple Banner “;

Thread t ;

boolean b;

public void init() {

setBackground(Color.gray);

setForeground(Color.yellow);

}

public void start() {

t = new Thread(this);

b = false;

t.start();

}

public void run () {

char ch;

for( ; ; ) {

try {

repaint();

Thread.sleep(250);

ch = str.charAt(0);

str = str.substring(1, str.length());

str = str + ch;

}

catch(InterruptedException e) {}

}

}

public void paint(Graphics g) {

g.drawRect(1,1,300,150);

g.setColor(Color.yellow);

g.fillRect(1,1,300,150);

g.setColor(Color.red);

g.drawString(str, 1, 150);

}

}

  1. How to display a clock using an applet?

A:  The example has used String class and Calendar class to display the applet clock. Calendar class gives the value of ‘Hours’, ‘Minutes’ and ‘second’.

import java.awt.*;

import java.applet.*;

import java.applet.*;

import java.awt.*;

import java.util.*;

public class ClockApplet extends Applet implements Runnable{

Thread t,t1;

public void start(){

t = new Thread(this);

t.start();

}

public void run(){

t1 = Thread.currentThread();

while(t1 == t){

repaint();

try{

t1.sleep(1000);

}

catch(InterruptedException e){}

}

}

public void paint(Graphics g){

Calendar cal = new GregorianCalendar();

String hour = String.valueOf(cal.get(Calendar.HOUR));

String minute = String.valueOf(cal.get(Calendar.MINUTE));

String second = String.valueOf(cal.get(Calendar.SECOND));

g.drawString(hour + “:” + minute + “:” + second, 20, 30);

}

}

Again you have to run the applet in a browser or applet viewer to check the output.

  1. How to create an event listener in Applet?

A: Following example demonstrates how to create a basic Applet having buttons to add & subtract two numbers. Methods used here are addActionListener () to listen to an event(click on a button) & Button() constructor to create a button.

import java.applet.*;
import java.awt.event.*;
import java.awt.*;

public class EventListeners extends Applet

implements ActionListener{

TextArea txtArea;

String Add, Subtract;

int i = 10, j = 20, sum =0,Sub=0;

public void init(){

txtArea = new TextArea(10,20);

txtArea.setEditable(false);

add(txtArea,”center”);

Button b = new Button(“Add”);

Button c = new Button(“Subtract”);

b.addActionListener(this);

c.addActionListener(this);

add(b);

add(c);

}

public void actionPerformed(ActionEvent e){

sum = i + j;

txtArea.setText(“”);

txtArea.append(“i = “+ i + “\t” + “j = ” + j + “\n”);

Button source = (Button)e.getSource();

if(source.getLabel() == “Add”){

txtArea.append(“Sum : ” + sum + “\n”);

}

if(i >j){

Sub = i – j;

}

else{

Sub = j – i;

}

if(source.getLabel() == “Subtract”){

txtArea.append(“Sub : ” + Sub + “\n”);

}

}

}

  1. How to open a link in a new window using Applet?

A: This example demonstrates how to open a particular webpage from an applet in a new window using showDocument() method with second argument as “_blank” .

import java.applet.*;

import java.awt.*;

import java.net.*;

import java.awt.event.*;

public class testURL_NewWindow extends Applet

implements ActionListener{

public void init(){

String link_Text = “google”;

Button b = new Button(link_Text);

b.addActionListener(this);

add(b);

}

public void actionPerformed(ActionEvent ae){

Button source = (Button)ae.getSource();

String link = “http://www.”+source.getLabel()+”.com”;

try {

AppletContext a = getAppletContext();

URL url = new URL(link);

a.showDocument(url,”_blank”);

}

catch (MalformedURLException e){

System.out.println(e.getMessage());

}

}

}

  1. How to read a file using Applet?

A: The following code snippet demonstrates how to read a file using an Applet using openStream() method of URL. There are different ways to read a stream like buffered stream, customized buffered stream etc. Here we have used buffered stream to read the data.

import java.applet.*;

import java.awt.*;

import java.io.*;

import java.net.*;

 

public class readFileApplet extends Applet{

String fileToRead = “test1.txt”;

StringBuffer strBuff;

TextArea txtArea;

Graphics g;

public void init(){

txtArea = new TextArea(100, 100);

txtArea.setEditable(false);

add(txtArea, “center”);

String prHtml = this.getParameter(“fileToRead”);

if (prHtml != null) fileToRead = new String(prHtml);

readFile();

}

public void readFile(){

String line;

URL url = null;

try{

url = new URL(getCodeBase(), fileToRead);

}

catch(MalformedURLException e){}

try{

InputStream in = url.openStream();

BufferedReader bf = new BufferedReader

(new InputStreamReader(in));

strBuff = new StringBuffer();

while((line = bf.readLine()) != null){

strBuff.append(line + “\n”);

}

txtArea.append(“File Name : ” + fileToRead + “\n”);

txtArea.append(strBuff.toString());

}

catch(IOException e){

e.printStackTrace();

}

}

}








  1. How to create different shapes using Applet?

A: This example demonstrates how to create an applet which will have a line, an Oval & a Rectangle using drawLine(), drawOval() and drawRect() methods of Graphics class. In java Graphics class is widely used to draw diagrams and those are used in pie chart, bar diagram etc.

import java.applet.*;

import java.awt.*;

 

public class  Shapes extends Applet{

int x=300,y=100,r=50;

public void paint(Graphics g){

g.drawLine(30,300,200,10);

g.drawOval(x-r,y-r,100,100);

g.drawRect(400,50,200,100);

}

}

The above code sample will produce the following result in a java enabled web browse

A line, Oval & a Rectangle will be drawn in the browser.

  1. How to use swing applet in JAVA?

A: Swing is an important component in java to produce UI interfaces. These swing components are also used in applet to make the user interface.Following example demonstrates how to go use Swing Applet in JAVA by implementing ActionListener & by creating JLabels.

import javax.swing.*;

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

public class SApplet extends Applet implements ActionListener {

TextField input,output;

Label label1,label2;

Button b1;

JLabel lbl;

int num, sum = 0;

public void init(){

label1 = new Label(“please enter number : “);

add(label1);

label1.setBackground(Color.yellow);

label1.setForeground(Color.magenta);

input = new TextField(5);

add(input);

label2 = new Label(“Sum : “);

add(label2);

label2.setBackground(Color.yellow);

label2.setForeground(Color.magenta);

output = new TextField(20);

add(output);

b1 = new Button(“Add”);

add(b1);

b1.addActionListener(this);

lbl = new JLabel(“Swing Applet Example. “);

add(lbl);

setBackground(Color.yellow);

}

public void actionPerformed(ActionEvent ae){

try{

num = Integer.parseInt(input.getText());

sum = sum+num;

input.setText(“”);

output.setText(Integer.toString(sum));

lbl.setForeground(Color.blue);

lbl.setText(“Output of the second Text Box : ”

+ output.getText());

}

catch(NumberFormatException e){

lbl.setForeground(Color.red);

lbl.setText(“Invalid Entry!”);

}

}

}

  1. How to write to a file using Applet?

A:  In the following example java text area has been used to enter the user input. After entering the input it has been written in a file in local file system. The File () constructor has been used to create the file.

import java.io.*;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import java.applet.Applet;

import java.net.*;

public class WriteFile extends Applet{

Button write = new Button(“WriteToFile”);

Label label1 = new Label(“Enter the file name:”);

TextField text = new TextField(20);

Label label2 = new Label(“Write your text:”);

TextArea area = new TextArea(10,20);

public void init(){

add(label1);

label1.setBackground(Color.lightGray);

add(text);

add(label2);

label2.setBackground(Color.lightGray);

add(area);

add(write,BorderLayout.CENTER);

write.addActionListener(new ActionListener (){

public void actionPerformed(ActionEvent e){

new WriteText();

}

}

);

}

public class WriteText {

WriteText(){

try {

String str = text.getText();

if(str.equals(“”)){

JOptionPane.showMessageDialog(null,

“Please enter the file name!”);

text.requestFocus();

}

else{

File f = new File(str);

if(f.exists()){

BufferedWriter out = new

BufferedWriter(new FileWriter(f,true));

if(area.getText().equals(“”)){

JOptionPane.showMessageDialog

(null,”Please enter your text!”);

area.requestFocus();

}

else{

out.write(area.getText());

if(f.canWrite()){

JOptionPane.showMessageDialog(null,

“Text is written in “+str);

text.setText(“”);

area.setText(“”);

text.requestFocus();

}

else{

JOptionPane.showMessageDialog(null,

“Text isn’t written in “+str);

}

out.close();

}

}

else{

JOptionPane.showMessageDialog

(null,”File not found!”);

text.setText(“”);

text.requestFocus();

}

}

}

catch(Exception x){

x.printStackTrace();

}

}

}

}

  1. How to print summation of n numbers?

A: Following example demonstrates how to add first n natural numbers by using the concept of stack. Here the static Stack class is used to hold the numbers. The custom stackAddition () method is used to add the numbers into the stack.

import java.io.IOException;

public class AdditionStack {

static int num;

static int ans;

static Stack theStack;

public static void main(String[] args) throws IOException {

num = 50;

stackAddition();

System.out.println(“Sum=” + ans);

}

public static void stackAddition() {

theStack = new Stack(10000);

ans = 0;

while (num > 0)

{

theStack.push(num);

–num;

}

while (!theStack.isEmpty())

{

int newN = theStack.pop();

ans += newN;

}

}

}

class Stack {

private int maxSize;

private int[] data;

private int top;

public Stack(int s) {

maxSize = s;

data = new int[maxSize];

top = -1;

}

public void push(int p) {

data[++top] = p;

}

public int pop() {

return data[top–];

}

public int peek() {

return data[top];

}

public boolean isEmpty() {

return (top == -1);

}

}

The above code sample will produce the following result.

Sum=1225

  1. How to get the first and the last element of a linked list?

A: Following example shows how to get the first and last element of a linked list with the help of linkedlistname.getFirst() and linkedlistname.getLast() of LinkedList class. All of the stack/queue/deque operations could be easily recast in terms of the standard list operations. They’re included here primarily for convenience, though they may run slightly faster than the equivalent List operations.

import java.util.LinkedList;

public class Main {

public static void main(String[] args) {

LinkedList lList = new LinkedList();

lList.add(“100”);

lList.add(“200”);

lList.add(“300”);

lList.add(“400”);

lList.add(“500”);

System.out.println(“First element of LinkedList is :

” + lList.getFirst());

System.out.println(“Last element of LinkedList is :

” + lList.getLast());

}

}

The above code sample will produce the following result.

First element of LinkedList is: 100

Last element of LinkedList is: 500

  1. How to add an element at first and last position of a linked list?

A: Following example shows how to add an element at the first and last position of a linked list by using addFirst() and addLast() method of Linked List class.

import java.util.LinkedList;

public class Main {

public static void main(String[] args) {

LinkedList lList = new LinkedList();

lList.add(“1”);

lList.add(“2”);

lList.add(“3”);

lList.add(“4”);

lList.add(“5”);

System.out.println(lList);

lList.addFirst(“0”);

System.out.println(lList);

lList.addLast(“6”);

System.out.println(lList);

}

}

The above code sample will produce the following result.

1, 2, 3, 4, 5

0, 1, 2, 3, 4, 5

0, 1, 2, 3, 4, 5, 6

  1. How to convert an infix expression to postfix expression?

A: Following example demonstrates how to convert an infix to postfix expression by using the concept of stack. Here push (), pop () and peek () methods are used to perform the task. And the Stack class is used to hold the expressions.

import java.io.IOException;

public class InToPost {

private Stack theStack;

 

private String input;

 

private String output = “”;

 

public InToPost(String in) {

input = in;

int stackSize = input.length();

theStack = new Stack(stackSize);

}

 

public String doTrans() {

for (int j = 0; j < input.length(); j++) {

char ch = input.charAt(j);

switch (ch) {

case ‘+’:

case ‘-‘:

gotOper(ch, 1);

break;

case ‘*’:

case ‘/’:

gotOper(ch, 2);

break;

case ‘(‘:

theStack.push(ch);

break;

case ‘)’:

gotParen(ch);

break;

default:

output = output + ch;

break;

}

}

while (!theStack.isEmpty()) {

output = output + theStack.pop();

}

System.out.println(output);

return output;

}

 

public void gotOper(char opThis, int prec1) {

 

while (!theStack.isEmpty()) {

char opTop = theStack.pop();

if (opTop == ‘(‘) {

theStack.push(opTop);

break;

}

else {

int prec2;

if (opTop == ‘+’ || opTop == ‘-‘)

prec2 = 1;

else

prec2 = 2;

if (prec2 < prec1)

{

theStack.push(opTop);

break;

} else

output = output + opTop;

}

}

theStack.push(opThis);

}

 

public void gotParen(char ch){

while (!theStack.isEmpty()) {

char chx = theStack.pop();

if (chx == ‘(‘)

break;

else

output = output + chx;

}

}

 

public static void main(String[] args) throws IOException {

 

String input = “1+2*4/5-7+3/6”;

String output;

InToPost theTrans = new InToPost(input);

output = theTrans.doTrans();

System.out.println(“Postfix is ” + output + ‘\n’);

}

class Stack {

 

private int maxSize;

private char[] stackArray;

private int top;

 

public Stack(int max) {

maxSize = max;

stackArray = new char[maxSize];

top = -1;

}

 

public void push(char j) {

stackArray[++top] = j;

}

 

public char pop() {

return stackArray[top–];

}

 

public char peek() {

return stackArray[top];

}

 

public boolean isEmpty() {

return (top == -1);

}

}

 

}

 

The above code sample will produce the following result.

124*5/+7-36/+

Postfix is 124*5/+7-36/+








  1. How to implement Queue?

A: Following example shows how to implement a queue in an employee structure. Linked list is an implementation of the List interface. Implements all optional list operations, and permits all elements (including null). In addition to implementing the List interface.The LinkedList class provides uniformly named methods to get, remove and insert an element at the beginning and end of the list. These operations allow linked lists to be used as a stack, queue, or double-ended queue.

import java.util.LinkedList;

class GenQueue {

private LinkedList list = new LinkedList();

public void enqueue(E item) {

list.addLast(item);

}

public E dequeue() {

return list.poll();

}

public boolean hasItems() {

return !list.isEmpty();

}

public int size() {

return list.size();

}

public void addItems(GenQueue q) {

while (q.hasItems())

list.addLast(q.dequeue());

}

}

public class GenQueueTest {

public static void main(String[] args) {

GenQueue empList;

empList = new GenQueue();

GenQueue hList;

hList = new GenQueue();

hList.enqueue(new HourlyEmployee(“T”, “D”));

hList.enqueue(new HourlyEmployee(“G”, “B”));

hList.enqueue(new HourlyEmployee(“F”, “S”));

empList.addItems(hList);

System.out.println(“The employees’ names are:”);

 

while (empList.hasItems()) {

Employee emp = empList.dequeue();

System.out.println(emp.firstName + ” ” + emp.lastName);

}

}

}

class Employee {

`       public String lastName;

public String firstName;

public Employee() {

}

public Employee(String last, String first) {

this.lastName = last;

 

this.firstName = first;

}

public String toString() {

return firstName + ” ” + lastName;

}

}

class HourlyEmployee extends Employee {

public double hourlyRate;

 

public HourlyEmployee(String last, String first) {

super(last, first);

}

}

The above code sample will produce the following result.

The employees’ names are:

T D

G B

F S

  1. How to reverse a string using stack?

A: Following example shows how to reverse a string using stack with the help of user defined method StringReverserThroughStack ().A simple Stack in Java, implemented as an object-oriented, recursive data structure, a singly linked list. Note that Java already provides a Stack class

import java.io.IOException;

public class StringReverserThroughStack {

private String input;

private String output;

public StringReverserThroughStack(String in) {

input = in;

}

public String doRev() {

int stackSize = input.length();

Stack theStack = new Stack(stackSize);

 

for (int i = 0; i < input.length(); i++) {

char ch = input.charAt(i);

theStack.push(ch);

}

output = “”;

while (!theStack.isEmpty()) {

char ch = theStack.pop();

output = output + ch;

}

return output;

}

public static void main(String[] args) throws IOException {

String input = “Java Source and Support”;

String output;

StringReverserThroughStack theReverser =

new StringReverserThroughStack(input);

output = theReverser.doRev();

System.out.println(“Reversed: ” + output);

}

class Stack {

private int maxSize;

private char[] stackArray;

private int top;

 

public Stack(int max) {

maxSize = max;

stackArray = new char[maxSize];

top = -1;

}

public void push(char j) {

stackArray[++top] = j;

}

public char pop() {

return stackArray[top–];

}

public char peek() {

return stackArray[top];

}

public boolean isEmpty() {

return (top == -1);

}

 

}

}

The above code sample will produce the following result.

JavaStringReversal

Reversed:lasreveRgnirtSavaJ

  1. How to check whether antialiasing is enabled or not?

A: Following example demonstrates how to check if antialiasing is turned on or not using RenderingHints Class. Aliasing occurs when a signal (in this case, a 2D graphics signal) is sampled and quantized from a continuous space into a discretized space. Sampling is the process of reading a value from a continuously varying signal. Quantization is the process by which these continuous sampled values are assigned a discrete value in the finite space represented by digital (binary-based) systems.

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.RenderingHints;

import javax.swing.JComponent;

import javax.swing.JFrame;

 

public class Main {

public static void main(String[] args) {

JFrame frame = new JFrame();

frame.add(new MyComponent());

frame.setSize(300, 300);

frame.setVisible(true);

}

}

class MyComponent extends JComponent {

public void paint(Graphics g) {

Graphics2D g2 = (Graphics2D) g;

RenderingHints rh = g2d.getRenderingHints();

boolean bl = rh.containsValue

(RenderingHints.VALUE_ANTIALIAS_ON);

System.out.println(bl);

g2.setRenderingHint(RenderingHints.

KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

}

}

The above code sample will produce the following result.

False

False

False

  1. How to display colors in a frame?

A: Following example displays how to a display all the colors in a frame using setRGB method of image class. The abstract class Image is the superclass of all classes that represent graphical images. The image must be obtained in a platform-specific manner.

import java.awt.Graphics;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.awt.image.BufferedImage;

import javax.swing.JComponent;

import javax.swing.JFrame;

 

public class Main extends JComponent {

BufferedImage image;

public void initialize() {

int width = getSize().width;

int height = getSize().height;

int[] data = new int[width * height];

int index = 0;

for (int i = 0; i < height; i++) {

int red = (i * 255) / (height – 1);

for (int j = 0; j < width; j++) {

int green = (j * 255) / (width – 1);

int blue = 128;

data[index++] = (red < < 16) | (green < < 8) | blue;

}

}

image = new BufferedImage

(width, height, BufferedImage.TYPE_INT_RGB);

image.setRGB(0, 0, width, height, data, 0, width);

}

public void paint(Graphics g) {

if (image == null)

initialize();

g.drawImage(image, 0, 0, this);

}

public static void main(String[] args) {

JFrame f = new JFrame(“Display Colours”);

f.getContentPane().add(new Main());

f.setSize(300, 300);

f.setLocation(100, 100);

f.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

f.setVisible(true);

}

}

The above code sample will produce the following result.

Displays all the colours in a frame.

  1. What is threading in java?

A: A Java program can contain many threads, all of which may be created without the explicit knowledge of the developer. For now, all you need to consider is that when you write a Java application, there is an initial thread that begins its operation by executing the main() method of your application. When you write a Java applet, there is a thread that is executing the callback methods (init(), actionPerformed(), etc.) of your applet; we speak of this thread as the applet’s thread. In either case, your program starts with what you can consider as a single thread. If you want to perform I/O (particularly if the I/O might block), start a timer, or do any other task in parallel with the initial thread, you must start a new thread to perform that task.

  1. How to display text in different fonts?

A: Following example demonstrates how to display text in different fonts using setFont () method of Font class. The Font class represents fonts, which are used to render text in a visible way. A font provides the information needed to map sequences of characters to sequences of glyphs and to render sequences of glyphs on Graphics and Component objects.

import java.awt.*;

import java.awt.event.*

import javax.swing.*

public class Main extends JPanel {

String[] type = { “Serif”,”SansSerif”};

int[] styles = { Font.PLAIN, Font.ITALIC, Font.BOLD,

Font.ITALIC + Font.BOLD };

String[] stylenames =

{ “Plain”, “Italic”, “Bold”, “Bold & Italic” };

public void paint(Graphics g) {

for (int f = 0; f < type.length; f++) {

for (int s = 0; s < styles.length; s++) {

Font font = new Font(type[f], styles[s], 18);

g.setFont(font);

String name = type[f] + ” ” + stylenames[s];

g.drawString(name, 20, (f * 4 + s + 1) * 20);

}

}

}

public static void main(String[] a) {

JFrame f = new JFrame();

f.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

}

);

f.setContentPane(new Main());

f.setSize(400,400);

f.setVisible(true);

}

}

The above code sample will produce the following result.

Different font names are displayed in a frame.

  1. How to draw a line using GUI?

A: Following example demonstrates how to draw a line using draw() method of Graphics2D class with Line2D object as an argument. The setPaint () method of the Graphics2D class has been used to paint the line. Here java applet is used to display the line on a JFrame.

 

import java.awt.*;

import java.awt.event.*;

import java.awt.geom.Line2D;

import javax.swing.JApplet;

import javax.swing.JFrame;

 

public class Main extends JApplet {

public void init() {

setBackground(Color.white);

setForeground(Color.white);

}

public void paint(Graphics g) {

Graphics2D g2 = (Graphics2D) g;

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

g2.setPaint(Color.gray);

int x = 5;

int y = 7;

g2.draw(new Line2D.Double(x, y, 200, 200));

g2.drawString(“Line”, x, 250);

}

public static void main(String s[]) {

JFrame f = new JFrame(“Line”);

f.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

JApplet applet = new Main();

f.getContentPane().add(“Center”, applet);

applet.init();

f.pack();

f.setSize(new Dimension(300, 300));

f.setVisible(true);

}

}

The above code sample will produce the following result.

Line is displayed in a frame.








  1. How to display a message in a new frame?

A: Following example demonstrates how to display message in a new frame by creating a frame using JFrame() & using JFrames getContentPanel(), setSize() & setVisible() methods to display this on the frame. Here Graphics2D and Rectangle2D classes have been ued to make the initial component.  And then the message is displayed on a JPanel component.

import java.awt.*;

import java.awt.font.FontRenderContext;

import java.awt.geom.Rectangle2D;

import javax.swing.JFrame;

import javax.swing.JPanel;

public class Main extends JPanel {

public void paint(Graphics g) {

Graphics2D g2 = (Graphics2D) g;

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

g2.setFont(new Font(“Serif”, Font.PLAIN, 48));

paintHorizontallyCenteredText(g2, “Java Source”, 200, 75);

paintHorizontallyCenteredText(g2, “and”, 200, 125);

paintHorizontallyCenteredText(g2, “Support”, 200, 175);

}

protected void paintHorizontallyCenteredText(Graphics2D g2,

String s, float centerX, float baselineY) {

FontRenderContext frc = g2.getFontRenderContext();

Rectangle2D bounds = g2.getFont().getStringBounds(s, frc);

float width = (float) bounds.getWidth();

g2.drawString(s, centerX – width / 2, baselineY);

}

public static void main(String[] args) {

JFrame f = new JFrame();

f.getContentPane().add(new Main());

f.setSize(450, 350);

f.setVisible(true);

}

}

The above code sample will produce the following result.

JAVA and J2EE displayed in a new Frame.

  1. How to display a pie chart using a frame?

A: Following example displays how to a display a piechart by making Slices class & creating arc depending on the slices. In this example AWT and swing components are used to draw the chart. Arguments are passed to the drawPie () method from the main () method. And the completed chart is displayed on a JFrame.

import java.awt.Color;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Rectangle;

import javax.swing.JComponent;

import javax.swing.JFrame;

class Slice {

double value;

Color color;

public Slice(double value, Color color) {

this.value = value;

this.color = color;

}

}

class MyComponent extends JComponent {

Slice[] slices = { new Slice(5, Color.black),

new Slice(33, Color.green),

new Slice(20, Color.yellow), new Slice(15, Color.red) };

MyComponent() {}

public void paint(Graphics g) {

drawPie((Graphics2D) g, getBounds(), slices);

}

void drawPie(Graphics2D g, Rectangle area, Slice[] slices) {

double total = 0.0D;

for (int i = 0; i < slices.length; i++) {

total += slices[i].value;

}

double curValue = 0.0D;

int startAngle = 0;

for (int i = 0; i < slices.length; i++) {

startAngle = (int) (curValue * 360 / total);

int arcAngle = (int) (slices[i].value * 360 / total);

g.setColor(slices[i].color);

g.fillArc(area.x, area.y, area.width, area.height,

startAngle, arcAngle);

curValue += slices[i].value;

}

}

}

public class Main {

public static void main(String[] argv) {

JFrame frame = new JFrame();

frame.getContentPane().add(new MyComponent());

frame.setSize(300, 200);

frame.setVisible(true);

}

}

The above code sample will produce the following result.

Displays a piechart on a frame.

  1. How to draw a polygon using GUI?

A: Following example demonstrates how to draw a polygon by creating Polygon() object. Here addPoint() & drawPolygon() methods are used to draw the Polygon. The entire drawing is placed on a JFrame which is a swing component. And when closing the frame window closing event is fired to exit.

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class Main extends JPanel {

public void paintComponent(Graphics g) {

super.paintComponent(g);

Polygon p = new Polygon();

for (int i = 0; i < 5; i++)

p.addPoint((int)

(100 + 50 * Math.cos(i * 2 * Math.PI / 5)),

(int) (100 + 50 * Math.sin(i * 2 * Math.PI / 5)));

g.drawPolygon(p);

}

public static void main(String[] args) {

JFrame frame = new JFrame();

frame.setTitle(“Polygon”);

frame.setSize(350, 250);

frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

Container contentPane = frame.getContentPane();

contentPane.add(new Main());

frame.setVisible(true);

}

}

The above code sample will produce the following result.

Polygon is displayed in a frame.

  1. How to create a transparent cursor?

A: Following example demonstrates how to create a transparent cursor by using createCustomCursor() method with “invisiblecursor” as an argument. Transparent cursor is generally used to hide something on the UI layer. Like in this example cursor is used on an image.

import java.awt.*;

import java.awt.image.MemoryImageSource;

public class Main {

public static void main(String[] argv) throws Exception {

int[] pixels = new int[16 * 16];

Image image = Toolkit.getDefaultToolkit().createImage(

new MemoryImageSource(16, 16, pixels, 0, 16));

Cursor transparentCursor = Toolkit.getDefaultToolkit().

createCustomCursor(image, new Point(0, 0),

“invisibleCursor”);

System.out.println(“Transparent Cursor created.”);

}

}

The above code sample will produce the following result.

Transparent Cursor created.

  1. How to commit a query?

A: Following example uses commit () method of connection class to commit a query. You need to setup the database and modify the fields accordingly to execute the example. In JDBC by default commit is set to ‘true’ so in this example first the autocommit is turned off. And when the execution is complete commit is triggered to the database.

import java.sql.*;

public class jdbcConn {

public static void main(String[] args) throws Exception{

Class.forName(“org.apache.derby.jdbc.ClientDriver”);

Connection con = DriverManager.getConnection

(“jdbc:derby://localhost:1527/testDb”,”name”,”pass”);

Statement stmt = con.createStatement();

String query = “insert into emp values(2,’name1′,’job’)”;

String query1 =”insert into emp values(5,’name2′,’job’)”;

String query2 = “select * from emp”;

ResultSet rs = stmt.executeQuery(query2);

int no_of_rows = 0;

while (rs.next()) {

no_of_rows++;

}

System.out.println(“No. of rows before commit

statement = “+ no_of_rows);

con.setAutoCommit(false);

stmt.execute(query1);

stmt.execute(query);

con.commit();

rs = stmt.executeQuery(query2);

no_of_rows = 0;

while (rs.next()) {

no_of_rows++;

}

System.out.println(“No. of rows after commit

statement = “+ no_of_rows);

}

}

The above code sample will produce the following result. The result may vary.

No. of rows before commit statement = 1

No. of rows after commit statement = 3

  1. How to use different methods of column to Count no of columns, get column name, get column type etc?

A: Following example uses getColumnCount, getColumnName, getColumnTypeName, getColumnDisplaySize methods to get the no of columns, name of the column or type of the column in the table. You need to setup the database and modify the fields accordingly to execute the example.

import java.sql.*;

public class jdbcConn {

public static void main(String[] args) throws Exception{

Class.forName(“org.apache.derby.jdbc.ClientDriver”);

Connection con = DriverManager.getConnection

(“jdbc:derby://localhost:1527/testDb”,”name”,”pass”);

Statement stmt = con.createStatement();

String query = “select * from emp order by name”;

ResultSet rs = stmt.executeQuery(query);

ResultSetMetaData rsmd = rs.getMetaData();

System.out.println(“no of columns in the table= “+

rsmd.getColumnCount());

System.out.println(“Name of the first column “+

rsmd.getColumnName(1));

System.out.println(“Type of the second column “+

rsmd.getColumnTypeName(2));

System.out.println(“No of characters in 3rd column “+

rsmd.getColumnDisplaySize(2));

}

}

The above code sample will produce the following result. The result may vary.

no of columns in the table= 3

Name of the first columnID

Type of the second columnVARCHAR

No of characters in 3rd column20

  1. How to connect to a database using JDBC? Assume that database name is testDb and it has table named employee which has 2 records.

A: Following example uses getConnection, createStatement & executeQuery methods to connect to a database & execute queries. In this example first the driver class has been loaded and then the getConnection() method of the DriverManager class has been used to get the JDBC connection.

import java.sql.*;

public class jdbcConn {

public static void main(String[] args) {

try {

Class.forName(“org.apache.derby.jdbc.ClientDriver”);

}

catch(ClassNotFoundException e) {

System.out.println(“Class not found “+ e);

}

System.out.println(“JDBC Class found”);

int no_of_rows = 0;

try {

Connection con = DriverManager.getConnection

(“jdbc:derby://localhost:1527/testDb”,”username”,

“password”);

Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery

(“SELECT * FROM employee”);

while (rs.next()) {

no_of_rows++;

}

System.out.println(“There are “+ no_of_rows

+ ” record in the table”);

}

catch(SQLException e){

System.out.println(“SQL exception occured” + e);

}

}

}

The above code sample will produce the following result.The result may vary. You will get ClassNotfound exception if your JDBC driver is not installed properly.

JDBC Class found

There are 2 records in the table

  1. How to edit (Add or update) columns of a Table and how to delete a table?

A: Following example uses create, alter & drop SQL commands to create, edit or delete table. The execute () method is the main method used in all the operations. And then the queries are built accordingly to add, update columns or drop a table.

import java.sql.*;

public class jdbcConn {

public static void main(String[] args) throws Exception{

Class.forName(“org.apache.derby.jdbc.ClientDriver”);

Connection con = DriverManager.getConnection

(“jdbc:derby://localhost:1527/testDb”,”username”,

“password”);

Statement stmt = con.createStatement();

String query =”CREATE TABLE employees

(id INTEGER PRIMARY KEY,

first_name CHAR(50),last_name CHAR(75))”;

stmt.execute(query);

System.out.println(“Employee table created”);

String query1 = “aLTER TABLE employees ADD

address CHAR(100) “;

String query2 = “ALTER TABLE employees DROP

COLUMN last_name”;

stmt.execute(query1);

stmt.execute(query2);

System.out.println(“Address column added to the table

& last_name column removed from the table”);

String query3 = “drop table employees”;

stmt.execute(query3);

System.out.println(“Employees table removed”);

}

}

The above code sample will produce the following result. The result may vary.

Employee table created

Address column added to the table & last_name

column removed from the table

Employees table removed from the database

  1. How to execute multiple SQL commands on a database simultaneously?

A: Following example uses addBatch & executeBatch commands to execute multiple SQL commands simultaneously. The batch update functionality allows the statement objects to support the submission of a number of update commands as a single batch.The ability to batch a number of commands together can have significant performance benefits. The methods addBatch, clearBatch and executeBatch are used in processing batch updates.

import java.sql.*;

public class jdbcConn {

public static void main(String[] args) throws Exception{

Class.forName(“org.apache.derby.jdbc.ClientDriver”);

Connection con = DriverManager.getConnection

(“jdbc:derby://localhost:1527/testDb”,”name”,”pass”);

Statement stmt = con.createStatement

(ResultSet.TYPE_SCROLL_SENSITIVE,

ResultSet.CONCUR_UPDATABLE);

String insertEmp1 = “insert into emp values

(10,’jay’,’trainee’)”;

String insertEmp2 = “insert into emp values

(11,’jayes’,’trainee’)”;

String insertEmp3 = “insert into emp values

(12,’shail’,’trainee’)”;

con.setAutoCommit(false);

stmt.addBatch(insertEmp1);

stmt.addBatch(insertEmp2);

stmt.addBatch(insertEmp3);

ResultSet rs = stmt.executeQuery(“select * from emp”);

rs.last();

System.out.println(“rows before batch execution= ”

+ rs.getRow());

stmt.executeBatch();

con.commit();

System.out.println(“Batch executed”);

rs = stmt.executeQuery(“select * from emp”);

rs.last();

System.out.println(“rows after batch execution= ”

+ rs.getRow());

}

}

The above code sample will produce the following result. The result may vary.

rows before batch execution= 6

Batch executed

rows after batch execution= = 9

 

  1. How to join contents of more than one table & display?

A: Following example uses inner join sql command to combine data from two tables. To display the contents of the table getString() method of resultset is used. The join clause binds columns of both the tables to create a single table. Join matches the columns in both tables. There are two types of join statements, inner and outer joins. An inner join returns all rows that result in a match.

import java.sql.*;

public class jdbcConn {

public static void main(String[] args) throws Exception{

Class.forName(“org.apache.derby.jdbc.ClientDriver”);

Connection con = DriverManager.getConnection

(“jdbc:derby://localhost:1527/testDb”,”username”,

“password”);

Statement stmt = con.createStatement();

String query =”SELECT fname,lname,isbn from author

inner join books on author.AUTHORID = books.AUTHORID”;

ResultSet rs = stmt.executeQuery(query);

System.out.println(“Fname  Lname   ISBN”);

while (rs.next()) {

String fname = rs.getString(“fname”);

String lname = rs.getString(“lname”);

int isbn = rs.getInt(“isbn”);

System.out.println(fname + ”  ” + lname+”   “+isbn);

}

System.out.println();

System.out.println();

}

}

The above code sample will produce the following result. The result may vary.

Fname  Lname   ISBN

john  grisham   123

jeffry  archer   113

jeffry  archer   112

jeffry  archer   122

  1. How to use Prepared Statement in java?

A: Following example uses PrepareStatement method to create PreparedStatement. It also uses setInt & setString methods of PreparedStatement to set parameters of PreparedStatement. Prepared statement is a pre compiled statement which reduces the execution time of an SQL query. It is generally used where repeated query is required.

import java.sql.*;

public class jdbcConn {

public static void main(String[] args) throws Exception{

Class.forName(“org.apache.derby.jdbc.ClientDriver”);

Connection con = DriverManager.getConnection

(“jdbc:derby://localhost:1527/testDb”,”name”,”pass”);

PreparedStatement updateemp = con.prepareStatement

(“insert into emp values(?,?,?)”);

updateemp.setInt(1,23);

updateemp.setString(2,”Roshan”);

updateemp.setString(3, “CEO”);

updateemp.executeUpdate();

Statement stmt = con.createStatement();

String query = “select * from emp”;

ResultSet rs =  stmt.executeQuery(query);

System.out.println(“Id Name    Job”);

while (rs.next()) {

int id = rs.getInt(“id”);

String name = rs.getString(“name”);

String job = rs.getString(“job”);

System.out.println(id + ”  ” + name+”   “+job);

}

}

}

The above code sample will produce the following result. The result may vary.

Id Name    Job

23  Roshan   CEO








  1. How to retrieve contents of a table using JDBC connection?

A: Following example uses getString (), getInt() & executeQuery() methods to fetch & display the contents of the table. The forName () method is used to load the driver and getConnection () method is used to get the connection to the database. This example covers all the normal database activities.

import java.sql.*;

public class jdbcResultSet {

public static void main(String[] args) {

try {

Class.forName(“org.apache.derby.jdbc.ClientDriver”);

}

catch(ClassNotFoundException e) {

System.out.println(“Class not found “+ e);

}

try {

Connection con = DriverManager.getConnection

(“jdbc:derby://localhost:1527/testDb”,”username”,

“password”);

Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery

(“SELECT * FROM employee”);

System.out.println(“id  name    job”);

while (rs.next()) {

int id = rs.getInt(“id”);

String name = rs.getString(“name”);

String job = rs.getString(“job”);

System.out.println(id+”   “+name+”    “+job);

}

}

catch(SQLException e){

System.out.println(“SQL exception occured” + e);

}

}

}

The above code sample will produce the following result. The result may vary.

id  name   job

1   alok   trainee

2   ravi   trainee

============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share