- How memory is managed in java?
Ա: Memory model is common to handle in all languages.It basically defines the possible scenarios and rules that govern multiple threads in a system.In java a memory management model determines if an execution trace of a program is legally allowed by the JVM. Here the execution trace is nothing but the execution path of a thread. The Java specification for JVM model does not force its implementations to follow any particular implementation rules during program execution.It gives the JVM implementer flexibility to provide compiler optimizations, execution path and reorganizations in the execution sequence. But the most important thing is that the memory model which specifies all implementations produce results that can be predicted by a programmer.So even the flexibility is there, but still the execution path can be well predicted by the programmer.The Memory model defines the possible rules for threads, its synchronization and the expected behavior of multi-threaded programs.The responsibility of avoiding data races, dirty reading, deadlock etc in threads are still the responsibility of the programmer.
In Java manual memory allocation and de-allocation has been eliminated and it is the biggest advantage to the programmer community. Memory in Java is automatically garbage collected so you never have to worry about memory corruption or memory leak. Java memory is managed by the memory model implemented by the JVM. The Java Memory model explains synchronization techniques to make sure data corruption does not take place. The following diagram gives an overview on java memory management.
չնայած որ, 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.
- Are multiple inheritances possible in java?
Ա: No, multiple inheritance is not possible in java. Interface has been introduced to serve the purpose and it has been derived from Objective C.
The reasons for omitting multiple inheritances from the Java language mostly stem from the “simple, object oriented and familiar” goal. As a simple language, Java’s creators wanted a language that most developers could grasp without extensive training. To that end, they worked to make the language as similar to C as possible (familiar) without carrying over C ’s unnecessary complexity (simple).
In the designers’ opinion, multiple inheritance causes more problems and confusion than it solves. So they cut multiple inheritances from the language (just as they cut operator overloading). The designers’ extensive C experience taught them that multiple inheritances just weren’t worth the headache.
Փոխարեն, Java’s designers chose to allow multiple interface inheritance through the use of interfaces, an idea borrowed from Objective C’s protocols. Multiple interface inheritance allows an object to inherit many different method signatures with the caveat that the inheriting object must implement those inherited methods.
- What are the eleven design goals of java?
Ա: Following are the eleven design goals of java programming language. Java designers have accomplished the task by keeping these goals in mind.
-
- Simple
- շարժական
- Object Oriented
- Interpreted
- Distributed
- High Performance
- Robust
- Multithreaded
- Secure
- Dynamic
- Architecture Neutral
Why java is called distributed?
Ա: Java has an extensive library of routines for handling TCP/IP protocols like HTTP and FTP. So Java applications can open and access objects across the internet via URLs. The network programming using java is strong and easy to use. So java is called distributed.
The distributed nature of Java really shines when combined with its dynamic class loading capabilities. Together, these features make it possible for a Java interpreter to download and run code from across the Internet. This is what happens when a Web browser downloads and runs a Java applet, օրինակ. 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.
- Why java is called architecture neutral?
Ա: 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.
- Why java enabled browser is needed to run an applet?
Ա: Applet is a java program that works on a web page. So the browser should have the capability to interpret the bytecode and make it work. That is why java enabled browser is required to run an applet embedded in a web page. Actually the browser contains the JVM inbuilt which helps to interpret the byte code and show the output.
- What do you mean by ‘Java is a strongly typed language’?
Ա: 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.
- How I/O is managed in java?
Ա: In java I/O represents Input and Output streams. Streams are used to read from or write to devices such as file or network or console. Java.io package provides I/O classes to manipulate streams. This package supports two types of streams – binary streams which handle binary data and character streams which handle character data. InputStream and OutputStream are high level interfaces for manipulating binary streams. Reader and Writer are high level interfaces for manipulating character streams.
The following figure shows the relationship of different IO classes addressed in this section
- How does buffered stream improve performance in java?
Ա: The default behavior of a stream is to read or write one byte at a time. This causes poor I/O performance because it takes lot of time to read/write byte by byte when dealing with large amounts of data. Java I/O provides Buffered streams to override these byte by byte default behaviors. You need to use Buffered streams (BufferedInputStream and BufferedOutputStream) to buffer the data and then read/write which gives good performance. You need to understand the method’s default behavior and act upon that.
The following figure shows how buffered streams divert the data flow.
- How do you measure performance of default behavior and buffering for file reading?
Ա: The following code snippet will take similar files to read and write using default reading and buffered reading. And then it will display the time taken by both of them. For testing the code keep the files in local file system as shown below.
package com.performance.io;
import java.io.*;
public class IOTest {
հասարակական ստատիկ անվավեր հիմնական(Լար[] args){
IOTest io = new IOTest();
փորձել{
long startTime = System.currentTimeMillis();
io.readWrite(“գ:/temp/test-origin.html”,”գ:/temp/test-destination.html”);
long endTime = System.currentTimeMillis();
System.out.println(“Time taken for reading and writing using default behaviour : ”
+ (endTime – startTime) + ” milli seconds” );
long startTime1 = System.currentTimeMillis();
io.readWriteBuffer(“գ:/temp/test-origin.html”,”գ:/temp/test-destination.html”);
long endTime1 = System.currentTimeMillis();
System.out.println(“Time taken for reading and writing using buffered streams : ”
+ (endTime1 – startTime1) + ” milli seconds” );
}բռնելը(IOException e){ e.printStackTrace();}
}
public static void readWrite(String fileFrom, String fileTo) նետում IOException{
InputStream in = null;
OutputStream out = null;
փորձել{
in = new FileInputStream(fileFrom);
out = new FileOutputStream(fileTo);
ժամանակ(ճիշտ){
int bytedata = in.read();
եթե(bytedata == -1)
break;
out.write(bytedata);
}
}
բռնելը(Բացառություն են ե)
{
e.printStackTrace();
}
finally{
եթե(in != Null)
in.close();
եթե(դուրս !=null)
out.close();
}
}
public static void readWriteBuffer(String fileFrom, String fileTo) նետում IOException{
InputStream inBuffer = null;
OutputStream outBuffer = null;
փորձել{
InputStream in = new FileInputStream(fileFrom);
inBuffer = new BufferedInputStream(in);
OutputStream out = new FileOutputStream(fileTo);
outBuffer = new BufferedOutputStream(դուրս);
ժամանակ(ճիշտ){
int bytedata = inBuffer.read();
եթե(bytedata == -1)
break;
out.write(bytedata);
}
}
բռնելը(Բացառություն են ե)
{
e.printStackTrace();
}
finally{
եթե(inBuffer != Null)
inBuffer.close();
եթե(outBuffer !=null)
outBuffer.close();
}
}
)
- What is collections framework in java?
Ա: Collection is a group of objects. java.util package provides important types of collections. There are two fundamental types of collections they are Collection and Map. Collection types hold a group of objects, like Lists and Sets. But Map types hold group of objects as key, value pairs like HashMap and Hashtable. Following diagram shows the entire hierarchy of collections framework.
- How to extend an array after initialization?
Ա: Following example shows how to extend an array after initialization by creating a new array. Here the code is basically appending the new values to an existing array. The arraycopy() method should be used carefully otherwise there may a problem of data loss in the existing array.
հասարակական կարգի Գլխավոր {
հասարակական ստատիկ անվավեր հիմնական(Լար[] args) {
Լար[] names = new String[] { “X”, “իսկ”, “Z” };
Լար[] extended = new String[5];
extended[3] = “D”;
extended[4] = “Այն”;
System.arraycopy(անուններ, 0, extended, 0, names.length);
համար (String str : extended){
System.out.println(փող);
}
}
}
And the result will be as follows
X
իսկ
Z
D
Այն
- How to fill (initialize at once) an array?
Ա: This example will fill (initialize all the elements of the array in one short) an array by using Array.fill (arrayname, արժեք) method and Array.fill (arrayname, starting index, ending index, արժեք) method of Java Util class.
import java.util.*;
public class FillTest {
հասարակական ստատիկ անվավեր հիմնական(Լարային args[]) {
int array[] = new int[6];
Arrays.fill(զարդ, 100);
համար (int i = 0, n=array.length; ես < N; i ) {
System.out.println(զարդ[ես]);
}
System.out.println();
Arrays.fill(զարդ, 3, 6, 50);
համար (int i = 0, n=array.length; ես< N; i ) {
System.out.println(զարդ[ես]);
}
}
}
If you run the code then the result will be as follows.
100
100
100
100
100
100
100
100
100
50
50
50
- How to multiply two matrices of different dimensions?
Ա: Following example shows multiplication of two rectangular matrices with the help of two user defined methods multiply ( 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];
համար (int i = 0; ես< m1rows; i ){
համար (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[][] ա){
int rows = a.length;
int cols = a[0].length;
System.out.println(“զարդ[“+rows ”][“+cols ”] = {“);
համար (int i = 0; ես< rows; i ){
System.out.print(“{“);
համար (int j=0; j< cols; J ){
System.out.print(” ” + ա[ես][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, y);
Matrix.mprint(x);
Matrix.mprint(y);
Matrix.mprint(z);
}
}
The code sample will produce the following result
զարդ[2][3]={
{3, 2, 3}
{5, 9, 8}
};
զարդ[3][2]={
{4, 7}
{9, 3}
{8, 1}
};
զարդ[2][2]={
{63, 30}
{165, 70}
};
- How to merge two arrays?
Ա: This example shows how to merge two arrays into a single array by the use of list.Addall(array1.asList(array2) method of List class and Arrays.toString () method of Array class. Be careful when assigning one array to another. Because if the references of the elements of both the arrays then there is chance of cascading effect.
ներմուծման java.util.ArrayList;
import java.util.Arrays;
ներմուծման java.util.List;
հասարակական կարգի Գլխավոր {
հասարակական ստատիկ անվավեր հիմնական(Լարային args[]) {
String a[] = { “Ա”, “Այն”, “ես” };
String b[] = { “O”, “U” };
List list = new ArrayList(Arrays.asList(ա));
list.addAll(Arrays.asList(բ));
օբյեկտ[] c = list.toArray();
System.out.println(Arrays.toString(գ));
}
}
The code sample will produce the following result
[Ա, Այն, ես, O, U]
- How to search the minimum and the maximum element in an array?
Ա: This example shows how to search the minimum and maximum element in an array by using Collection.max () and Collection.min() methods of Collection class. Although there are some other ways also to find the max and min values from an array but this API is the most efficient one to work with arrays.
import java.util.Arrays;
import java.util.Collections;
հասարակական կարգի Գլխավոր {
հասարակական ստատիկ անվավեր հիմնական(Լար[] args) {
ամբողջ թիվ[] 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
- How to reverse an arraylist?
Ա: Collections API has a method called reverse (ArrayList). So this is used to reverse an array list. The following example will show you how to use the API to make the code work.
ներմուծման java.util.ArrayList;
import java.util.Collections;
հասարակական կարգի Գլխավոր {
հասարակական ստատիկ անվավեր հիմնական(Լար[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add(“Ա”);
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: [Ա, B, C, D, Այն]
After Reverse Order: [Այն, D, C, B, Ա]
- How to sort an array and insert an element inside it?
Ա: The following example shows how to use sort () method and user defined method insertElement () to accomplish the task. The sort () method is used to sort the array from negative to positive value then the customized insertElement () method is used to add additional elements into it.
import java.util.Arrays;
public class MainClass {
հասարակական ստատիկ անվավեր հիմնական(Լարային args[]) throws Exception {
int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
Arrays.sort(զարդ);
printArray(“Sorted array”, զարդ);
int index = Arrays.binarySearch(զարդ, 1);
System.out.println(“Didn’t find 1 @ ”
+ ինդեքս);
int newIndex = -index – 1;
array = insertElement(զարդ, 1, newIndex);
printArray(“With 1 added”, զարդ);
}
private static void printArray(String հաղորդագրությունը, int array[]) {
System.out.println(message
+ “: [length: ” + array.length + “]”);
համար (int i = 0; ես < array.length; i ) {
եթե (ես != 0){
System.out.print(“, “);
}
System.out.print(զարդ[ես]);
}
System.out.println();
}
private static int[] insertElement(int original[],
int element, int index) {
int length = original.length;
int destination[] = new int[length + 1];
System.arraycopy(original, 0, destination, 0, ինդեքս);
destination[ինդեքս] = element;
System.arraycopy(original, ինդեքս, destination, ինդեքս
+ 1, length – ինդեքս);
return destination;
}
}
- How to sort an array and search an element inside it?
Ա: The following example shows how to use sort () and binarySearch () method to accomplish the task. The user defined method printArray () is used to display the output.
mport java.util.Arrays;
public class MainClass {
հասարակական ստատիկ անվավեր հիմնական(Լարային args[]) throws Exception {
int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
Arrays.sort(զարդ);
printArray(“Sorted array”, զարդ);
int index = Arrays.binarySearch(զարդ, 2);
System.out.println(“Found 2 @ ” + ինդեքս);
}
private static void printArray(String հաղորդագրությունը, int array[]) {
System.out.println(message
+ “: [length: ” + array.length + “]”);
համար (int i = 0; ես < array.length; i ) {
եթե(ես != 0){
System.out.print(“, “);
}
System.out.print(զարդ[ես]);
}
System.out.println();
}
}
If you run the code then the application will show the result as given below.
Sorted array: [length: 10]
-9, -7, -3, -2, 0, 2, 4, 5, 6, 8
Found 2 @ 5
- How to create a banner using Applet?
Ա: The following example has used the Thread class and Graphics class to display the banner. The functionality of the thread is to give an effect of animation to the banner. To view the output the applet should be run In a browser which supports applet.
iimport java.awt.*;
import java.applet.*;
public class SampleBanner extends Applet
implements Runnable{
String str = “This is a simple Banner “;
Thread t ;
boolean b;
public void init() {
setBackground(Color.gray);
setForeground(Color.yellow);
}
public void start() {
t = new Thread(այս);
b = false;
t.start();
}
public void run () {
char ch;
համար( ; ; ) {
փորձել {
repaint();
Thread.sleep(250);
ch = str.charAt(0);
str = str.substring(1, str.length());
str = str + ch;
}
բռնելը(InterruptedException e) {}
}
}
public void paint(Graphics g) {
g.drawRect(1,1,300,150);
g.setColor(Color.yellow);
g.fillRect(1,1,300,150);
g.setColor(Color.red);
g.drawString(փող, 1, 150);
}
}
- How to display a clock using an applet?
Ա: The example has used String class and Calendar class to display the applet clock. Calendar class gives the value of ‘Hours’, ‘Minutes’ and ‘second’.
ներմուծումը java.awt *;
import java.applet.*;
import java.applet.*;
ներմուծումը java.awt *;
import java.util.*;
public class ClockApplet extends Applet implements Runnable{
Thread t,t1;
public void start(){
t = new Thread(այս);
t.start();
}
public void run(){
t1 = Thread.currentThread();
ժամանակ(t1 == t){
repaint();
փորձել{
t1.sleep(1000);
}
բռնելը(InterruptedException e){}
}
}
public void paint(Graphics g){
Calendar cal = new GregorianCalendar();
String hour = String.valueOf(cal.get(Calendar.HOUR));
String minute = String.valueOf(cal.get(Calendar.MINUTE));
String second = String.valueOf(cal.get(Calendar.SECOND));
g.drawString(hour + “:” + minute + “:” + երկրորդ, 20, 30);
}
}
Again you have to run the applet in a browser or applet viewer to check the output.
- How to create an event listener in Applet?
Ա: Following example demonstrates how to create a basic Applet having buttons to add & subtract two numbers. Methods used here are addActionListener () to listen to an event(click on a button) & կոճակ() constructor to create a button.
import java.applet.*;
import java.awt.event.*;
ներմուծումը java.awt *;
public class EventListeners extends Applet
implements ActionListener{
TextArea txtArea;
String Add, Subtract;
int i = 10, j = 20, sum =0,Sub=0;
public void init(){
txtArea = new TextArea(10,20);
txtArea.setEditable(false);
ավելացնել(txtArea,”center”);
Button b = new Button(“Add”);
Button c = new Button(“Subtract”);
b.addActionListener(այս);
c.addActionListener(այս);
ավելացնել(բ);
ավելացնել(գ);
}
public void actionPerformed(ActionEvent e){
sum = i + j;
txtArea.setText(“”);
txtArea.append(“i = “+ ես + “\T” + “j = ” + j + “\N”);
Button source = (կոճակ)e.getSource();
եթե(source.getLabel() == “Add”){
txtArea.append(“Sum : ” + sum + “\N”);
}
եթե(ես >j){
Sub = i – j;
}
else{
Sub = j – ես;
}
եթե(source.getLabel() == “Subtract”){
txtArea.append(“Sub : ” + Sub + “\N”);
}
}
}
- How to open a link in a new window using Applet?
Ա: This example demonstrates how to open a particular webpage from an applet in a new window using showDocument() method with second argument as “_blank” .
import java.applet.*;
ներմուծումը java.awt *;
import java.net.*;
import java.awt.event.*;
public class testURL_NewWindow extends Applet
implements ActionListener{
public void init(){
String link_Text = “google”;
Button b = new Button(link_Text);
b.addActionListener(այս);
ավելացնել(բ);
}
public void actionPerformed(ActionEvent ae){
Button source = (կոճակ)ae.getSource();
String link = “HTTP://www.”+source.getLabel()+”.com”;
փորձել {
AppletContext a = getAppletContext();
URL url = new URL(link);
a.showDocument(url,”_blank”);
}
բռնելը (MalformedURLException e){
System.out.println(e.getMessage());
}
}
}
- How to read a file using Applet?
Ա: The following code snippet demonstrates how to read a file using an Applet using openStream() method of URL. There are different ways to read a stream like buffered stream, customized buffered stream etc. Here we have used buffered stream to read the data.
import java.applet.*;
ներմուծումը java.awt *;
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();
ժամանակ((line = bf.readLine()) != Null){
strBuff.append(line + “\N”);
}
txtArea.append(“File Name : ” + fileToRead + “\N”);
txtArea.append(strBuff.toString());
}
բռնելը(IOException e){
e.printStackTrace();
}
}
}
- How to create different shapes using Applet?
Ա: This example demonstrates how to create an applet which will have a line, an Oval & a Rectangle using drawLine(), drawOval() and drawRect() methods of Graphics class. In java Graphics class is widely used to draw diagrams and those are used in pie chart, bar diagram etc.
import java.applet.*;
ներմուծումը java.awt *;
public class Shapes extends Applet{
int x=300,y=100,r=50;
public void paint(Graphics g){
g.drawLine(30,300,200,10);
g.drawOval(x-r,y-r,100,100);
g.drawRect(400,50,200,100);
}
}
The above code sample will produce the following result in a java enabled web browse
A line, Oval & a Rectangle will be drawn in the browser.
- How to use swing applet in JAVA?
Ա: Swing is an important component in java to produce UI interfaces. These swing components are also used in applet to make the user interface.Following example demonstrates how to go use Swing Applet in JAVA by implementing ActionListener & by creating JLabels.
ներմուծման javax.swing *;
import java.applet.*;
ներմուծումը java.awt *;
import java.awt.event.*;
public class SApplet extends Applet implements ActionListener {
TextField input,output;
Label label1,label2;
Button b1;
JLabel lbl;
int num, գումարը = 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(այս);
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!”);
}
}
}
- How to write to a file using Applet?
Ա: In the following example java text area has been used to enter the user input. After entering the input it has been written in a file in local file system. The File () constructor has been used to create the file.
import java.io.*;
ներմուծումը java.awt *;
import java.awt.event.*;
ներմուծման javax.swing *;
import java.applet.Applet;
import java.net.*;
public class WriteFile extends Applet{
Button write = new Button(“WriteToFile”);
Label label1 = new Label(“Enter the file name:”);
TextField text = new TextField(20);
Label label2 = new Label(“Write your text:”);
TextArea area = new TextArea(10,20);
public void init(){
ավելացնել(label1);
label1.setBackground(Color.lightGray);
ավելացնել(text);
ավելացնել(label2);
label2.setBackground(Color.lightGray);
ավելացնել(area);
ավելացնել(write,BorderLayout.CENTER);
write.addActionListener(new ActionListener (){
public void actionPerformed(ActionEvent e){
new WriteText();
}
}
);
}
public class WriteText {
WriteText(){
փորձել {
String str = text.getText();
եթե(str.equals(“”)){
JOptionPane.showMessageDialog(զրո,
“Please enter the file name!”);
text.requestFocus();
}
else{
File f = new File(փող);
եթե(f.exists()){
BufferedWriter out = new
BufferedWriter(նոր FileWriter(զ,ճիշտ));
եթե(area.getText().հավասար(“”)){
JOptionPane.showMessageDialog
(զրո,”Please enter your text!”);
area.requestFocus();
}
else{
out.write(area.getText());
եթե(f.canWrite()){
JOptionPane.showMessageDialog(զրո,
“Text is written in “+փող);
text.setText(“”);
area.setText(“”);
text.requestFocus();
}
else{
JOptionPane.showMessageDialog(զրո,
“Text isn’t written in “+փող);
}
out.close();
}
}
else{
JOptionPane.showMessageDialog
(զրո,”File not found!”);
text.setText(“”);
text.requestFocus();
}
}
}
բռնելը(Exception x){
x.printStackTrace();
}
}
}
}
- How to print summation of n numbers?
Ա: Following example demonstrates how to add first n natural numbers by using the concept of stack. Here the static Stack class is used to hold the numbers. The custom stackAddition () method is used to add the numbers into the stack.
Ներմուծման java.io.IOException;
public class AdditionStack {
static int num;
static int ans;
static Stack theStack;
հասարակական ստատիկ անվավեր հիմնական(Լար[] args) նետում IOException {
num = 50;
stackAddition();
System.out.println(“Sum=” + ans);
}
public static void stackAddition() {
theStack = new Stack(10000);
ans = 0;
ժամանակ (Num > 0)
{
theStack.push(Num);
–Num;
}
ժամանակ (!theStack.isEmpty())
{
int newN = theStack.pop();
ans = newN;
}
}
}
class Stack {
private int maxSize;
private int[] data;
private int top;
public Stack(int s) {
maxSize = s;
data = new int[maxSize];
top = -1;
}
public void push(int p) {
data[++top] = p;
}
public int pop() {
return data[top–];
}
public int peek() {
return data[top];
}
public boolean isEmpty() {
return (top == -1);
}
}
The above code sample will produce the following result.
Sum=1225
- How to get the first and the last element of a linked list?
Ա: Following example shows how to get the first and last element of a linked list with the help of linkedlistname.getFirst() and linkedlistname.getLast() of LinkedList class. All of the stack/queue/deque operations could be easily recast in terms of the standard list operations. They’re included here primarily for convenience, though they may run slightly faster than the equivalent List operations.
import java.util.LinkedList;
հասարակական կարգի Գլխավոր {
հասարակական ստատիկ անվավեր հիմնական(Լար[] 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
- How to add an element at first and last position of a linked list?
Ա: Following example shows how to add an element at the first and last position of a linked list by using addFirst() and addLast() method of Linked List class.
import java.util.LinkedList;
հասարակական կարգի Գլխավոր {
հասարակական ստատիկ անվավեր հիմնական(Լար[] 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
- How to convert an infix expression to postfix expression?
Ա: Following example demonstrates how to convert an infix to postfix expression by using the concept of stack. Here push (), pop () and peek () methods are used to perform the task. And the Stack class is used to hold the expressions.
Ներմուծման java.io.IOException;
public class InToPost {
private Stack theStack;
private String input;
private String output = “”;
public InToPost(String in) {
input = in;
int stackSize = input.length();
theStack = new Stack(stackSize);
}
public String doTrans() {
համար (int J = 0; j < input.length(); J ) {
char ch = input.charAt(j);
switch (ch) {
case ‘ ’:
case ‘-‘:
gotOper(ch, 1);
break;
case ‘*’:
case ‘/’:
gotOper(ch, 2);
break;
case ‘(‘:
theStack.push(ch);
break;
case ‘)’:
gotParen(ch);
break;
default:
output = output + ch;
break;
}
}
ժամանակ (!theStack.isEmpty()) {
output = output + theStack.pop();
}
System.out.println(output);
return output;
}
public void gotOper(char opThis, int prec1) {
ժամանակ (!theStack.isEmpty()) {
char opTop = theStack.pop();
եթե (opTop == ‘(‘) {
theStack.push(opTop);
break;
}
else {
int prec2;
եթե (opTop == ‘ ’ || opTop == ‘-‘)
prec2 = 1;
else
prec2 = 2;
եթե (prec2 < prec1)
{
theStack.push(opTop);
break;
} else
output = output + opTop;
}
}
theStack.push(opThis);
}
public void gotParen(char ch){
ժամանակ (!theStack.isEmpty()) {
char chx = theStack.pop();
եթե (chx == ‘(‘)
break;
else
output = output + chx;
}
}
հասարակական ստատիկ անվավեր հիմնական(Լար[] args) նետում IOException {
String input = “1+2*4/5-7+3/6”;
String output;
InToPost theTrans = new InToPost(input);
output = theTrans.doTrans();
System.out.println(“Postfix is ” + output + ‘n’);
}
class Stack {
private int maxSize;
private char[] stackArray;
private int top;
public Stack(int max) {
maxSize = max;
stackArray = new char[maxSize];
top = -1;
}
public void push(char j) {
stackArray[++top] = j;
}
public char pop() {
return stackArray[top–];
}
public char peek() {
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
}
}
The above code sample will produce the following result.
124*5/+7-36/+
Postfix is 124*5/+7-36/+
- How to implement Queue?
Ա: Following example shows how to implement a queue in an employee structure. Linked list is an implementation of the List interface. Implements all optional list operations, and permits all elements (including null). In addition to implementing the List interface.The LinkedList class provides uniformly named methods to get, remove and insert an element at the beginning and end of the list. These operations allow linked lists to be used as a stack, queue, or double-ended queue.
import java.util.LinkedList;
class GenQueue {
private LinkedList list = new LinkedList();
public void enqueue(E item) {
list.addLast(կետ);
}
public E dequeue() {
return list.poll();
}
public boolean hasItems() {
return !list.isEmpty();
}
public int size() {
return list.size();
}
public void addItems(GenQueue q) {
ժամանակ (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:”);
ժամանակ (empList.hasItems()) {
Employee emp = empList.dequeue();
System.out.println(emp.firstName + ” ” + emp.lastName);
}
}
}
class Employee {
` public String lastName;
public String firstName;
հասարակական Employee() {
}
հասարակական 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
- How to reverse a string using stack?
Ա: Following example shows how to reverse a string using stack with the help of user defined method StringReverserThroughStack ().A simple Stack in Java, implemented as an object-oriented, recursive data structure, a singly linked list. Note that Java already provides a Stack class
Ներմուծման java.io.IOException;
public class StringReverserThroughStack {
private String input;
private String output;
public StringReverserThroughStack(String in) {
input = in;
}
public String doRev() {
int stackSize = input.length();
Stack theStack = new Stack(stackSize);
համար (int i = 0; ես < input.length(); i ) {
char ch = input.charAt(ես);
theStack.push(ch);
}
output = “”;
ժամանակ (!theStack.isEmpty()) {
char ch = theStack.pop();
output = output + ch;
}
return output;
}
հասարակական ստատիկ անվավեր հիմնական(Լար[] args) նետում IOException {
String input = “Java Source and Support”;
String output;
StringReverserThroughStack theReverser =
new StringReverserThroughStack(input);
output = theReverser.doRev();
System.out.println(“Reversed: ” + output);
}
class Stack {
private int maxSize;
private char[] stackArray;
private int top;
public Stack(int max) {
maxSize = max;
stackArray = new char[maxSize];
top = -1;
}
public void push(char j) {
stackArray[++top] = j;
}
public char pop() {
return stackArray[top–];
}
public char peek() {
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
}
}
The above code sample will produce the following result.
JavaStringReversal
Reversed:lasreveRgnirtSavaJ
- How to check whether antialiasing is enabled or not?
Ա: Following example demonstrates how to check if antialiasing is turned on or not using RenderingHints Class. Aliasing occurs when a signal (in this case, a 2D graphics signal) is sampled and quantized from a continuous space into a discretized space. Sampling is the process of reading a value from a continuously varying signal. Quantization is the process by which these continuous sampled values are assigned a discrete value in the finite space represented by digital (binary-based) systems.
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JComponent;
Ներմուծման javax.swing.JFrame;
հասարակական կարգի Գլխավոր {
հասարակական ստատիկ անվավեր հիմնական(Լար[] 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
- How to display colors in a frame?
Ա: Following example displays how to a display all the colors in a frame using setRGB method of image class. The abstract class Image is the superclass of all classes that represent graphical images. The image must be obtained in a platform-specific manner.
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;
Ներմուծման javax.swing.JFrame;
public class Main extends JComponent {
BufferedImage image;
public void initialize() {
int width = getSize().width;
int height = getSize().height;
int[] data = new int[width * height];
int index = 0;
համար (int i = 0; ես < height; i ) {
int red = (ես * 255) / (height – 1);
համար (int J = 0; j < width; J ) {
int green = (j * 255) / (width – 1);
int blue = 128;
data[index ] = (կարմիր < < 16) | (կանաչ < < 8) | blue;
}
}
image = new BufferedImage
(width, height, BufferedImage.TYPE_INT_RGB);
image.setRGB(0, 0, width, height, data, 0, width);
}
public void paint(Graphics g) {
եթե (image == null)
initialize();
g.drawImage(image, 0, 0, այս);
}
հասարակական ստատիկ անվավեր հիմնական(Լար[] 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.
- What is threading in java?
Ա: A Java program can contain many threads, all of which may be created without the explicit knowledge of the developer. For now, all you need to consider is that when you write a Java application, there is an initial thread that begins its operation by executing the main() method of your application. When you write a Java applet, there is a thread that is executing the callback methods (init(), actionPerformed(), etc.) of your applet; we speak of this thread as the applet’s thread. In either case, your program starts with what you can consider as a single thread. If you want to perform I/O (particularly if the I/O might block), start a timer, or do any other task in parallel with the initial thread, you must start a new thread to perform that task.
- How to display text in different fonts?
Ա: Following example demonstrates how to display text in different fonts using setFont () method of Font class. The Font class represents fonts, which are used to render text in a visible way. A font provides the information needed to map sequences of characters to sequences of glyphs and to render sequences of glyphs on Graphics and Component objects.
ներմուծումը java.awt *;
import java.awt.event.*
ներմուծման javax.swing *
public class Main extends JPanel {
Լար[] 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; զ < type.length; f ) {
համար (int s = 0; S < styles.length; s ) {
Font font = new Font(type[զ], styles[S], 18);
g.setFont(font);
String name = type[զ] + ” ” + stylenames[S];
g.drawString(անվանում, 20, (զ * 4 + S + 1) * 20);
}
}
}
հասարակական ստատիկ անվավեր հիմնական(Լար[] ա) {
JFrame f = new JFrame();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
f.setContentPane(new Main());
f.setSize(400,400);
f.setVisible(ճիշտ);
}
}
The above code sample will produce the following result.
Different font names are displayed in a frame.
- How to draw a line using GUI?
Ա: Following example demonstrates how to draw a line using draw() method of Graphics2D class with Line2D object as an argument. The setPaint () method of the Graphics2D class has been used to paint the line. Here java applet is used to display the line on a JFrame.
ներմուծումը java.awt *;
import java.awt.event.*;
import java.awt.geom.Line2D;
import javax.swing.JApplet;
Ներմուծման javax.swing.JFrame;
public class Main extends JApplet {
public void init() {
setBackground(Color.white);
setForeground(Color.white);
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(Color.gray);
int x = 5;
int y = 7;
g2.draw(new Line2D.Double(x, y, 200, 200));
g2.drawString(“Line”, x, 250);
}
հասարակական ստատիկ անվավեր հիմնական(String s[]) {
JFrame f = new JFrame(“Line”);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JApplet applet = new Main();
f.getContentPane().ավելացնել(“Center”, applet);
applet.init();
f.pack();
f.setSize(Նոր Dimension(300, 300));
f.setVisible(ճիշտ);
}
}
The above code sample will produce the following result.
Line is displayed in a frame.
- How to display a message in a new frame?
Ա: Following example demonstrates how to display message in a new frame by creating a frame using JFrame() & using JFrames getContentPanel(), setSize() & setVisible() methods to display this on the frame. Here Graphics2D and Rectangle2D classes have been ued to make the initial component. And then the message is displayed on a JPanel component.
ներմուծումը java.awt *;
import java.awt.font.FontRenderContext;
գումարը java.awt.geom.Rectangle2D;
Ներմուծման javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JPanel {
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setFont(new Font(“Serif”, Font.PLAIN, 48));
paintHorizontallyCenteredText(g2, “Java Source”, 200, 75);
paintHorizontallyCenteredText(g2, “իսկ”, 200, 125);
paintHorizontallyCenteredText(g2, “Support”, 200, 175);
}
protected void paintHorizontallyCenteredText(Graphics2D g2,
String s, float centerX, float baselineY) {
FontRenderContext frc = g2.getFontRenderContext();
Rectangle2D bounds = g2.getFont().getStringBounds(S, frc);
float width = (float) bounds.getWidth();
g2.drawString(S, centerX – width / 2, baselineY);
}
հասարակական ստատիկ անվավեր հիմնական(Լար[] 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.
- How to display a pie chart using a frame?
Ա: Following example displays how to a display a piechart by making Slices class & creating arc depending on the slices. In this example AWT and swing components are used to draw the chart. Arguments are passed to the drawPie () method from the main () մեթոդ. And the completed chart is displayed on a JFrame.
Ներմուծման java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
Ներմուծման javax.swing.JFrame;
class Slice {
double value;
Color color;
public Slice(double value, Color color) {
this.value = value;
this.color = color;
}
}
class MyComponent extends JComponent {
Slice[] slices = { new Slice(5, Color.black),
new Slice(33, Color.green),
new Slice(20, Color.yellow), new Slice(15, Color.red) };
MyComponent() {}
public void paint(Graphics g) {
drawPie((Graphics2D) g, getBounds(), slices);
}
void drawPie(Graphics2D g, Rectangle area, Slice[] slices) {
double total = 0.0D;
համար (int i = 0; ես < slices.length; i ) {
total = slices[ես].արժեք;
}
double curValue = 0.0D;
int startAngle = 0;
համար (int i = 0; ես < slices.length; i ) {
startAngle = (int) (curValue * 360 / ընդհանուր);
int arcAngle = (int) (slices[ես].արժեք * 360 / ընդհանուր);
g.setColor(slices[ես].color);
g.fillArc(area.x, area.y, area.width, area.height,
startAngle, arcAngle);
curValue = slices[ես].արժեք;
}
}
}
հասարակական կարգի Գլխավոր {
հասարակական ստատիկ անվավեր հիմնական(Լար[] argv) {
JFrame frame = new JFrame();
frame.getContentPane().ավելացնել(new MyComponent());
frame.setSize(300, 200);
frame.setVisible(ճիշտ);
}
}
The above code sample will produce the following result.
Displays a piechart on a frame.
- How to draw a polygon using GUI?
Ա: 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.
ներմուծումը java.awt *;
import java.awt.event.*;
ներմուծման javax.swing *;
public class Main extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Polygon p = new Polygon();
համար (int i = 0; ես < 5; i )
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.
- How to create a transparent cursor?
Ա: Following example demonstrates how to create a transparent cursor by using createCustomCursor() method with “invisiblecursor” as an argument. Transparent cursor is generally used to hide something on the UI layer. Like in this example cursor is used on an image.
ներմուծումը java.awt *;
import java.awt.image.MemoryImageSource;
հասարակական կարգի Գլխավոր {
հասարակական ստատիկ անվավեր հիմնական(Լար[] argv) 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.
- How to commit a query?
Ա: Following example uses commit () method of connection class to commit a query. You need to setup the database and modify the fields accordingly to execute the example. In JDBC by default commit is set to ‘true’ so in this example first the autocommit is turned off. And when the execution is complete commit is triggered to the database.
import java.sql.*;
public class jdbcConn {
հասարակական ստատիկ անվավեր հիմնական(Լար[] args) throws Exception{
Class.forName(“org.apache.derby.jdbc.ClientDriver”);
Connection con = DriverManager.getConnection
(“JDBC:derby://localhost: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;
ժամանակ (rs.next()) {
no_of_rows ;
}
System.out.println(“No. of rows before commit
statement = “+ no_of_rows);
con.setAutoCommit(false);
stmt.execute(query1);
stmt.execute(հարցում);
con.commit();
rs = stmt.executeQuery(query2);
no_of_rows = 0;
ժամանակ (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
- How to use different methods of column to Count no of columns, get column name, get column type etc?
Ա: Following example uses getColumnCount, getColumnName, getColumnTypeName, getColumnDisplaySize methods to get the no of columns, name of the column or type of the column in the table. You need to setup the database and modify the fields accordingly to execute the example.
import java.sql.*;
public class jdbcConn {
հասարակական ստատիկ անվավեր հիմնական(Լար[] args) throws Exception{
Class.forName(“org.apache.derby.jdbc.ClientDriver”);
Connection con = DriverManager.getConnection
(“JDBC:derby://localhost:1527/testDb”,”անվանում”,”pass”);
Statement stmt = con.createStatement();
String query = “select * from emp order by name”;
ResultSet rs = stmt.executeQuery(հարցում);
ResultSetMetaData rsmd = rs.getMetaData();
System.out.println(“no of columns in the table= “+
rsmd.getColumnCount());
System.out.println(“Name of the first column “+
rsmd.getColumnName(1));
System.out.println(“Type of the second column “+
rsmd.getColumnTypeName(2));
System.out.println(“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
- How to connect to a database using JDBC? Assume that database name is testDb and it has table named employee which has 2 գրառումները.
Ա: Following example uses getConnection, createStatement & executeQuery methods to connect to a database & execute queries. In this example first the driver class has been loaded and then the getConnection() method of the DriverManager class has been used to get the JDBC connection.
import java.sql.*;
public class jdbcConn {
հասարակական ստատիկ անվավեր հիմնական(Լար[] 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://localhost:1527/testDb”,”username”,
“password”);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery
(“SELECT * FROM employee”);
ժամանակ (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
- How to edit (Add or update) columns of a Table and how to delete a table?
Ա: Following example uses create, alter & drop SQL commands to create, edit or delete table. The execute () method is the main method used in all the operations. And then the queries are built accordingly to add, update columns or drop a table.
import java.sql.*;
public class jdbcConn {
հասարակական ստատիկ անվավեր հիմնական(Լար[] args) throws Exception{
Class.forName(“org.apache.derby.jdbc.ClientDriver”);
Connection con = DriverManager.getConnection
(“JDBC:derby://localhost:1527/testDb”,”username”,
“password”);
Statement stmt = con.createStatement();
String query =”CREATE TABLE employees
(id INTEGER PRIMARY KEY,
first_name CHAR(50),last_name CHAR(75))”;
stmt.execute(հարցում);
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 & Ազգանուն
column removed from the table
Employees table removed from the database
- How to execute multiple SQL commands on a database simultaneously?
Ա: Following example uses addBatch & executeBatch commands to execute multiple SQL commands simultaneously. The batch update functionality allows the statement objects to support the submission of a number of update commands as a single batch.The ability to batch a number of commands together can have significant performance benefits. The methods addBatch, clearBatch and executeBatch are used in processing batch updates.
import java.sql.*;
public class jdbcConn {
հասարակական ստատիկ անվավեր հիմնական(Լար[] args) throws Exception{
Class.forName(“org.apache.derby.jdbc.ClientDriver”);
Connection con = DriverManager.getConnection
(“JDBC:derby://localhost: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
- How to join contents of more than one table & display?
Ա: 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://localhost:1527/testDb”,”username”,
“password”);
Statement stmt = con.createStatement();
String query =”SELECT fname,lname,isbn from author
inner join books on author.AUTHORID = books.AUTHORID”;
ResultSet rs = stmt.executeQuery(հարցում);
System.out.println(“Fname Lname ISBN”);
ժամանակ (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
- How to use Prepared Statement in java?
Ա: Following example uses PrepareStatement method to create PreparedStatement. It also uses setInt & setString methods of PreparedStatement to set parameters of PreparedStatement. Prepared statement is a pre compiled statement which reduces the execution time of an SQL query. It is generally used where repeated query is required.
import java.sql.*;
public class jdbcConn {
հասարակական ստատիկ անվավեր հիմնական(Լար[] args) throws Exception{
Class.forName(“org.apache.derby.jdbc.ClientDriver”);
Connection con = DriverManager.getConnection
(“JDBC:derby://localhost:1527/testDb”,”անվանում”,”pass”);
PreparedStatement updateemp = con.prepareStatement
(“insert into emp values(?,?,?)”);
updateemp.setInt(1,23);
updateemp.setString(2,”Roshan”);
updateemp.setString(3, “գործադիր տնօրեն”);
updateemp.executeUpdate();
Statement stmt = con.createStatement();
String query = “select * from emp”;
ResultSet rs = stmt.executeQuery(հարցում);
System.out.println(“Id Name Job”);
ժամանակ (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
- How to retrieve contents of a table using JDBC connection?
Ա: Following example uses getString (), getInt() & executeQuery() methods to fetch & display the contents of the table. The forName () method is used to load the driver and getConnection () method is used to get the connection to the database. This example covers all the normal database activities.
import java.sql.*;
public class jdbcResultSet {
հասարակական ստատիկ անվավեր հիմնական(Լար[] args) {
փորձել {
Class.forName(“org.apache.derby.jdbc.ClientDriver”);
}
բռնելը(ClassNotFoundException e) {
System.out.println(“Class not found “+ իսկ);
}
փորձել {
Connection con = DriverManager.getConnection
(“JDBC:derby://localhost:1527/testDb”,”username”,
“password”);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery
(“SELECT * FROM employee”);
System.out.println(“id name job”);
ժամանակ (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