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?

一: 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?

一: 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, 從Objective C協議中藉鑑的想法,,en,多接口繼承允許對象繼承許多不同的方法簽名,但需要注意的是繼承對象必須實現那些繼承的方法,,en,java的十一個設計目標是什麼?,,en,以下是java編程語言的11個設計目標,,en,Java設計者通過牢記這些目標完成了任務,,en,面向對象,,en,解讀,,en,分散式,,en,強大的,,en,多線程,,en,安全,,en,動態,,en,建築中立,,en,為什麼java被稱為分佈式,,en,Java有一個廣泛的例程庫,用於處理HTTP和FTP等TCP / IP協議,,en,因此,Java應用程序可以通過URL打開和訪問Internet上的對象,,en,使用java的網絡編程功能強大且易於使用,,en,所以java被稱為分佈式,,en. 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?

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

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

Why java is called distributed?

一: 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.

Java的分佈式特性與其動態類加載功能相結合,確實令人眼前一亮,,en,這些功能使Java解釋器可以從Internet下載和運行代碼,,en,這是Web瀏覽器下載並運行Java applet時發生的情況,,en,場景可能比這更複雜,,en,想像一下用Java編寫的多媒體文字處理器,,en,當要求該程序顯示以前從未遇到過的某種類型的數據時,,en,它可以從網絡中動態下載一個可以解析數據的類,,en,然後動態下載另一個類,,en,可能是一個Java,,en,可以顯示複合文檔中的數據,,en,像這樣的程序使用網絡上的分佈式資源來動態增長並適應其用戶的需求,,en. 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, 例如. 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. 為什麼java被稱為架構中立,,en,Java編譯器生成一個獨立於計算機體系結構的字節碼指令,,en,字節碼設計為易於在任何機器上解釋,並且可以在運行中輕鬆轉換為本機機器代碼,,en,下圖顯示了其工作原理的詳細信息,,en,Java架構中立,,en,為什麼運行applet需要支持java的瀏覽器,,en,Applet是一個在網頁上運行的java程序,,en,因此瀏覽器應該具有解釋字節碼並使其工作的能力,,en,這就是為什麼需要支持java的瀏覽器來運行嵌入在網頁中的applet,,en,實際上瀏覽器包含內置的JVM,它有助於解釋字節代碼並顯示輸出,,en?

一: 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?

一: 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. 你是什​​麼意思'Java是一種強類型語言',,en,Java強類型意味著java中的每個變量都必須具有聲明的類型,,en,Java中有八種原始類型,,en,其中四個是整數類型,兩個是浮點數類型,,en,一個是字符類型char,,en,用於Unicode編碼中的字符,一個是真值的布爾類型,,en,如何在java中管理I / O.,,en,在java中,I / O表示輸入和輸出流,,en,流用於讀取或寫入設備,如文件或網絡或控制台,,en,Java.io包提供了操作流的I / O類,,en,該包支持兩種類型的流,,en,處理二進制數據的二進制流和處理字符數據的字符流,,en?

一: 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?

一: 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和OutputStream是用於操作二進制流的高級接口,,en,Reader和Writer是用於處理字符流的高級接口,,en,下圖顯示了本節中介紹的不同IO類的關係,,en,不同的I / O類,,en,緩衝流如何提高java中的性能,,en,流的默認行為是一次讀取或寫入一個字節,,en,這會導致較差的I / O性能,因為在處理大量數據時,需要花費大量時間逐字節讀/寫,,en,Java I / O提供緩衝流來覆蓋這些逐字節的默認行為,,en,您需要使用緩衝流,,en,BufferedInputStream和BufferedOutputStream,,en,緩衝數據然後讀/寫,這提供了良好的性能,,en. 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?

一: 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. 您需要了解方法的默認行為並採取相應措施,,en,下圖顯示了緩衝流如何轉移數據流,,en,緩衝流,,en,如何衡量默認行為的性能和文件讀取的緩衝,,en,以下代碼片段將使用默認讀取和緩衝讀取來讀取和寫入類似的文件,,en,然後它將顯示兩者所花費的時間,,en,為了測試代碼,請將文件保存在本地文件系統中,如下所示,,en,緩衝文件讀取,,en,包com.performance.io,,en,公共課IOTest,,en,IOTest io =新的IOTest,,it,long startTime = System.currentTimeMillis,,en,io.readWrite,,en,溫度/測試origin.html,,en,溫度/測試destination.html,,en,long endTime = System.currentTimeMillis,,en,使用默認行為進行讀寫所需的時間,,en,時間結束,,en,開始時間,,en,毫秒,,en.

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?

一: 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;

 

進口java.io. *;

public class IOTest {

公共靜態無效的主要(串[] 參數){

IOTest io = new IOTest();

嘗試{

long startTime = System.currentTimeMillis();

io.readWrite(“Ç:/temp/test-origin.html”,”Ç:/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,,en,io.readWriteBuffer,,en,long endTime1 = System.currentTimeMillis,,en,使用緩衝流進行讀寫的時間,,en,endTime1,,en,startTime1,,sv,public static void readWrite,,en,字符串文件來自,,fy,字符串文件,,bg,InputStream in = null,,en,OutputStream out = null,,en,in = new FileInputStream,,en,fileFrom,,fy,out = new FileOutputStream,,en,fileTo,,el,int bytedata = in.read,,en,字節數據==,,sv,字節數據,,sv,最後,,en,附寄,,en,public static void readWriteBuffer,,en,InputStream inBuffer = null,,en,OutputStream outBuffer = null,,en,InputStream in = new FileInputStream,,en,inBuffer = new BufferedInputStream,,en,OutputStream out = new FileOutputStream,,en,outBuffer = new BufferedOutputStream,,en,int bytedata = inBuffer.read,,en,inBuffer,,en,inBuffer.close,,en,outBuffer,,en,outBuffer.close,,en,techalpine.com/10-java-tips-series-i,,en();

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

long endTime1 = System.currentTimeMillis();

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

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

}抓(IOException異常Ë){ e.printStackTrace();}

}

public static void readWrite(String fileFrom, String fileTo) 拋出IOException異常{

InputStream in = null;

OutputStream out = null;

嘗試{

in = new FileInputStream(fileFrom);

out = new FileOutputStream(fileTo);

while(真){

int bytedata = in.read();

如果(bytedata == -1)

break;

out.write(bytedata);

}

}

抓(例外五)

{

e.printStackTrace();

}

finally{

如果(in != NULL)

in.close();

如果(出 !=null)

out.close();

}

}

public static void readWriteBuffer(String fileFrom, String fileTo) 拋出IOException異常{

InputStream inBuffer = null;

OutputStream outBuffer = null;

嘗試{

InputStream in = new FileInputStream(fileFrom);

inBuffer = new BufferedInputStream(in);

OutputStream out = new FileOutputStream(fileTo);

outBuffer = new BufferedOutputStream(出);

while(真){

int bytedata = inBuffer.read();

如果(bytedata == -1)

break;

out.write(bytedata);

}

}

抓(例外五)

{

e.printStackTrace();

}

finally{

如果(inBuffer != NULL)

inBuffer.close();

如果(outBuffer !=null)

outBuffer.close();

}

}

)

  1. What is collections framework in java?

一: 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?

一: 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.

公共類主 {

公共靜態無效的主要(串[] 參數) {

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

串[] extended = new String[5];

extended[3] = “ð”;

extended[4] = “它”;

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

為 (String str : extended){

System.out.println(海峽);

}

}

}

And the result will be as follows

X
Y
Z
ð

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

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

import java.util.*;

public class FillTest {

公共靜態無效的主要(字符串參數[]) {

int array[] = new int[6];

Arrays.fill(排列, 100);

為 (int i=0, n=array.length; 我 < Ň; 我 ) {

System.out.println(排列[我]);

}

System.out.println();

Arrays.fill(排列, 3, 6, 50);

為 (int i=0, n=array.length; 我< Ň; 我 ) {

System.out.println(排列[我]);

}

}

}

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?

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

public class Matrix{

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

int m1rows = m1.length;

int m1cols = m1[0].length;

int m2rows = m2.length;

int m2cols = m2[0].length;

如果 (m1cols != m2rows){

throw new IllegalArgumentException(“matrices

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

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

為 (int i=0; 我< m1rows; 我 ){

為 (int j=0; Ĵ< m2cols; J ){

為 (int k=0; ķ< m1cols; k ){

result[我][Ĵ] += m1[我][ķ] * m2[ķ][Ĵ];

return result;

)

}

}

}

}

/** Matrix print.

*/

public static void mprint(詮釋[][] 一){

int rows = a.length;

int cols = a[0].length;

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

為 (int i=0; 我< rows; 我 ){

System.out.print(“{“);

為 (int j=0; Ĵ< COLS; J ){

System.out.print(” ” + 一[我][Ĵ] + “,”);

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

}

}

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

}

公共靜態無效的主要(串[] 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

排列[2][3]={

{3, 2, 3}

{5, 9, 8}

};

排列[3][2]={

{4, 7}

{9, 3}

{8, 1}

};

排列[2][2]={

{63, 30}

{165, 70}

};

  1. How to merge two arrays?

一: 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;

進口的java.util.List;

公共類主 {

公共靜態無效的主要(字符串參數[]) {

String a[] = { “一”, “它”, “I” };

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

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

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

目的[] c = list.toArray();

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

}

}

The code sample will produce the following result

[一, 它, I, O, U]

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

一: 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;

公共類主 {

公共靜態無效的主要(串[] 參數) {

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

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

int max = (詮釋) 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?

一: 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;

公共類主 {

公共靜態無效的主要(串[] 參數) {

ArrayList arrayList = new ArrayList();

arrayList.add(“一”);

arrayList.add(“乙”);

arrayList.add(“Ç”);

arrayList.add(“ð”);

arrayList.add(“它”);

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: [一, 乙, Ç, ð, 它]

After Reverse Order: [它, ð, Ç, 乙, 一]

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

一: 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 {

公共靜態無效的主要(字符串參數[]) 拋出異常 {

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

Arrays.sort(排列);

printArray(“Sorted array”, 排列);

int index = Arrays.binarySearch(排列, 1);

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

+ index);

int newIndex = -index – 1;

array = insertElement(排列, 1, newIndex);

printArray(“With 1 額外”, 排列);

}

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

System.out.println(信息

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

為 (INT I = 0; 我 < array.length; 我 ) {

如果 (我 != 0){

System.out.print(“, “);

}

System.out.print(排列[我]);

}

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?

一: 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 {

公共靜態無效的主要(字符串參數[]) 拋出異常 {

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

Arrays.sort(排列);

printArray(“Sorted array”, 排列);

int index = Arrays.binarySearch(排列, 2);

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

}

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

System.out.println(信息

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

為 (INT I = 0; 我 < array.length; 我 ) {

如果(我 != 0){

System.out.print(“, “);

}

System.out.print(排列[我]);

}

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?

一: 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(這個);

b = false;

t.start();

}

public void run () {

char ch;

為( ; ; ) {

嘗試 {

repaint();

視頻下載(250);

ch = str.charAt(0);

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

str = str + ch;

}

抓(InterruptedException的Ë) {}

}

}

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(海峽, 1, 150);

}

}

  1. How to display a clock using an applet?

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

進口的軟件包java.awt。*;

import java.applet.*;

import java.applet.*;

進口的軟件包java.awt。*;

import java.util.*;

public class ClockApplet extends Applet implements Runnable{

Thread t,t1;

public void start(){

t = new Thread(這個);

t.start();

}

public void run(){

t1 = Thread.currentThread();

while(t1 == t){

repaint();

嘗試{

t1.sleep(1000);

}

抓(InterruptedException的Ë){}

}

}

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 + “:” + 第二, 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?

一: 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) & 按鍵() constructor to create a button.

import java.applet.*;
import java.awt.event.*;
進口的軟件包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);

加(txtArea,”center”);

Button b = new Button(“Add”);

Button c = new Button(“Subtract”);

b.addActionListener(這個);

c.addActionListener(這個);

加(b);

加(Ç);

}

public void actionPerformed(ActionEvent e){

sum = i + Ĵ;

txtArea.setText(“”);

txtArea.append(“I = “+ 我 + “\t” + “j = ” + Ĵ + “\Ň”);

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

如果(source.getLabel() == “Add”){

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

}

如果(我 >Ĵ){

Sub = i – Ĵ;

}

其他{

Sub = j – 我;

}

如果(source.getLabel() == “Subtract”){

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

}

}

}

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

一: 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.*;

進口的軟件包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(這個);

加(b);

}

public void actionPerformed(ActionEvent ae){

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

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

嘗試 {

AppletContext a = getAppletContext();

URL url = new URL(link);

a.showDocument(url,”_blank”);

}

抓 (MalformedURLException e){

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

}

}

}

  1. How to read a file using Applet?

一: 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.*;

進口的軟件包java.awt。*;

進口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);

加(txtArea, “center”);

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

如果 (prHtml != NULL) fileToRead = new String(prHtml);

readFile();

}

public void readFile(){

String line;

URL url = null;

嘗試{

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

}

抓(MalformedURLException e){}

嘗試{

InputStream in = url.openStream();

BufferedReader bf = new BufferedReader

(new InputStreamReader(in));

strBuff = new StringBuffer();

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

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

}

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

txtArea.append(strBuff.toString());

}

抓(IOException異常Ë){

e.printStackTrace();

}

}

}








  1. How to create different shapes using Applet?

一: 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.*;

進口的軟件包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?

一: 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.

導入javax.swing中。;

import java.applet.*;

進口的軟件包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 : “);

加(label1);

label1.setBackground(Color.yellow);

label1.setForeground(Color.magenta);

input = new TextField(5);

加(輸入);

label2 = new Label(“Sum : “);

加(label2);

label2.setBackground(Color.yellow);

label2.setForeground(Color.magenta);

output = new TextField(20);

加(output);

b1 = new Button(“Add”);

加(B1);

b1.addActionListener(這個);

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

加(lbl);

的setBackground(Color.yellow);

}

public void actionPerformed(ActionEvent ae){

嘗試{

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());

}

抓(NumberFormatException e){

lbl.setForeground(Color.red);

lbl.setText(“Invalid Entry!”);

}

}

}

  1. How to write to a file using Applet?

一: 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.

進口java.io. *;

進口的軟件包java.awt。*;

import java.awt.event.*;

導入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(){

加(label1);

label1.setBackground(Color.lightGray);

加(text);

加(label2);

label2.setBackground(Color.lightGray);

加(area);

加(write,BorderLayout.CENTER);

write.addActionListener(new ActionListener (){

public void actionPerformed(ActionEvent e){

new WriteText();

}

}

);

}

public class WriteText {

WriteText(){

嘗試 {

String str = text.getText();

如果(str.equals(“”)){

JOptionPane.showMessageDialog(零,

“Please enter the file name!”);

text.requestFocus();

}

其他{

File f = new File(海峽);

如果(f.exists()){

BufferedWriter out = new

BufferedWriter(新的FileWriter中(f,真));

如果(area.getText().等於(“”)){

JOptionPane.showMessageDialog

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

area.requestFocus();

}

其他{

out.write(area.getText());

如果(f.canWrite()){

JOptionPane.showMessageDialog(零,

“Text is written in “+海峽);

text.setText(“”);

area.setText(“”);

text.requestFocus();

}

其他{

JOptionPane.showMessageDialog(零,

“Text isn’t written in “+海峽);

}

out.close();

}

}

其他{

JOptionPane.showMessageDialog

(零,”File not found!”);

text.setText(“”);

text.requestFocus();

}

}

}

抓(Exception x){

x.printStackTrace();

}

}

}

}

  1. How to print summation of n numbers?

一: 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.

進口java.io.IOException異常;

public class AdditionStack {

static int num;

static int ans;

static Stack theStack;

公共靜態無效的主要(串[] 參數) 拋出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?

一: 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;

公共類主 {

公共靜態無效的主要(串[] 參數) {

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?

一: 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;

公共類主 {

公共靜態無效的主要(串[] 參數) {

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?

一: 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.

進口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() {

為 (INT J = 0; Ĵ < input.length(); J ) {

char ch = input.charAt(Ĵ);

switch (ch) {

case ‘ ’:

case ‘-‘:

gotOper(ch, 1);

break;

case ‘*’:

case ‘/’:

gotOper(ch, 2);

break;

case ‘(&#8216;:

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();

如果 (opTop == ‘(&#8216;) {

theStack.push(opTop);

break;

}

其他 {

int prec2;

如果 (opTop == ‘ ’ || opTop == ‘-‘)

prec2 = 1;

其他

prec2 = 2;

如果 (prec2 < prec1)

{

theStack.push(opTop);

break;

} 其他

output = output + opTop;

}

}

theStack.push(opThis);

}

 

public void gotParen(char ch){

while (!theStack.isEmpty()) {

char chx = theStack.pop();

如果 (chx == ‘(&#8216;)

break;

其他

output = output + chx;

}

}

 

公共靜態無效的主要(串[] 參數) 拋出IOException異常 {

 

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

String output;

InToPost theTrans = new InToPost(輸入);

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?

一: 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(項目);

}

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 {

公共靜態無效的主要(串[] 參數) {

GenQueue empList;

empList = new GenQueue();

GenQueue hList;

hList = new GenQueue();

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

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

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) {

非常(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?

一: 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

進口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);

 

為 (INT I = 0; 我 < input.length(); 我 ) {

char ch = input.charAt(我);

theStack.push(ch);

}

output = “”;

while (!theStack.isEmpty()) {

char ch = theStack.pop();

output = output + ch;

}

return output;

}

公共靜態無效的主要(串[] 參數) 拋出IOException異常 {

String input = “Java Source and Support”;

String output;

StringReverserThroughStack theReverser =

new StringReverserThroughStack(輸入);

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?

一: 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;

進口javax.swing.JFrame;

 

公共類主 {

公共靜態無效的主要(串[] 參數) {

JFrame frame = new JFrame();

frame.add(new MyComponent());

frame.setSize(300, 300);

frame.setVisible(真);

}

}

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?

一: 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;

進口javax.swing.JFrame;

 

public class Main extends JComponent {

BufferedImage image;

public void initialize() {

int width = getSize().width;

int height = getSize().height;

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

int index = 0;

為 (INT I = 0; 我 < height; 我 ) {

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

為 (INT J = 0; Ĵ < width; J ) {

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

int blue = 128;

data[index ] = (紅 < < 16) | (綠色 < < 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) {

如果 (image == null)

initialize();

g.drawImage(image, 0, 0, 這個);

}

公共靜態無效的主要(串[] 參數) {

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

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

f.setSize(300, 300);

f.setLocation(100, 100);

f.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

f.setVisible(真);

}

}

The above code sample will produce the following result.

Displays all the colours in a frame.

  1. What is threading in java?

一: 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?

一: 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.

進口的軟件包java.awt。*;

import java.awt.event.*

導入javax.swing中。

public class Main extends JPanel {

串[] 類型= { “Serif”,”SansSerif”};

詮釋[] styles = { Font.PLAIN, Font.ITALIC, Font.BOLD,

Font.ITALIC + Font.BOLD };

串[] stylenames =

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

public void paint(Graphics g) {

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

為 (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(名稱, 20, (f * 4 + s + 1) * 20);

}

}

}

公共靜態無效的主要(串[] 一) {

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(真);

}

}

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?

一: 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.

 

進口的軟件包java.awt。*;

import java.awt.event.*;

import java.awt.geom.Line2D;

import javax.swing.JApplet;

進口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);

}

公共靜態無效的主要(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().加(“Center”, applet);

applet.init();

f.pack();

f.setSize(新尺寸(300, 300));

f.setVisible(真);

}

}

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?

一: 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.

進口的軟件包java.awt。*;

import java.awt.font.FontRenderContext;

java.awt.geom.Rectangle2D金額;

進口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, “和”, 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);

}

公共靜態無效的主要(串[] 參數) {

JFrame f = new JFrame();

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

f.setSize(450, 350);

f.setVisible(真);

}

}

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?

一: 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 () 方法. And the completed chart is displayed on a JFrame.

進口了java.awt.Color;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Rectangle;

import javax.swing.JComponent;

進口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;

為 (INT I = 0; 我 < slices.length; 我 ) {

total = slices[我].值;

}

double curValue = 0.0D;

int startAngle = 0;

為 (INT I = 0; 我 < slices.length; 我 ) {

startAngle = (詮釋) (curValue * 360 / 總);

int arcAngle = (詮釋) (slices[我].值 * 360 / 總);

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

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

startAngle, arcAngle);

curValue = slices[我].值;

}

}

}

公共類主 {

公共靜態無效的主要(串[] argv) {

JFrame frame = new JFrame();

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

frame.setSize(300, 200);

frame.setVisible(真);

}

}

The above code sample will produce the following result.

Displays a piechart on a frame.

  1. How to draw a polygon using GUI?

一: Following example demonstrates how to draw a polygon by creating Polygon() 目的. 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.

進口的軟件包java.awt。*;

import java.awt.event.*;

導入javax.swing中。;

public class Main extends JPanel {

public void paintComponent(Graphics g) {

super.paintComponent(g);

Polygon p = new Polygon();

為 (INT I = 0; 我 < 5; 我 )

p.addPoint((詮釋)

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

(詮釋) (100 + 50 * Math.sin(我 * 2 * Math.PI / 5)));

g.drawPolygon(p);

}

公共靜態無效的主要(串[] 參數) {

JFrame frame = new JFrame();

frame.setTitle(“多邊形”);

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(真);

}

}

The above code sample will produce the following result.

Polygon is displayed in a frame.

  1. How to create a transparent cursor?

一: 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.

進口的軟件包java.awt。*;

import java.awt.image.MemoryImageSource;

公共類主 {

公共靜態無效的主要(串[] argv) 拋出異常 {

詮釋[] 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?

一: 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 {

公共靜態無效的主要(串[] 參數) 拋出異常{

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

Connection con = DriverManager.getConnection

(“JDBC:derby://本地:1527/testDb”,”名稱”,”pass”);

Statement stmt = con.createStatement();

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

字符串query1 =,en,’名稱2,en,字符串query2 =,en,來自EMP,en,Resultset RS = STMT.ExecuteQuery,en,query2,pt,int no_of_rows =,en,Rs.next,en,NO_OF_ROWS ,en,提交之前的行,en,語句=,en,no_of_rows,en,con.setautocommit,en,stmt.execute,en,query1,pt,con.commit,en,rs = stmt.executequery,en,no_of_rows =,en,提交後行,en,結果可能有所不同,en,提交語句=之前的行,en,commit語句之後的行=,en,如何使用不同的列方法來計算列,en,獲取列名,en,獲取列類型等,en,以下示例使用getColumnCount,en,getColumnname,en,GetColumnTypename,en,getColumnDisplaysize方法以獲取列,en,表格中的列的名稱或類型,en,從EMP訂單按名稱,en,resultsetsetmetadata rsmd = rs.getMetadata,en,表中沒有列=,en,RSMD.GetColumnCount,en,第一列的名稱,en,rsmd.getColumnname,en,第二列的類型,en,rsmd.getColumnTypename,en”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(詢問);

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?

一: 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 {

公共靜態無效的主要(串[] 參數) 拋出異常{

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

Connection con = DriverManager.getConnection

(“JDBC:derby://本地:1527/testDb”,”名稱”,”pass”);

Statement stmt = con.createStatement();

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

ResultSet rs = stmt.executeQuery(詢問);

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(“第三列中沒有字符,en,rsmd.getColumnDisplaysize,en,第一個列的名稱,en,第二個柱面的類型,en,第三列中沒有字符,en,如何使用JDBC連接到數據庫,en,假設數據庫名稱是testDB,並且具有名為僱員的表,en,以下示例使用getConnection,en,創作,en,執行方法可以連接到數據庫,en,執行查詢,en,在此示例中,首先已加載驅動程序類,然後是GetConnection,en,DriverManager類的方法已用於獲得JDBC連接,en,找不到課,en,發現JDBC課程,en,來自員工,en,記錄表,en,sqlexception e,en,SQL異常,en,以上代碼樣本將產生以下結果。結果可能會有所不同,en,如果您的JDBC驅動程序未正確安裝,您將獲得ClassNotFound異常,en,表中的記錄,en “+

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 記錄.

一: 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 {

公共靜態無效的主要(串[] 參數) {

嘗試 {

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

}

抓(ClassNotFoundException e) {

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

}

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

int no_of_rows = 0;

嘗試 {

Connection con = DriverManager.getConnection

(“JDBC:derby://本地:1527/testDb”,”用戶名”,

“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”);

}

抓(SQLException e){

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

}

}

}

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?

一: 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 {

公共靜態無效的主要(串[] 參數) 拋出異常{

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

Connection con = DriverManager.getConnection

(“JDBC:derby://本地:1527/testDb”,”用戶名”,

“password”);

Statement stmt = con.createStatement();

String query =”CREATE TABLE employees

(id INTEGER PRIMARY KEY,

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

stmt.execute(詢問);

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

字符串query1 =,en,’名稱2,en,字符串query2 =,en,來自EMP,en,Resultset RS = STMT.ExecuteQuery,en,query2,pt,int no_of_rows =,en,Rs.next,en,NO_OF_ROWS ,en,提交之前的行,en,語句=,en,no_of_rows,en,con.setautocommit,en,stmt.execute,en,query1,pt,con.commit,en,rs = stmt.executequery,en,no_of_rows =,en,提交後行,en,結果可能有所不同,en,提交語句=之前的行,en,commit語句之後的行=,en,如何使用不同的列方法來計算列,en,獲取列名,en,獲取列類型等,en,以下示例使用getColumnCount,en,getColumnname,en,GetColumnTypename,en,getColumnDisplaysize方法以獲取列,en,表格中的列的名稱或類型,en,從EMP訂單按名稱,en,resultsetsetmetadata rsmd = rs.getMetadata,en,表中沒有列=,en,RSMD.GetColumnCount,en,第一列的名稱,en,rsmd.getColumnname,en,第二列的類型,en,rsmd.getColumnTypename,en “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 & 姓

column removed from the table

Employees table removed from the database

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

一: 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 {

公共靜態無效的主要(串[] 參數) 拋出異常{

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

Connection con = DriverManager.getConnection

(“JDBC:derby://本地:1527/testDb”,”名稱”,”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?

一: 以下示例使用內部加入SQL命令來組合兩個表的數據,en,顯示表格串的內容,en,使用結果集的方法,en,聯接子句綁定了兩個表的列以創建一個表格,en,加入兩個表中的列匹配,en,有兩種類型的加入語句,en,內部和外部連接,en,內部連接返回導致比賽的所有行,en,選擇fname,en,來自作者的ISBN,en,內部加入作者的書籍。authorid= books.authorid,en,fname lname isbn,en,字符串fname = rs.getString,en,字符串lname = rs.getString,en,int isbn = rs.getInt,en,ISBN,en,lname ,en,約翰·格里森(John Grisham),en,杰弗裡·阿切爾(Jeffry Archer),en,如何在Java中使用準備好的陳述,en,以下示例使用準備播放方法來創建準備序列,en,它也使用setint,en. 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 {

公共靜態無效的主要(串[] 參數) 拋出異常{

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

Connection con = DriverManager.getConnection

(“JDBC:derby://本地:1527/testDb”,”用戶名”,

“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(詢問);

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?

一: 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 {

公共靜態無效的主要(串[] 參數) 拋出異常{

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

Connection con = DriverManager.getConnection

(“JDBC:derby://本地:1527/testDb”,”名稱”,”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(詢問);

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

while (rs.next()) {

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

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

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?

一: 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 {

公共靜態無效的主要(串[] 參數) {

嘗試 {

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

}

抓(ClassNotFoundException e) {

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

}

嘗試 {

Connection con = DriverManager.getConnection

(“JDBC:derby://本地:1527/testDb”,”用戶名”,

“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(“名稱”);

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

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

}

}

抓(SQLException e){

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

}

}

}

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

id name job

1 alok trainee

2 ravi trainee

============================================= ============================================== 在亞馬遜上購買最佳技術書籍,en,電工CT Chestnutelectric,en
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share