50 Tub ntxhais Java sib tham thiab cov lus teb

Java interview questions and answers

50 Tub ntxhais Java sib tham thiab cov lus teb

  1. Cas cov cim xeeb yog tswj nyob rau hauv java?

IB: 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. Tus qauv Java nco qauv piav txog synchronization txheej txheem kom paub tseeb tias cov ntaub ntawv kev noj nyiaj txiag tsis muab qhov chaw. Cov kev tswj nram qab no muab ib overview ntawm java nco.

Txawm hais tias, 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. Raws li lwm txoj kev, 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. Muaj inheritances ntau zaum hauv java?

IB: Tsis yog, ntau ncaus no tsis tau java. Interface muaj tau nkag tau rau lub hom phiaj thiab nws twb tau derived ntawm Objective C.

Yog vim li cas rau omitting ntau inheritances los ntawm cov lus Java language feem coob ntawm tus “yooj yim, kwv oriented thiab paub” lub hom phiaj. Ua ib hom lus yooj yim, Java tus creators xav tau ib hom lus uas feem coob developers yuav tuav tsis kim heev. Los ntawd xaus, lawv ua hauj lwm kom tau cov lus zoo ib yam li C tau li (paub zoo) tsis muaj nqa pem C tus tsis txaus siab complexity (yooj yim).

Nyob rau hauv cov designers’ tswvyim, ntau zaus ua teeb meem ntau yam thiab tsis meej pem li nws solves. Li ntawd, lawv hlais ntau inheritances los ntawm cov lus (thaum lawv txiav neeg teb xov tooj overloading). Lub designers’ Kim C kev qhia tau lawv tias muaj ntau yam inheritances cia li tsis tsim nyog lub taub hau.

Xwb, Java tus designers xaiv pub ntau interface interface los ntawm kev siv interfaces, ib lub tswv yim borrowed ntawm Objective C lub protocols. Ntau yam interface interface pub rau ib yam khoom rau inherit ntau ntau hom kev kos npe nrog lub caveat uas cov khoom inheriting yuav tsum siv cov kev phiv cov kev phiv.






  1. Yog dab tsi tsim hom phiaj ntawm java?

IB: Tom qab no yog cov qauv tsim hom phiaj ntawm java programming lus. Java designers muaj accomplished ua hauj lwm los kom cov hom phiaj nyob rau hauv siab.

    • yooj yim
    • Chaw nres nkoj
    • Yam Ntxwv Nkaus
    • txhais lus
    • faib
    • Kev kawm siab
    • Robust
    • Multithreaded
    • ruaj ntseg
    • Dynamic
    • Architecture Neutral

Vim li cas java hu ua distributed?

IB: Java muaj ib txoj kev tsev qiv ntawv uas niaj zaus rau tuav TCP/IP/IP cov protocols xws li HTTP thiab FTP. Li ntawd, Java applications yuav qhib thiab khoom thoob hauv internet ntawm URLs. Lub network programming siv java muaj zog thiab yooj yim rau siv. Li ntawd, java hu ua distributed.

Qhov xwm ntawm Java yeej ntsaws ci thaum tag nrho nrog nws hoob kawm dynamic loading capabilities. ua ke, Cov nta kom nws tau ib tug neeg txhais lus Java mus download thiab khiav tawm hauv internet. Qhov no yog li cas thaum ib Web browser downloads thiab sau ib kua txiv Java applet, Piv txwv. Scenarios yuav nyuab dua qhov no, Txawm li cas los. Xav txog tej yam ib txuj kev nyuaj-tawm lo lus sau hauv Java. Thaum twg qhov kev pab cuam no yog kom muab tej ntaub ntawv uas nws twb yeej tsis ces yuav tsum tau ces yuav tsum tau ua ntej, Nws yuav dynamically download ib hoob kawm los ntawm lub network uas yuav parse cov ntaub ntawv, thiab ces dynamically download lwm hoob kawm (tej zaum ib Java “taum”) uas yuav tso saib tau cov ntaub ntawv nyob rau hauv ib cov ntaub ntawv compound. Ib qhov kev pab cuam li no siv faib cov chaw muab kev pab rau lub network rau dynamically loj hlob thiab pab kom cov kev xav tau ntawm nws cov neeg siv.

  1. Vim li cas java hu ua architecture neutral?

IB: Java compiler generates ib bytecode qhia uas yog ywj siab ntawm lub computer architecture. Lub bytecode yog tsim los ua ob yooj yim rau txhais lus rau tej lub tshuab thiab yooj yim txhais ua cuaj cav tov rau hauv lub cav tov. Cov lus nram qab no qhia tau hais tias cov lus nthuav qhia li cas nws tej hauj lwm.

  1. Vim li cas java enabled browser yuav tsum tau khiav ib cov kua?

IB: Kua yog ib qhov kev pab cuam java uas ua haujlwm rau ib lub web sab. Li ntawd, tus browser yuav tsum muaj lub peev xwm txhais tau cov bytecode thiab ua nws ua hauj lwm. Yog vim li cas java enabled browser yuav tsum khiav ib lub kua embedded nyob rau hauv ib lub web sab. Ua tau tus browser muaj cov JVM inbuilt uas yuav pab txhais cov code thiab qhia cov zis.

  1. Koj txhais li cas los ntawm 'Java yog ib hom lus typed nruab nrab'?

IB: Java yog xav typed txhais tau hais tias txhua yam variable hauv java yuav tsum muaj ib hom. Muaj ntau yim txheej xwm rau Java. Plaub leeg muaj integer ntau hom thiab ob yog floating-taw tes ntau hom. Ib tug yog cov ua cim char, siv rau cov cim hauv lub Unicode encoding thiab ib tug yog ib hom Boolean rau qhov tseem ceeb.

  1. Li cas kuv/O yog tswj nyob rau hauv java?

IB: Nyob rau hauv java I/O nruab nrab yog input thiab tso zis kwj. Streams siv los yog sau ntawv mus rau li ntaub ntawv xws li tes hauj lwm los yog network los yog console. Java.io pob khoom rau kuv/O chav kawm ntawv rau manipulate streams. Qhov pob nyiaj them yug ob hom ntawm streams – binary streams uas kov cov ntaub ntawv binary thiab cov ua cim streams uas kov cov ua cim. InputStream thiab OutputStream muaj siab interfaces rau manipulating binary streams. Nyeem thiab txawj sau ntawv muaj kev cuam tshuam rau manipulating cim streams.

Cov nram qab no qhia tau hais tias txoj kev sib raug zoo ntawm cov IO chav kawm ntawv nyob rau hauv tshooj no

  1. Li cas yog buffered kwj txhim khu kev kawm nyob rau hauv java?

IB: Lub neej ntawd tus cwj pwm ntawm ib kwj yog nyeem los yog sau ib lub sij hawm. Qhov no ua rau kuv/O kev kawm vim hais tias nws yuav siv sij hawm ntau nyeem/sau ntawv los ntawm kev koom ua ke thaum soj ntsuam nrog cov ntaub ntawv loj loj ntawm cov ntaub ntawv. Java I/O muab Buffered streams rau override no los ntawm cov cwj pwm uas tsim nyog. Koj yuav tsum tau siv Buffered streams (BufferedInputream thiab BufferedOutStream) buffer cov ntaub ntawv thiab ces nyeem/sau ntawv uas muab kev kawm zoo. Koj yuav tsum to taub txog txoj kev vim tus cwj pwm coj thiab ua li ntawd.

Daim duab nram qab no qhia li cas buffered streams divert cov ntaub ntawv ntws.

  1. Yuav ua li cas koj ntsuas kev kawm ntawm tus cwj pwm coj thiab buffering rau cov ntaub ntawv nyeem ntawv?

IB: Cov nram qab no snippet yuav siv cov ntaub ntawv zoo sib xws thiab sau ntawv siv cov nyeem ntawv thiab buffered nyeem ntawv. Thiab ces nws yuav tso saib lub sij hawm noj los ntawm ob leeg. Kev ntsuam xyuas qhov chaws no cia cov ntaub ntawv nyob rau hauv lawv cov ntaub ntawv raws li qhia hauv qab no.

 

pob khoom com.performance.io;

 

ntshuam java.io.*;

Pej xeem hoob kawm IOTest {

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args){

IOTest io = tshiab IOTest();

sim{

Pib ntev = System.tam sim no();

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

Kawg endtime = System.tam sim no();

System.out.println(“Lub sij hawm noj nyeem ntawv thiab sau ntawv siv behaviour : ”

+ (kawg – pib) + ” milli vib nas” );

 

System startime = System.tam sim no();

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

Endtime1 = System.tam sim no();

System.out.println(“Lub sij hawm noj rau nyeem ntawv thiab sau ntawv siv buffered streams : ”

+ (kawg – pib) + ” milli vib nas” );

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

}

Pej xeem txheeb cais tawm nyeem(txoj hlua fileFrom, NTAIV) throws IOException{

InputStream hauv = null;

Outputream = null;

sim{

hauv = FileInStream(filefrom);

tawm = Fileoutputream tshiab(ntaub ntawv);

Thaum(tseeb){

nyeem tshwm sim = nyob rau hauv.nyeem();

Yog hais tias(bytedata == -1)

so;

out.Write(nruab nrab);

}

}

ntes(Kos e)

{

e.printStackTrace();

}

thaum kawg{

Yog hais tias(nyob rau hauv != thov)

nyob ze();

Yog hais tias(tawm != thov)

out.close();

}

}

pej xeem txheej txheem nyeem readWriteBuffer(txoj hlua fileFrom, NTAIV) throws IOException{

InputStream inBuffer = null;

Outputream outBuffer = null;

sim{

Inputstream hauv = FileInStream(filefrom);

Inbuffer = tshiab BufferedInStream(nyob rau hauv);

Outputream = tshiab FileoutStream(ntaub ntawv);

outbuffer = tshiab BufferedoutUtstream(tawm);

Thaum(tseeb){

Intedata = inBuffer.nyeem();

Yog hais tias(bytedata == -1)

so;

out.Write(nruab nrab);

}

}

ntes(Kos e)

{

e.printStackTrace();

}

thaum kawg{

Yog hais tias(inBuffer != thov)

inBuffer.ze ntawm();

Yog hais tias(outBuffer != thov)

outBuffer.ze ntawm();

}

}

)

  1. Dab tsi yog collections framework nyob java?

IB: Sau los ua yog ib pawg khoom. nkawm khaws tseg.... Muaj ob hom sau los ua ib collections lawv yog sau thiab Map. Sau hom khoom tuav ib pawg khoom, Nyiam cov npe thiab Cov Txheej Txheem. Tiam sis Map ntaus tuav ib pawg khoom ua tseem ceeb, tus nqi khub xws li HashMap thiab Hashtable. Following diagram shows the entire hierarchy of collections framework.

  1. Yuav ncua ib array tom qab thawj zaug?

IB: Tom qab piv txwv qhia tau hais tias yuav ncua ib array tom qab ntawv los ntawm kev tsim ib array tshiab. Ntawm no yog yeej appending qhov tseem ceeb tshiab rau ib array uas twb muaj lawm. Lub arraycopy() Yuav tsum tau siv kom zoo zoo txwv tsis pub muaj tej qho teeb meem ntawm cov ntaub ntawv uas twb muaj lawm nyob rau hauv cov array uas twb muaj lawm.

pej xeem hoob loj {

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args) {

Txoj hlua[] Npe tshiab = Txoj hlua tshiab[] { “X”, “Y”, “Z” };

Txoj hlua[] ncua = txoj hlua tshiab[5];

ncua[3] = “D”;

ncua[4] = “E”;

System.arraycopy(npe, 0, ncua, 0, npe);

rau (hlua : ncua){

System.out.println(str);

}

}

}

Thiab qhov txheeb xyuas tau yuav ua raws li

X
Y
Z
D
E

  1. Yuav ua li cas (txeeb ib zaug) ib array?

IB: Qhov piv txwv no yuav sau (thawj kauj ruam tag nrho lub ntsiab ntawm cov array hauv ib short) ib array los siv Array... sau (arrayname, tus nqi) txoj kev thiab Array... sau (arrayname, sawv ntxov, xaus, tus nqi) txoj kev Java cov chav kawm ntawv.

ntshuam java.util.*;

Pej xeem hoob kawm Filltest {

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua args[]) {

txajmuag[] = hauv tshiab[6];

Arrays... sau(array, 100);

rau (rau cov menyuam kuv = 0, ncaj nraim...; Kuv < n; i ) {

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

}

System.out.println();

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

rau (rau cov menyuam kuv = 0, ncaj nraim...; Kuv< n; i ) {

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

}

}

}

Yog hais tias koj khiav qhov chaws ces yuav tsum ua raws li cov lus nram qab no.

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








  1. Yuav ua li cas rau ntau ob matrices ntawm dimensions sib txawv?

IB: Tom qab piv txwv qhia multiplication ntawm ob tug rectangular matrices nrog kev pab los ntawm ob tug neeg siv cov kev txhais tau hais tias muaj ntau yam ( rau cov menyuam [] [] ,rau cov menyuam [] []) tujtais(rau cov menyuam [] []).

Pej xeem hoob kawm Matrix{

pej xeem static[][] ntau yam(rau cov menyuam[][] m1, rau cov menyuam[][] m2){

hauv m1rows = m1.ntev;

hauv m1cols = m11[0].ntev;

hauv m2rows = m2.ntev;

hauv m2cols = m2[0].ntev;

Yog hais tias (m1cols != m2rows){

pov tseg Tshiab IllegalgumentargumentExtion(“txheej txheem

ntais ntawv: “+ m1cols + ” != ” + m2rows);

rau cov menyuam[][] tshwmsim = tshiab[m1rows][m2cols];

rau (rau cov menyuam kuv = 0; Kuv< m1rows; i ){

rau (hauv j=0; j< m2cols; j ){

rau (hauv 0=0; k< m1cols; k ){

tshwm[Kuv][j] += m11[Kuv][k] * m2[k][j];

rov qab los;

)

}

}

}

}

/** Print Matrix.

*/

pej xeem txheeb ze mprint(rau cov menyuam[][] ib){

uake = ib leeg ntev;

hauv cov kwvtij = ib tug[0].ntev;

System.out.println(“array[“+nyuj nqaij hloov”][“+muaj xim kasfes”] = {“);

rau (rau cov menyuam kuv = 0; Kuv< nyuj nyoos; i ){

System.out.Print(“{“);

rau (hauv j=0; j< cols; j ){

System.out.Print(” ” + ib[Kuv][j] + “,”);

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

}

}

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

}

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] av){

ntxias[][] ={

{ 3, 2, 3 },

{ 5, 9, 8 },

};

ntxawm[][] ={

{ 4, 7 },

{ 9, 3 },

{ 8, 1 },

};

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

Matrix.mprint(x);

Matrix.mprint(y);

Matrix.mprint(z);

}

}

Tus code qauv yuav tsim cov nram no

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. Yuav ua li cas los merge ob arrays?

IB: Qhov no piv txwv qhia li cas los merge ob arrays mus ua ib zaug xwb array los ntawm daim ntawv teev. pob(array1.aslist(array2) Txoj kev ntawm daim ntawv teev cov hoob kawm thiab Arrays.toString () txoj kev Array hoob kawm. Ceev faj thaum muab ib tug array rau lwm tus. Vim hais tias cov kev siv ntawm lub ntsiab ntawm cov arrays ces yuav muaj sij hawm ntawm cascading nyhuv.

ntshuam java.util.ArrayList;

ntshuam java.util.Arrays;

ntshuam java.util.List;

pej xeem hoob loj {

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua args[]) {

hlua[] = { “IB”, “E”, “Kuv” };

hlua[] = { “O”, “U.S.” };

Sau daim ntawv teev = ArrayList(Arrays.aslist(ib));

sau.addall(Arrays.aslist(b));

Nruas[] c = sau.toArray();

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

}

}

Tus code qauv yuav tsim cov nram no

[IB, E, Kuv, O, U.S.]

  1. Yuav tshawb nrhiav qhov tsawg kawg thiab qhov tsawg kawg yog ib qho array?

IB: Qhov no piv txwv qhia tau hais tias yuav nrhiav qhov tsawg kawg thiab tsawg kawg yog ib qho array uas siv los sau.max () thiab sau los ua kev sib sau los ua luv nqi() Txoj kev coj class. Txawm hais tias muaj lwm txoj kev uas yuav nrhiav tau tus txiv neej thiab qhov tseem ceeb ntawm ib array tab sis no API yog qhov npaum ib tug ua hauj lwm nrog arrays.

ntshuam java.util.Arrays;

import java.util.Collections;

pej xeem hoob loj {

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args) {

Integer[] pes tsawg tus zauv = { 8, 2, 7, 1, 4, 9, 5};

hauv mint = (rau cov menyuam) Sau los ua lug luv nqi(Arrays.aslist(zauv));

nyob rau hauv max = (rau cov menyuam) Sau los.max(Arrays.aslist(zauv));

System.out.println(“Tsawg tus nab npawb: ” + mintsis);

System.out.println(“Naj npawb: ” + max);

}

}

Qhov txheeb xyuas tau yuav ua raws li cov lus qhia

Tsawg tus nab npawb: 1

Naj npawb: 9

  1. Yuav ua li cas kom rov qab muaj arraylist?

IB: Collections API muaj ib txoj kev uas hu ua nraud (Arraylist). Ces qhov no yog siv los rov qab muab ib daim ntawv teev array. Cov neeg ua hauj lwm hauv qab no yuav qhia koj siv cov API los ua qhov chaw ua hauj lwm.

ntshuam java.util.ArrayList;

import java.util.Collections;

pej xeem hoob loj {

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args) {

Arraylist arraylist = tshiab ArrayList();

arrayList.ntxiv(“IB”);

arrayList.ntxiv(“B”);

arrayList.ntxiv(“C”);

arrayList.ntxiv(“D”);

arrayList.ntxiv(“E”);

System.out.println(“Ua ntej yuav rov qab muab kev txiav txim: ” + txheej txheem);

Sau los...(txheej txheem);

System.out.println(“Tom qab reverse order: ” + txheej txheem);

}

}

Ntawm cov piv txwv saum toj no yuav ua raws li.

Ua ntej yuav rov qab muab kev txiav txim: [IB, B, C, D, E]

Tom qab reverse order: [E, D, C, B, IB]

  1. Yuav ua li cas thiaj tsim muaj array thiab insert ib lub caij nyob rau hauv nws?

IB: Cov piv txwv qhia tau hais tias yuav siv tsawm tsawv thiab () Txoj kev thiab neeg siv cov kev txhais tau hais tias txoj kev insertlement () ua kom tiav cov hauj lwm. tus tsi () Txoj kev siv los tsawm tus array ntawm tsis zoo rau tus nqi ces tus neeg insertomized insertelement () Txoj kev siv ntxiv mus ntxiv rau hauv nws.

ntshuam java.util.Arrays;

Pej xeem hoob kawm MainClass {

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua args[]) throws kos {

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

Arrays.sort(array);

thawj xib fwb(“Array Sorted array”, array);

Index = Arrays.binarySech(array, 1);

System.out.println(“Tsis nrhiav 1 @ ”

+ Performance Index);

Tshiab IntIndex = -Index – 1;

array = insertlement(array, 1, TshiabIndex);

thawj xib fwb(“Nrog 1 ntxiv”, array);

}

qhov tseeb static void printArray(Txoj hlua xov, txajmuag[]) {

System.out.println(xov

+ “: [ntev: ” + txheej txheem.ntev + “]”);

rau (rau cov menyuam kuv = 0; Kuv < txheej txheem.ntev; i ) {

Yog hais tias (Kuv != 0){

System.out.Print(“, “);

}

System.out.Print(array[Kuv]);

}

System.out.println();

}

ntiav[] kev koom tes(cheeb tsam[],

kev xaiv tsa, index) {

ntev npaum li cas = ntev;

kev ntxub ntxaug[] = hauv tshiab[ntev + 1];

System.arraycopy(xeebtxwv, 0, kev ntxub ntxaug, 0, Performance Index);

kev ntxub ntxaug[Performance Index] = ib lub caij hais txog kev xaiv tsa;

System.arraycopy(xeebtxwv, Performance Index, kev ntxub ntxaug, Performance Index

+ 1, ntev – Performance Index);

rho tawm;

}

}

  1. Yuav ua li cas thiaj muaj array thiab nrhiav ib lub caij rau nws?

IB: Cov piv txwv qhia tau hais tias yuav siv tsawm tsawv thiab () thiab binarySecharch () txoj kev ua kom tiav cov hauj lwm. Tus neeg siv txhais txoj kev printary () muab cov tso zis tso zis.

chaw nres nkoj java.Arrays;

Pej xeem hoob kawm MainClass {

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua args[]) throws kos {

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

Arrays.sort(array);

thawj xib fwb(“Array Sorted array”, array);

Index = Arrays.binarySech(array, 2);

System.out.println(“Nrhiav tau 2 @ ” + Performance Index);

}

qhov tseeb static void printArray(Txoj hlua xov, txajmuag[]) {

System.out.println(xov

+ “: [ntev: ” + txheej txheem.ntev + “]”);

rau (rau cov menyuam kuv = 0; Kuv < txheej txheem.ntev; i ) {

Yog hais tias(Kuv != 0){

System.out.Print(“, “);

}

System.out.Print(array[Kuv]);

}

System.out.println();

}

}

Yog hais tias koj khiav qhov chaw ntawd ces daim ntawv thov kev pab yuav qhia qhov tseeb raws li hauv qab no.

Array Sorted array: [ntev: 10]

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

Nrhiav tau 2 @ 5








  1. Yuav tsim ib tug banner siv kua?

IB: Cov piv txwv nram qab no tau siv cov hoob kawm thread thiab Graphics kawm kom zaub tus banner. Lub functionality ntawm cov thread yog muab ib cov nyhuv ntawm animation rau tus banner. Saib lub tso zis lub kua yuav tsum tau khiav hauv ib browser uas txhawb kua.

iimport java.awt.*;

chaw nres nkoj nyoog.*;

Pej xeem hoob kawm SampleBanner extends kua

DVR Runnable{

Kaj lug = “Qhov no yog ib tug yooj yim Banner “;

Xov ;

nkoj ntshiv;

pej xeem zam() {

setBackground(txho tshauv.);

setForeground(daj lug...);

}

pej xeem pib() {

= tshiab Thread(no);

b = bal false;

pib();

}

pej xeem qhib () {

nplua;

rau( ; ; ) {

sim {

khaws cia();

Thread.sleep(250);

= chr.charat(0);

khau ntaus nplawm(1, ntev());

qauv = + xubnt;

}

ntes(InterruptedException e) {}

}

}

pej xeem tsis txhob mob(Nraaj g) {

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

g.g.setcolor(daj lug...);

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

g.g.setcolor(liab xim liab..);

g.g.drawString(str, 1, 150);

}

}

  1. Yuav ua li cas zaub mov ib moos siv ib lub kua?

IB: Piv txwv muaj siv txoj hlua chav kawm ntawv thiab Calendar chav kawm ntawv rau zaub cov kua clock. Calendar hoob kawm muab tus nqi ntawm 'Teev', 'Feeb' thiab 'thib ob'.

import java.awt.*;

chaw nres nkoj nyoog.*;

chaw nres nkoj nyoog.*;

import java.awt.*;

ntshuam java.util.*;

Pej xeem hoob kawm ClockAplet extends kua dluab Runnable{

Xov,ntsaws;

pej xeem pib(){

= tshiab Thread(no);

pib();

}

pej xeem qhib(){

t1 = Thread.tam sim no();

Thaum(t1 = t = t=){

khaws cia();

sim{

pw tsaug zog(1000);

}

ntes(InterruptedException e){}

}

}

pej xeem tsis txhob mob(Nraaj g){

Calendar cal = tshiab GregorianCandar();

Txoj hlua xuab moos = Txoj hlua valuef(twj ywm..(COV SIJ HAWM ZOV ME NYUAM));

Txoj hlua feeb = Stringing.valuef(twj ywm..(Qhov tseeb...));

Txoj hlua thib ob = txoj hlua..(twj ywm..(Thib ob...));

g.g.drawString(Teev + “:” + feeb + “:” + thib ob, 20, 30);

}

}

Ntxiv dua thiab koj yuav tsum khiav lub kua hauv ib browser los yog kua saib xyuas cov zis.

  1. Yuav tsim ib qho kev tshwm sim mloog hauv kua?

IB: Tom qab piv txwv li cov qauv qhia li cas yuav tsim ib kua yooj yim muaj khawm nyees khawm ntxiv & subtract ob tug lej. Txoj kev siv ntawm no yog addActionener () mloog ib qho kev tshwm sim(nyem rau ib khawm) & Khawm() tsim ib lub pob khawm.

chaw nres nkoj nyoog.*;
import java.awt.event.*;
import java.awt.*;

Pej xeem hoob kawm EventListeners extends kua

Txhim kho ActionListener{

Textarea txtarea;

Txoj hlua ntxiv, rho tawm;

rau cov menyuam kuv = 10, j = j= 20, lub caij ntuj sov =0,00;

pej xeem zam(){

txtarea = tshiab Textarea(10,20);

txtarea... setEditable(tsis tseeb);

ntxiv(txtArea,”Center”);

Khawm b = Button tshiab(“Ntxiv”);

Khawm c = Button tshiab(“rho tawm”);

b.addActionListener(no);

c.addActionener(no);

ntxiv(b);

ntxiv(c);

}

pej xeem yuav tsum tsis txhob ua(Kev Tshwm Sim){

Summ = kuv + j;

txtarea..setTex(“”);

txtarea.append(“Kuv = “+ Kuv + “\t” + “j = j= ” + j + “\n”);

Khawm tau qhov twg los = (Khawm)e.getsource();

Yog hais tias(qhov twg los...() == “Ntxiv”){

txtarea.append(“caij ntuj sov : ” + caij ntuj sov + “\n”);

}

Yog hais tias(Kuv >j){

Sub = kuv – j;

}

ntxiv{

Sub = j – Kuv;

}

Yog hais tias(qhov twg los...() == “rho tawm”){

txtarea.append(“subs : ” + subs + “\n”);

}

}

}

  1. Yuav ua li cas qhib ib qhov rais tshiab siv kua?

IB: Qhov no piv txwv qhia li cas qhib ib webpage ntawm ib lub kua hauv lub qhov rais tshiab siv showDocument() txoj kev thib ob sib cav li “_blank” .

chaw nres nkoj nyoog.*;

import java.awt.*;

import java.net.*;

import java.awt.event.*;

Pej xeem kawm testURL_NewWindow ncua kua

Txhim kho ActionListener{

pej xeem zam(){

Hlua link_Text = “kaj siab lug”;

Khawm b = Button tshiab(link_Text);

b.addActionListener(no);

ntxiv(b);

}

pej xeem yuav tsum tsis txhob ua(Tshwm sim ntev){

Khawm tau qhov twg los = (Khawm)ae.getsource();

Kev txuas = “http://www.”+qhov twg los...()+”.com”;

sim {

Kua AppletContext ib = getapletcontex();

URL url = new URL(txuas);

ib tug showDocument (showDocument)(url,”_blank”);

}

ntes (Malformed MalformedLCEPtion e){

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

}

}

}

  1. Yuav nyeem ib daim ntawv siv cov kua?

IB: Cov chaws hauv qab no snippet qha tau yuav nyeem ib daim ntawv siv ib cov kua siv kua qhib() txoj kev URL. Muaj ntau txoj kev nyeem ib kwj xws li buffered kwj, txheej buffered stream etc. Ntawm no peb tau siv buffered kwj dej nyeem cov ntaub ntawv.

chaw nres nkoj nyoog.*;

import java.awt.*;

ntshuam java.io.*;

import java.net.*;

 

Pej xeem hoob nyeem readFileapplet extends kua{

Kauj Ruam FileToRead = “kev ntsuam xyuas.txt”;

StringBuffer stringBuffer;

Textarea txtarea;

Nraaj g;

pej xeem zam(){

txtarea = tshiab Textarea(100, 100);

txtarea... setEditable(tsis tseeb);

ntxiv(txtArea, “Center”);

Txoj hlua prHtml = no.getParameter(“ntaub ntawv”);

Yog hais tias (prHtm != thov) Ntaub ntawv fileToRead = txoj hlua tshiab(prHtm);

nyeem ntawv();

}

pej xeem tsis txhob nyeem ntawv(){

txoj kab ntxwv;

URL url = nuj;

sim{

url = URL(tau txaiscodebase(), ntaub ntawv);

}

ntes(Malformed MalformedLCEPtion e){}

sim{

InputStream hauv = url.openStream();

BufferedReader bf = BufferedReader tshiab

(InputStreamReader tshiab(nyob rau hauv));

khoom = tshiab StringBuffer();

Thaum((= nyeem cov kab txheej txheem."()) != thov){

txawj txheem.append(kab + “\n”);

}

txtarea.append(“Tsev Neeg Lub Npe : ” + ntaub ntawv + “\n”);

txtarea.append(kauj ruam.toString());

}

ntes(IOException e){

e.printStackTrace();

}

}

}








  1. Yuav ua li cas los tsim shapes siv kua?

IB: Qhov no piv txwv qhia li cas los tsim ib tug kua uas yuav muaj ib txoj kab, ib qho Oval & Ib Rectangle siv drawline(), twv txiaj() thiab kos() txoj kev Graphics class. Nyob rau hauv java Graphics hoob kawm yog lug siv los kos thiab cov neeg siv nyob rau hauv daim qauv, puas tsuaj.

chaw nres nkoj nyoog.*;

import java.awt.*;

 

Pej xeem hoob kawm Shapes extends kua{

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

pej xeem tsis txhob mob(Nraaj g){

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

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

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

}

}

Cov chaws saum toj no yuav ua rau cov nram qab no nyob rau hauv lub java enabled web browse

ib txoj kab, qee zaum & Ib Rectangle yuav tau twv hauv lub browser.

  1. Yuav siv cov kua hauv JAVA?

IB: Viav vias yog ib qho tseem ceeb tivthaiv hauv java los ua UI interfaces. Cov viav vias no kuj siv hauv cov kua los ua cov neeg siv interface. Tom qab qauv qhia li cas yuav siv cov kua hauv JAVA los siv ActionListener & yog tsim JLabels.

import javax.swing.*;

chaw nres nkoj nyoog.*;

import java.awt.*;

import java.awt.event.*;

Pej xeem hoob kawm SApplet extends kua siv ActionListener {

TextField input,tso zis;

Daim ntawv lo lub hwj huam, daim ntawv lo;

Khawm 11;

Jlabel lb;

hauv nruab nrab, zaum = 0;

pej xeem zam(){

daim ntawv lo tshiab = tshiab(“naj npawb : “);

ntxiv(daim ntawv lo);

ntawv lo phem.setBackground(daj lug...);

ntawv lo phem.setForeground(magenta.magenta);

input = TextField(5);

ntxiv(tswv yim);

daim ntawv lo tshiab = tshiab(“caij ntuj sov : “);

ntxiv(daim ntawv lo);

label2.setBackground(daj lug...);

label2.setForeground(magenta.magenta);

tso zis = TextField(20);

ntxiv(tso zis);

b1 = khawm tshiab khawm(“Ntxiv”);

ntxiv(b1);

b1.addActionListener(no);

lbl = JLabel(“Piv txwv kua. “);

ntxiv(lws);

setBackground(daj lug...);

}

pej xeem yuav tsum tsis txhob ua(Tshwm sim ntev){

sim{

= Integer.parseint(tsis txaus siab...());

Lub caij ntuj sov number;

txheej txheem(“”);

setTex(Integer.toString(caij ntuj sov));

lblb.setForeground(xiav.xiav);

lbl.setTex(“Tso zis rau ob phau ntawv nyeem : ”

+ tso zis.taub hau());

}

ntes(NumberFormatception e){

lblb.setForeground(liab xim liab..);

lbl.setTex(“Invalid Entry!”);

}

}

}

  1. Yuav sau ib daim ntawv uas siv kua?

IB: Nyob rau hauv cov piv txwv java text tau siv los sau tus neeg siv input. Tom qab nkag mus rau hauv lub input nws twb tau sau ntawv nyob rau hauv ib cov ntaub ntawv nyob rau hauv lawv cov ntaub ntawv hauv zos. Cov ntaub ntawv () tsim kom muaj cov ntaub ntawv.

ntshuam java.io.*;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import java.applet.kua;

import java.net.*;

Pej xeem hoob kawm WriteFile extends kua{

Button sau = khawm tshiab khawm(“Sau WriteFile (WriteToFile)”);

Daim ntawv lo rau ntawm daim ntawv lo tshiab =(“Nkag mus rau hauv lub npe:”);

TextField text = tshiab TextField(20);

Daim ntawv lo rau ntawm daim ntawv lo rau lub hwjchim tshiab(“Sau koj phau ntawv:”);

TextArea thaj tsam = tshiab Textarea(10,20);

pej xeem zam(){

ntxiv(daim ntawv lo);

ntawv lo phem.setBackground(xim lightray);

ntxiv(ntawv nyeem);

ntxiv(daim ntawv lo);

label2.setBackground(xim lightray);

ntxiv(Koog);

ntxiv(sau ntawv,BorderLayout CENTER);

sau.addAlistener(Actionlistener tshiab (){

pej xeem yuav tsum tsis txhob ua(Kev Tshwm Sim){

Sau ntawv tshiab();

}

}

);

}

Pej xeem cov hoob kawm {

Sau Ntawv Sau(){

sim {

Txoj hlua = text.getText();

Yog hais tias(sib npaug(“”)){

JoptionPane.showMesDiaTagesDialog(thov,

“Thov sau daim ntawv npe!”);

phau ntawv... thov kom muaj kev sib tham();

}

ntxiv{

Ntaub ntawv thov = Ntaub ntawv tshiab(str);

Yog hais tias(f.pheej tshwm sim()){

BufferedWriter tawm = tshiab

BufferedWriter(tshiab FileWriter(f,tseeb));

Yog hais tias(thaj chaw().qhov sib npaug(“”)){

JoptionPane.showMesDiaTagesDialog

(thov,”Thov sau koj phau ntawv!”);

thov...();

}

ntxiv{

out.Write(thaj chaw());

Yog hais tias(f.canwrite()){

JoptionPane.showMesDiaTagesDialog(thov,

“Cov ntawv nyeem yog sau rau hauv “+str);

phau ntawv nyeem.setTex(“”);

cheeb tsam(“”);

phau ntawv... thov kom muaj kev sib tham();

}

ntxiv{

JoptionPane.showMesDiaTagesDialog(thov,

“Phau ntawv tsis sau ntawv “+str);

}

out.close();

}

}

ntxiv{

JoptionPane.showMesDiaTagesDialog

(thov,”Cov ntaub ntawv tsis muaj nyob!”);

phau ntawv nyeem.setTex(“”);

phau ntawv... thov kom muaj kev sib tham();

}

}

}

ntes(Tshwj x x){

x.printStackTrace();

}

}

}

}

  1. Yuav ua li cas thiaj sau tau cov zauv npaum li cas?

IB: Tom qab piv txwv qhia li cas ntxiv ua ntej tooj ntawm kev siv lub tswvyim ntawm teev tseg. Ntawm no cov txheej txheem static class siv los tuav cov zauv. Cov neeg muas zaub stackAddition () Txoj kev siv los ntxiv cov zauv ntxiv rau hauv lub tsho tiaj.

ntshuam java.io.IOException;

Pej xeem hoob kawm AdditionStack {

txheej;

txheeb cais;

Txheej Txheem Stack;

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args) throws IOException {

naj npawb 50;

tshaaj plab();

System.out.println(“Lub caij ntuj sov.” + ib qho);

}

Pej xeem static void stackAddition() {

Lub plawv = Tshoj tshiab(10000);

ib yam twg = 0;

Thaum (num > 0)

{

Xovtooj khwb rho tawm(num);

–num;

}

Thaum (!Lub khwb rhuav tag())

{

Tshiab int newN = lub pop.pop();

ib tug tshiab;

}

}

}

Hoob Kawm {

qhov hauv maxSize;

ntiav[] cov ntaub ntawv;

ntiav;

Pej xeem Stack(nyob rau hauv) {

maxSize = s;

cov ntaub ntawv = tshiab[maxSize];

nyob saum toj kawg nka -1;

}

pej xeem tsis txhob raug thawb(hauv nkuaj) {

cov ntaub ntawv[++saum toj kawg n] = p;

}

pej xeem nyob hauv pop() {

cov ntaub ntawv rov qab[saum toj kawg n–];

}

pej xeem() {

cov ntaub ntawv rov qab[saum toj kawg n];

}

Pej xeem boolean ntxias() {

rov qab mus (sab saum toj = -1);

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no.

Lub caij ntuj sov =1225

  1. Yuav ua li cas thiaj tau tus thawj thiab lub caij kawg ntawm ib daim ntawv txuas?

IB: Tom qab piv txwv qhia li cas mus ua ntej thiab lub caij kawg ntawm ib daim ntawv txuas nrog rau kev pab los ntawm linkedlistname.getFirst() thiab linkedlistname.getLast() Hoob Kawm LinkedList. Tag nrho cov tuam txhab/queue/queue/deque haujlwm yuav yog yooj yim so tej ntsiab lus uas teev tseg. Tsuav yog nyob ntawm no feem ntau rau convenience, tab sis yog lawv yuav khiav ib nyuag sai dua li daim ntawv teev cov haujlwm.

chaw nres nkoj java..util.Linkedlist;

pej xeem hoob loj {

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args) {

Linkedlist = tshiab Linkedlist();

lList.ntxiv(“100”);

lList.ntxiv(“200”);

lList.ntxiv(“300”);

lList.ntxiv(“400”);

lList.ntxiv(“500”);

System.out.println(“Thawj lub caij uas LinkedList yog :

” + lList.getFirst());

System.out.println(“Lub caij kawg ntawm LinkedList yog :

” + lList.getlast());

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no.

Thawj lub caij uas LinkedList yog: 100

Lub caij kawg ntawm LinkedList yog: 500

  1. Yuav ntxiv ib lub caij thaum xub thiab kawg txoj hauj lwm ntawm ib daim ntawv txuas?

IB: Tom qab piv txwv qhia li cas ntxiv rau ib lub caij thaum thawj thiab kawg txoj hauj lwm ntawm ib daim ntawv txuas los ntawm kev siv addFirst() thiab yus tus kheej() Txoj kev txuas ntawm daim ntawv teev Cov Hoob Kawm.

chaw nres nkoj java..util.Linkedlist;

pej xeem hoob loj {

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args) {

Linkedlist = tshiab Linkedlist();

lList.ntxiv(“1”);

lList.ntxiv(“2”);

lList.ntxiv(“3”);

lList.ntxiv(“4”);

lList.ntxiv(“5”);

System.out.println(llist);

lList.addFirst(“0”);

System.out.println(llist);

lList.addlast(“6”);

System.out.println(llist);

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no.

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?

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

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

Lub plawv = Tshoj tshiab(stackSize);

}

 

public String doTrans() {

rau (rau cov menyuam j = 0; j < input.length(); j ) {

char ch = input.charAt(j);

hloov (xubnt) {

case ‘+’:

case ‘-‘:

gotOper(xubnt, 1);

so;

case ‘*’:

case ‘/’:

gotOper(xubnt, 2);

so;

case ‘(‘:

Xovtooj khwb rho tawm(xubnt);

so;

case ‘)’:

gotParen(xubnt);

so;

vim:

output = output + xubnt;

so;

}

}

Thaum (!Lub khwb rhuav tag()) {

output = output + theStack.pop();

}

System.out.println(tso zis);

return output;

}

 

public void gotOper(char opThis, int prec1) {

 

Thaum (!Lub khwb rhuav tag()) {

char opTop = theStack.pop();

Yog hais tias (opTop == ‘(‘) {

Xovtooj khwb rho tawm(opTop);

so;

}

ntxiv {

int prec2;

Yog hais tias (opTop == ‘+’ || opTop == ‘-‘)

prec2 = 1;

ntxiv

prec2 = 2;

Yog hais tias (prec2 < prec1)

{

Xovtooj khwb rho tawm(opTop);

so;

} ntxiv

output = output + opTop;

}

}

Xovtooj khwb rho tawm(opThis);

}

 

public void gotParen(nplua){

Thaum (!Lub khwb rhuav tag()) {

char chx = theStack.pop();

Yog hais tias (chx == ‘(‘)

so;

ntxiv

output = output + chx;

}

}

 

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args) throws IOException {

 

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

String output;

InToPost theTrans = new InToPost(tswv yim);

output = theTrans.doTrans();

System.out.println(“Postfix is ” + tso zis + 'n');

}

Hoob Kawm {

 

qhov hauv maxSize;

private char[] stackArray;

ntiav;

 

Pej xeem Stack(int max) {

maxSize = max;

stackArray = new char[maxSize];

nyob saum toj kawg nka -1;

}

 

pej xeem tsis txhob raug thawb(char j) {

stackArray[++saum toj kawg n] = j;

}

 

public char pop() {

return stackArray[saum toj kawg n–];

}

 

public char peek() {

return stackArray[saum toj kawg n];

}

 

Pej xeem boolean ntxias() {

rov qab mus (sab saum toj = -1);

}

}

 

}

 

Cov chaws saum toj no yuav ua tau cov nram qab no.

124*5/+7-36/+

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








  1. How to implement Queue?

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

chaw nres nkoj java..util.Linkedlist;

class GenQueue {

private LinkedList list = new LinkedList();

public void enqueue(E item) {

list.addLast(yam khoom);

}

public E dequeue() {

return list.poll();

}

public boolean hasItems() {

rov qab mus !list.isEmpty();

}

public int size() {

return list.size();

}

public void addItems(GenQueue q) {

Thaum (q.hasItems())

list.addLast(q.dequeue());

}

}

public class GenQueueTest {

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] 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 employeesnames are:”);

 

Thaum (empList.hasItems()) {

Employee emp = empList.dequeue();

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

}

}

}

kawm ua hauj lwm {

` public String lastName;

public String firstName;

neeg ua hauj lwm rau pej xeem() {

}

neeg ua hauj lwm rau pej xeem(String last, String first) {

this.lastName = last;

 

this.firstName = first;

}

Pej xeem stringing torsting() {

rov qab los ua ntej + ” ” + lastName;

}

}

class HourlyEmployee extends Employee {

public double hourlyRate;

 

public HourlyEmployee(String last, String first) {

super(last, thawj);

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no.

The employeesnames are:

T D

G B

F S

  1. How to reverse a string using stack?

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

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

 

rau (rau cov menyuam kuv = 0; Kuv < input.length(); i ) {

char ch = input.charAt(Kuv);

Xovtooj khwb rho tawm(xubnt);

}

output = “”;

Thaum (!Lub khwb rhuav tag()) {

char ch = theStack.pop();

output = output + xubnt;

}

return output;

}

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args) throws IOException {

String input =Java Source and Support”;

String output;

StringReverserThroughStack theReverser =

new StringReverserThroughStack(tswv yim);

output = theReverser.doRev();

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

}

Hoob Kawm {

qhov hauv maxSize;

private char[] stackArray;

ntiav;

 

Pej xeem Stack(int max) {

maxSize = max;

stackArray = new char[maxSize];

nyob saum toj kawg nka -1;

}

pej xeem tsis txhob raug thawb(char j) {

stackArray[++saum toj kawg n] = j;

}

public char pop() {

return stackArray[saum toj kawg n–];

}

public char peek() {

return stackArray[saum toj kawg n];

}

Pej xeem boolean ntxias() {

rov qab mus (sab saum toj = -1);

}

 

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no.

JavaStringReversal

Reversed:lasreveRgnirtSavaJ

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

IB: Following example demonstrates how to check if antialiasing is turned on or not using RenderingHints Class. Aliasing occurs when a signal (qhov no, 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) tshuab.

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.RenderingHints;

import javax.swing.JComponent;

import javax.swing.JFrame;

 

pej xeem hoob loj {

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args) {

JFrame frame = new JFrame();

frame.add(new MyComponent());

frame.setSize(300, 300);

frame.setVisible(tseeb);

}

}

class MyComponent extends JComponent {

pej xeem tsis txhob mob(Nraaj 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);

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no.

False

False

False

  1. How to display colors in a frame?

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

import java.awt.Graphics;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.awt.image.BufferedImage;

import javax.swing.JComponent;

import javax.swing.JFrame;

 

public class Main extends JComponent {

BufferedImage image;

pej xeem tsis muaj dabtsis initialize() {

int width = getSize().width;

int height = getSize().qhov siab;

rau cov menyuam[] cov ntaub ntawv = tshiab[width * qhov siab];

int index = 0;

rau (rau cov menyuam kuv = 0; Kuv < qhov siab; i ) {

int red = (Kuv * 255) / (qhov siab – 1);

rau (rau cov menyuam j = 0; j < width; j ) {

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

int blue = 128;

cov ntaub ntawv[index++] = (liab < < 16) | (ntsuab < < 8) | blue;

}

}

image = new BufferedImage

(width, qhov siab, BufferedImage.TYPE_INT_RGB);

image.setRGB(0, 0, width, qhov siab, cov ntaub ntawv, 0, width);

}

pej xeem tsis txhob mob(Nraaj g) {

Yog hais tias (image == null)

initialize();

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

}

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args) {

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

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

f.setSize(300, 300);

f.setLocation(100, 100);

f.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.Exit(0);

}

});

f.setVisible(tseeb);

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no.

Displays all the colours in a frame.

  1. What is threading in java?

IB: A Java program can contain many threads, all of which may be created without the explicit knowledge of the developer. Tamsim no, 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(), thiab lwm yam.) 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?

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

import java.awt.*;

import java.awt.event.*

import javax.swing.*

public class Main extends JPanel {

Txoj hlua[] yam = { “Serif”,”SansSerif”};

rau cov menyuam[] styles = { Font.PLAIN, Font.ITALIC, Font.BOLD,

Font.ITALIC + Font.BOLD };

Txoj hlua[] stylenames =

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

pej xeem tsis txhob mob(Nraaj g) {

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

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

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

g.setFont(font);

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

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

}

}

}

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] ib) {

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

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no.

Different font names are displayed in a frame.

  1. How to draw a line using GUI?

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

 

import java.awt.*;

import java.awt.event.*;

import java.awt.geom.Line2D;

import javax.swing.JApplet;

import javax.swing.JFrame;

 

public class Main extends JApplet {

pej xeem zam() {

setBackground(Color.white);

setForeground(Color.white);

}

pej xeem tsis txhob mob(Nraaj g) {

Graphics2D g2 = (Graphics2D) g;

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

g2.setPaint(txho tshauv.);

int x = 5;

int y = 7;

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

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

}

pej xeem tsis muaj dabtsis loj zoo li qub(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().ntxiv(“Center”, applet);

applet.init();

f.pack();

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

f.setVisible(tseeb);

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no.

Line is displayed in a frame.








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

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

import java.awt.*;

import java.awt.font.FontRenderContext;

import java.awt.geom.Rectangle2D;

import javax.swing.JFrame;

import javax.swing.JPanel;

public class Main extends JPanel {

pej xeem tsis txhob mob(Nraaj 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, “thiab”, 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 = (ntab) bounds.getWidth();

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

}

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args) {

JFrame f = new JFrame();

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

f.setSize(450, 350);

f.setVisible(tseeb);

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no.

JAVA and J2EE displayed in a new Frame.

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

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

import java.awt.Color;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Rectangle;

import javax.swing.JComponent;

import javax.swing.JFrame;

class Slice {

double value;

Color color;

public Slice(double value, Color color) {

this.value = value;

this.color = color;

}

}

class MyComponent extends JComponent {

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

new Slice(33, Color.green),

new Slice(20, daj lug...), new Slice(15, liab xim liab..) };

MyComponent() {}

pej xeem tsis txhob mob(Nraaj g) {

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

}

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

double total = 0.0D;

rau (rau cov menyuam kuv = 0; Kuv < slices.length; i ) {

total += slices[Kuv].tus nqi;

}

double curValue = 0.0D;

int startAngle = 0;

rau (rau cov menyuam kuv = 0; Kuv < slices.length; i ) {

startAngle = (rau cov menyuam) (curValue * 360 / tag nrho);

int arcAngle = (rau cov menyuam) (slices[Kuv].tus nqi * 360 / tag nrho);

g.g.setcolor(slices[Kuv].xim);

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

startAngle, arcAngle);

curValue += slices[Kuv].tus nqi;

}

}

}

pej xeem hoob loj {

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] av) {

JFrame frame = new JFrame();

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

frame.setSize(300, 200);

frame.setVisible(tseeb);

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no.

Displays a piechart on a frame.

  1. How to draw a polygon using GUI?

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

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class Main extends JPanel {

public void paintComponent(Nraaj g) {

super.paintComponent(g);

Polygon p = new Polygon();

rau (rau cov menyuam kuv = 0; Kuv < 5; i )

p.addPoint((rau cov menyuam)

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

(rau cov menyuam) (100 + 50 * Math.sin(Kuv * 2 * Math.PI / 5)));

g.drawPolygon(p);

}

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args) {

JFrame frame = new JFrame();

frame.setTitle(“Polygon”);

frame.setSize(350, 250);

frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.Exit(0);

}

});

Container contentPane = frame.getContentPane();

contentPane.add(new Main());

frame.setVisible(tseeb);

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no.

Polygon is displayed in a frame.

  1. How to create a transparent cursor?

IB: Following example demonstrates how to create a transparent cursor by using createCustomCursor() method withinvisiblecursoras 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;

pej xeem hoob loj {

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] av) throws kos {

rau cov menyuam[] 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.”);

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no.

Transparent Cursor created.

  1. How to commit a query?

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

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args) throws kos{

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

Connection con = DriverManager.getConnection

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

Statement stmt = con.createStatement();

Cov lus nug txoj hlua = “insert into emp values(2,’name1′,’job’)”;

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

String query2 = “xaiv * from emp”;

ResultSet rs = stmt.executeQuery(query2);

int no_of_rows = 0;

Thaum (rs.next()) {

no_of_rows++;

}

System.out.println(“Tsis yog. of rows before commit

statement = “+ no_of_rows);

con.setAutoCommit(tsis tseeb);

stmt.execute(query1);

stmt.execute(lus nug);

con.commit();

rs = stmt.executeQuery(query2);

no_of_rows = 0;

Thaum (rs.next()) {

no_of_rows++;

}

System.out.println(“Tsis yog. of rows after commit

statement = “+ no_of_rows);

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no. The result may vary.

Tsis yog. of rows before commit statement = 1

Tsis yog. 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?

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

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args) throws kos{

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

Connection con = DriverManager.getConnection

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

Statement stmt = con.createStatement();

Cov lus nug txoj hlua = “xaiv * from emp order by name”;

ResultSet rs = stmt.executeQuery(lus nug);

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

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no. 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 cov ntaub ntawv.

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

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args) {

sim {

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

}

ntes(ClassNotFoundException e) {

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

}

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

int no_of_rows = 0;

sim {

Connection con = DriverManager.getConnection

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

“lo lus zais”);

Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery

(“XAIV * FROM employee”);

Thaum (rs.next()) {

no_of_rows++;

}

System.out.println(“Muaj “+ no_of_rows

+ ” record in the table”);

}

ntes(SQLException e){

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

}

}

}

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

JDBC Class found

Muaj 2 records in the table

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

IB: Following example uses create, alter & drop SQL commands to create, edit or delete table. Tus 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 {

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args) throws kos{

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

Connection con = DriverManager.getConnection

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

“lo lus zais”);

Statement stmt = con.createStatement();

Cov lus nug txoj hlua =”CREATE TABLE employees

(id INTEGER PRIMARY KEY,

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

stmt.execute(lus nug);

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

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no. 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?

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

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args) throws kos{

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

Connection con = DriverManager.getConnection

(“jdbc:derby://localhost:1527/testDb”,”lub npe”,”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(tsis tseeb);

stmt.addBatch(insertEmp1);

stmt.addBatch(insertEmp2);

stmt.addBatch(insertEmp3);

ResultSet rs = stmt.executeQuery(“xaiv * 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(“xaiv * from emp”);

rs.last();

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

+ rs.getRow());

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no. 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?

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

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args) throws kos{

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

Connection con = DriverManager.getConnection

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

“lo lus zais”);

Statement stmt = con.createStatement();

Cov lus nug txoj hlua =”SELECT fname,lname,isbn from author

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

ResultSet rs = stmt.executeQuery(lus nug);

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

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

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no. 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?

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

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args) throws kos{

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

Connection con = DriverManager.getConnection

(“jdbc:derby://localhost:1527/testDb”,”lub npe”,”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();

Cov lus nug txoj hlua = “xaiv * from emp”;

ResultSet rs = stmt.executeQuery(lus nug);

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

Thaum (rs.next()) {

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

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

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

System.out.println(daim + ” ” + lub npe ” “+job);

}

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no. The result may vary.

Id Name Job

23 Roshan CEO








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

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

pej xeem tsis muaj dabtsis loj zoo li qub(Txoj hlua[] args) {

sim {

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

}

ntes(ClassNotFoundException e) {

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

}

sim {

Connection con = DriverManager.getConnection

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

“lo lus zais”);

Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery

(“XAIV * FROM employee”);

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

Thaum (rs.next()) {

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

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

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

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

}

}

ntes(SQLException e){

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

}

}

}

Cov chaws saum toj no yuav ua tau cov nram qab no. The result may vary.

id name job

1 alok trainee

2 ravi trainee

============================================= ============================================== Yuav zoo TechAlpine phau ntawv rau Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Txaus siab rau qhov blog? Tshaj tawm lus thov :)

Follow by Email
LinkedIn
LinkedIn
Share