50 Core Java interview questions and answers

Java interview questions and answers

50 Core Java interview questions and answers

  1. メモリは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.

代わりに, Java’s designers chose to allow multiple interface inheritance through the use of interfaces, Objective Cのプロトコルから借りたアイデア,,en,複数のインタフェースの継承により、オブジェクトは、継承するオブジェクトがそれらの継承されたメソッドを実装しなければならないという注意を払って、多くの異なるメソッドシグネチャを継承できます,,en,Javaの11の設計目標は何ですか?,,en,以下は、Javaプログラミング言語の11の設計目標です,,en,Javaデザイナーは、これらの目標を念頭に置いてタスクを達成しました,,en,オブジェクト指向,,en,解釈された,,en,分散,,en,ロバスト,,en,マルチスレッド,,en,安全な,,en,動的,,en,建築中立,,en,なぜjavaは分散型と呼ばれるのですか?,,en,Javaには、HTTPやFTPなどのTCP / IPプロトコルを処理するための豊富なルーチンライブラリがあります,,en,そのため、JavaアプリケーションはURL経由でインターネット上のオブジェクトを開いたりアクセスしたりすることができます,,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?

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
    • ハイパフォーマンス
    • 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.

動的なクラスローディング機能と組み合わせると、Javaの分散された性質が本当に輝きます,,en,これらの機能により、Javaインタープリタはインターネットからコードをダウンロードして実行することができます,,en,WebブラウザがJavaアプレットをダウンロードして実行すると、これが起こります,,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,Java対応のブラウザがアプレットを実行するために必要な理由,,en,アプレットはWebページ上で動作するJavaプログラムです,,en,したがって、ブラウザには、バイトコードを解釈して機能させる機能が必要です,,en,そのため、Webページに埋め込まれたアプレットを実行するにはJava対応ブラウザが必要です,,en,実際には、ブラウザにはバイトコードの解釈と出力の表示に役立つJVMが組み込まれています,,en?

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. 「Javaは強く型付けされた言語です」とはどういう意味ですか?,,en,Javaは強く型付けされているということは、javaのすべての変数は宣言された型,,en,Javaには8つのプリミティブ型があります,,en,4つは整数型で、2つは浮動小数点型です,,en,1つは文字タイプchar,,en,Unicodeエンコーディングの文字に使用され、1つは真偽値のブール型です,,en,JavaでI / Oをどのように管理するか,,en,Java I / Oでは入力ストリームと出力ストリームを表します,,en,ストリームは、ファイルやネットワーク、コンソールなどのデバイスの読み書きに使用されます。,,en,Java.ioパッケージは、ストリームを操作するためのI / Oクラスを提供します,,en,このパッケージは2種類のストリームをサポートしています,,en,バイナリデータを扱うバイナリストリームと、文字データを扱う文字ストリーム,,en?

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とOutputStreamは、バイナリストリームを操作するための高水準インタフェースです,,en,リーダとライタは、文字ストリームを操作するための高水準のインタフェースです,,en,次の図は、このセクションで扱うさまざまなIOクラスの関係を示しています,,en,異なるI / Oクラス,,en,バッファリングされたストリームはJavaのパフォーマンスをどのように向上させますか,,en,ストリームのデフォルトの動作は、一度に1バイトを読み書きすることです,,en,これは、大量のデータを扱うときに1バイトずつ読み書きするのに時間がかかるため、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?

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. メソッドのデフォルト動作を理解し、それに基づいて動作する必要があります,,en,次の図は、バッファリングされたストリームがデータフローをどのように迂回するかを示しています,,en,バッファリングされたストリーム,,en,ファイルの読み込みのデフォルト動作とバッファリングのパフォーマンスをどのように測定しますか,,en,次のコードスニペットは、既定の読み取りとバッファ付きの読み取りを使用して、読み取りと書き込みを行う同様のファイルを取ります,,en,そして、両方の時間が表示されます,,en,コードをテストするには、以下のようにファイルをローカルファイルシステムに保管してください,,en,ファイルの読み込みのためのバッファリング,,en,package com.performance.io,,en,パブリッククラスIOTest,,en,IOTest io =新しいIOTest,,en,長いstartTime = System.currentTimeMillis,,en,io.readWrite,,en,temp / test-origin.html,,en,temp / test-destination.html,,en,long endTime = System.currentTimeMillis,,en,既定の動作を使用して読み書きするのにかかる時間,,en,終了時間,,en,始まる時間,,en,ミリ秒,,kn.

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 {

公共の静的な無効メイン(文字列[] argsに){

IOTest io = new IOTest();

試す{

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

 

長いstartTime1 = System.currentTimeMillis,,en,io.readWriteBuffer,,en,long endTime1 = System.currentTimeMillis,,en,バッファリングされたストリームを使用して読み書きする時間,,en,endTime1,,en,startTime1,,fi,public static void readWrite,,en,文字列fileFrom,,fy,String fileTo,,el,InputStream in = null,,en,OutputStream out = null,,en,in =新しいFileInputStream,,en,ファイルから,,fy,out =新しいFileOutputStream,,en,fileTo,,el,int bytedata = in.read,,en,バイトデータ==,,sv,バイトデータ,,sv,最後に,,en,in.close,,en,public static void readWriteBuffer,,en,InputStream inBuffer = null,,en,OutputStream outBuffer = null,,en,InputStream in =新しいFileInputStream,,en,inBuffer =新しいBufferedInputStream,,en,OutputStream out =新しいFileOutputStream,,en,outBuffer =新しい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(“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” );

}キャッチ(IOExceptionが電子){ e.printStackTrace();}

}

public static void readWrite(String fileFrom, String fileTo) throws 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);

}

}

キャッチ(Exception e)

{

e.printStackTrace();

}

finally{

場合(in != null)

in.close();

場合(外に !=null)

out.close();

}

}

public static void readWriteBuffer(String fileFrom, String fileTo) throws 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);

}

}

キャッチ(Exception e)

{

e.printStackTrace();

}

finally{

場合(inBuffer != null)

inBuffer.close();

場合(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 {

公共の静的な無効メイン(文字列[] argsに) {

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

文字列[] extended = new String[5];

extended[3] = “D”;

extended[4] = “それ”;

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

のために (String str : extended){

System.out.printlnは(str);

}

}

}

And the result will be as follows

X
Y
Z
D
それ

  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, 値) method and Array.fill (arrayname, starting index, ending index, 値) method of Java Util class.

import java.util.*;

public class FillTest {

公共の静的な無効メイン(String args[]) {

int array[] = new int[6];

Arrays.fill(array, 100);

のために (I = 0 int型, n=array.length; 私 < N; 私 ) {

System.out.printlnは(array[私]);

}

System.out.printlnは();

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

のために (I = 0 int型, n=array.length; 私< N; 私 ) {

System.out.printlnは(array[私]);

}

}

}

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;

場合 (m1cols != m2rows){

throw new IllegalArgumentException(“matrices

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

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

のために (I = 0 int型; 私< m1rows; 私 ){

のために (int j=0; j< m2cols; j ){

のために (int k=0; k< m1cols; k ){

result[私][j] += m1[私][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 ”] = {“);

のために (I = 0 int型; 私< rows; 私 ){

System.out.print(“{“);

のために (int j=0; j< cols; j ){

System.out.print(” ” + A[私][j] + “,”);

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, と);

Matrix.mprint(X);

Matrix.mprint(と);

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 {

公共の静的な無効メイン(String args[]) {

String a[] = { “A”, “それ”, “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, それ, 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 {

公共の静的な無効メイン(文字列[] 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 {

公共の静的な無効メイン(文字列[] argsに) {

ArrayList arrayList = new ArrayList();

arrayList.add(“A”);

arrayList.add(“B”);

arrayList.add(“C言語”);

arrayList.add(“D”);

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: [A, B, C言語, D, それ]

After Reverse Order: [それ, 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 {

公共の静的な無効メイン(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(文字列メッセージ, int array[]) {

System.out.printlnは(message

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

のために (int型私= 0; 私 < array.length; 私 ) {

場合 (私 != 0){

System.out.print(“, “);

}

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

}

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 {

公共の静的な無効メイン(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(文字列メッセージ, int array[]) {

System.out.printlnは(message

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

のために (int型私= 0; 私 < array.length; 私 ) {

場合(私 != 0){

System.out.print(“, “);

}

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

}

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;

のために( ; ; ) {

試す {

repaint();

のThread.sleep(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(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();

試す{

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 + “:” + 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型私= 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(this);

c.addActionListener(this);

加える(B);

加える(C言語);

}

public void actionPerformed(ActionEvent e){

sum = i + j;

txtArea.setText(“”);

txtArea.append(“I = “+ 私 + “\t” + “j = ” + j + “\N”);

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

場合(source.getLabel() == “Add”){

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

}

場合(私 >j){

Sub = i – j;

}

ほかに{

Sub = j – 私;

}

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

加える(B);

}

public void actionPerformed(ActionEvent ae){

Button source = (Button)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?

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

加える(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 + “\N”);

}

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

txtArea.append(strBuff.toString());

}

キャッチ(IOExceptionが電子){

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.

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

加える(label1);

label1.setBackground(Color.yellow);

label1.setForeground(Color.magenta);

input = new TextField(5);

加える(input);

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

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?

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

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

加える(書きます,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(str);

場合(f.exists()){

BufferedWriter out = new

BufferedWriter(新しいFileWriter(F,真));

場合(area.getText().equals(“”)){

JOptionPane.showMessageDialog

(ゼロ,”Please enter your text!”);

area.requestFocus();

}

ほかに{

out.write(area.getText());

場合(f.canWrite()){

JOptionPane.showMessageDialog(ゼロ,

“Text is written in “+str);

text.setText(“”);

area.setText(“”);

text.requestFocus();

}

ほかに{

JOptionPane.showMessageDialog(ゼロ,

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

}

out.close();

}

}

ほかに{

JOptionPane.showMessageDialog

(ゼロ,”File not found!”);

text.setText(“”);

text.requestFocus();

}

}

}

キャッチ(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.

輸入java.io.IOExceptionが;

public class AdditionStack {

static int num;

static int ans;

static Stack theStack;

公共の静的な無効メイン(文字列[] 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() {

リターン (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 {

公共の静的な無効メイン(文字列[] 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 {

公共の静的な無効メイン(文字列[] 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.

輸入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; j < input.length(); j ) {

char ch = input.charAt(j);

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;

}

}

 

公共の静的な無効メイン(文字列[] 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() {

リターン (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() {

リターン !list.isEmpty();

}

public int size() {

return list.size();

}

public void addItems(GenQueue q) {

while (q.hasItems())

list.addLast(q.dequeue());

}

}

public class GenQueueTest {

公共の静的な無効メイン(文字列[] 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) {

スーパー(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

輸入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型私= 0; 私 < input.length(); 私 ) {

char ch = input.charAt(私);

theStack.push(ch);

}

output = “”;

while (!theStack.isEmpty()) {

char ch = theStack.pop();

output = output + ch;

}

return output;

}

公共の静的な無効メイン(文字列[] 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() {

リターン (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 (この場合, 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;

 

public class Main {

公共の静的な無効メイン(文字列[] argsに) {

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?

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;

インポート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;

のために (int型私= 0; 私 < height; 私 ) {

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

のために (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) {

場合 (image == null)

initialize();

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

}

公共の静的な無効メイン(文字列[] argsに) {

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

javax.swingのインポートします*

public class Main extends JPanel {

文字列[] type = { “Serif”,”SansSerif”};

int型[] 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);

}

}

}

公共の静的な無効メイン(文字列[] 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(真);

}

}

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;

インポート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, と, 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?

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;

金額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);

}

公共の静的な無効メイン(文字列[] argsに) {

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?

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 () 方法. 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型私= 0; 私 < slices.length; 私 ) {

total = slices[私].値;

}

double curValue = 0.0D;

int startAngle = 0;

のために (int型私= 0; 私 < slices.length; 私 ) {

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

int arcAngle = (int型) (slices[私].値 * 360 / total);

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

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

startAngle, arcAngle);

curValue = slices[私].値;

}

}

}

public class Main {

公共の静的な無効メイン(文字列[] 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?

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

javax.swingのインポートします*;

public class Main extends JPanel {

public void paintComponent(Graphics g) {

super.paintComponent(g);

Polygon p = new Polygon();

のために (int型私= 0; 私 < 5; 私 )

p.addPoint((int型)

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

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

g.drawPolygon(p);

}

公共の静的な無効メイン(文字列[] argsに) {

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?

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 {

公共の静的な無効メイン(文字列[] 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 {

公共の静的な無効メイン(文字列[] argsに) throws Exception{

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

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 {

公共の静的な無効メイン(文字列[] argsに) throws Exception{

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

公共の静的な無効メイン(文字列[] argsに) {

試す {

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

}

キャッチ(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?

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 {

公共の静的な無効メイン(文字列[] argsに) throws Exception{

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

Connection con = DriverManager.getConnection

(“jdbc:derby://ローカルホスト: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 {

公共の静的な無効メイン(文字列[] argsに) throws Exception{

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?

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 {

公共の静的な無効メイン(文字列[] argsに) throws Exception{

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

Connection con = DriverManager.getConnection

(“jdbc:derby://ローカルホスト: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 {

公共の静的な無効メイン(文字列[] argsに) throws Exception{

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

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?

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 {

公共の静的な無効メイン(文字列[] argsに) {

試す {

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

}

キャッチ(ClassNotFoundException e) {

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

}

試す {

Connection con = DriverManager.getConnection

(“jdbc:derby://ローカルホスト: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(“名前”);

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

============================================= ============================================== Amazonで最高のTechAlpine Booksを購入してください,en,電気技師CT栗,en
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share