Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 34

Object array

==--======

class Ab{
public int a;

public class Test1 {

public static void main(String[] args) {


// TODO code application logic here
Ab[] arr = new Ab[4];
for( int i=0; i<4; i++ ){
arr[i] = new Ab();
arr[i].a=i;
}

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


System.out.println(" a= "+arr[i].a);

}
}
}

Object array 2
-------------

class Ab{
public int a;

class X{
Ab[] arr=new Ab[4];
void input()
{
for( int i=0; i<4; i++ ){
arr[i] = new Ab();
arr[i].a=i;
}
}
void show()
{
for( int i=0; i<4; i++ ){
System.out.println(" a= "+arr[i].a);

}
}
}

public class Test1 {


public static void main(String[] args) {
// TODO code application logic here
X ob=new X();
ob.input();
ob.show();

}
}

====-===

File Write
=-====

import java.io.*;

class FileReaderDemow {
public static void main(String args[]) throws IOException {
FileReader fr = new FileReader("Test1.java");
BufferedReader br = new BufferedReader(fr);
String s;
FileWriter f1 = new FileWriter("file5.txt");

while((s = br.readLine()) != null) {


f1.write(s);
f1.write("\r\n");
System.out.println(s);
}

fr.close();
f1.close();
}
}

=-===
Fileappend

==-==-==

import java.io.*;

class FileReaderDemo {
public static void main(String args[]) throws IOException {
FileReader fr = new FileReader("file3.txt");
BufferedReader br = new BufferedReader(fr);
String s;
// FileWriter f1 = new FileWriter("file4.txt");
FileWriter f1 = new FileWriter("file4.txt",true);
while((s = br.readLine()) != null) {
//f1.write(s);
//f1.write("\r\n");
System.out.println(s);
}
f1.append("hhhhhs");
f1.append("\r\n");
fr.close();
f1.close();
}
}

=====--

import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;

public class Server extends JFrame {


// Text area for displaying contents
private JTextArea jta = new JTextArea();

public static void main(String[] args) {


new Server();
}

public Server() {
// Place text area on the frame
setLayout(new BorderLayout());
add(new JScrollPane(jta), BorderLayout.CENTER);

setTitle("Server");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // It is necessary to show the frame here!

try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8000);
jta.append("Server started at " + new Date() + '\n');

// Listen for a connection request


Socket socket = serverSocket.accept();

// Create data input and output streams


DataInputStream inputFromClient = new DataInputStream(
socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(
socket.getOutputStream());

while (true) {
// Receive radius from the client
double radius = inputFromClient.readDouble();

// Compute area
double area = radius * radius * Math.PI;

// Send area back to the client


outputToClient.writeDouble(area);

jta.append("Radius received from client: " + radius + '\n');


jta.append("Area found: " + area + '\n');
}
}
catch(IOException ex) {
System.err.println(ex);
}
}
}

import java.io.*;

import java.net.*;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class Client extends JFrame {

// Text field for receiving radius


private JTextField jtf = new JTextField();

// Text area to display contents

private JTextArea jta = new JTextArea();

// IO streams

private DataOutputStream toServer;

private DataInputStream fromServer;

public static void main(String[] args) {

new Client();

public Client() {

// Panel p to hold the label and text field

JPanel p = new JPanel();

p.setLayout(new BorderLayout());

p.add(new JLabel("Enter radius"), BorderLayout.WEST);

p.add(jtf, BorderLayout.CENTER);

jtf.setHorizontalAlignment(JTextField.RIGHT);

setLayout(new BorderLayout());

add(p, BorderLayout.NORTH);

add(new JScrollPane(jta), BorderLayout.CENTER);


jtf.addActionListener(new ButtonListener()); // Register listener

setTitle("Client");

setSize(500, 300);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setVisible(true); // It is necessary to show the frame here!

try {

// Create a socket to connect to the server

Socket socket = new Socket("localhost", 8000);

// Socket socket = new Socket("130.254.204.36", 8000);

// Socket socket = new Socket("drake.Armstrong.edu", 8000);

// Create an input stream to receive data from the server

fromServer = new DataInputStream(

socket.getInputStream());

// Create an output stream to send data to the server

toServer =

new DataOutputStream(socket.getOutputStream());

catch (IOException ex) {

jta.append(ex.toString() + '\n');

}
private class ButtonListener implements ActionListener {

public void actionPerformed(ActionEvent e) {

try {

// Get the radius from the text field

double radius = Double.parseDouble(jtf.getText().trim());

// Send the radius to the server

toServer.writeDouble(radius);

toServer.flush();

// Get area from the server

double area = fromServer.readDouble();

// Display to the text area

jta.append("Radius is " + radius + "\n");

jta.append("Area received from the server is "

+ area + '\n');

catch (IOException ex) {

System.err.println(ex);

}
-----------------------

Database sqlite

----------------------------

import java.sql.*;

public class dbsq

public static void main(String[] args)

try

Class.forName("org.sqlite.JDBC");

Connection conn = DriverManager.getConnection("jdbc:sqlite:test2.sqlite");

Statement s = conn.createStatement();

String selTable = "SELECT * FROM EMP";

s.execute(selTable);

ResultSet rs = s.getResultSet();

while((rs!=null) && (rs.next()))

System.out.println(rs.getString(1) + " : " + rs.getString(2)+" : " + rs.getString(3));

s.close();
conn.close();

catch(Exception ex)

ex.printStackTrace();

----------------------

Database dbAccess: File Location

----------------------

import java.sql.*;

public class dbAccess

public static void main(String[] args)

try

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

String database ="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" +


"E:\\BDTest1.accdb";
//String database ="jdbc:odbc:bdtest1dsn";

Connection conn = DriverManager.getConnection(database, "", "");

Statement s = conn.createStatement();

String selTable = "SELECT * FROM student";

s.execute(selTable);

ResultSet rs = s.getResultSet();

while((rs!=null) && (rs.next()))

System.out.println(rs.getString(1) + " : " + rs.getString(2));

s.close();

conn.close();

catch(Exception ex)

ex.printStackTrace();

-----------

DSN-Access:

----------- -

import java.sql.*;
public class dbAccess

public static void main(String[] args)

try

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

//String database ="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" +


"E:\\BDTest1.accdb";

String database ="jdbc:odbc:bdtest1dsn";

Connection conn = DriverManager.getConnection(database, "", "");

Statement s = conn.createStatement();

String selTable = "SELECT * FROM student";

s.execute(selTable);

ResultSet rs = s.getResultSet();

while((rs!=null) && (rs.next()))

System.out.println(rs.getString(1) + " : " + rs.getString(2));

s.close();

conn.close();

catch(Exception ex)

{
ex.printStackTrace();

-- ---

Access Insert update

-- --- ---

import java.sql.*;

public class dbAccess

public static void main(String[] args)

try

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

String database ="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" +


"D:\\java\\BDTest1.accdb";

// String database ="jdbc:odbc:bdtest1dsn";

Connection conn = DriverManager.getConnection(database, "", "");

Statement s = conn.createStatement();

//String sql2 = "INSERT INTO student " +

// "VALUES ('3', 'Zara', 'Dhaka')";


// s.executeUpdate(sql2);

String sql3 = "Update student " +

"SET Name='Sara' Where id='3'";

s.executeUpdate(sql3);

String selTable = "SELECT * FROM student";

s.execute(selTable);

ResultSet rs = s.getResultSet();

while((rs!=null) && (rs.next()))

System.out.println(rs.getString(1) + " : " + rs.getString(2));

s.close();

conn.close();

catch(Exception ex)

ex.printStackTrace();

---- -----

Select only MySQL

---------- ----
import java.sql.*;

public class DBTest {

// JDBC driver name and database URL

static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";

static final String DB_URL = "jdbc:mysql://localhost/EMP";

// Database credentials

static final String USER = "root";

static final String PASS = "";

public static void main(String[] args) {

Connection conn = null;

Statement stmt = null;

try{

//STEP 2: Register JDBC driver

Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a connection

System.out.println("Connecting to database...");

conn = DriverManager.getConnection(DB_URL,USER,PASS);

//STEP 4: Execute a query

System.out.println("Creating statement...");

stmt = conn.createStatement();
String sql;

sql = "SELECT id, name, address FROM Empinfo";

ResultSet rs = stmt.executeQuery(sql);

//STEP 5: Extract data from result set

while(rs.next()){

//Retrieve by column name

int id = rs.getInt("id");

String name = rs.getString("name");

String address = rs.getString("address");

//Display values

System.out.print("ID: " + id);

//System.out.print(", Age: " + age);

System.out.print(", Name: " + name);

System.out.println(", addr: " + address);

//STEP 6: Clean-up environment

rs.close();

stmt.close();

conn.close();

}catch(SQLException se){

//Handle errors for JDBC

se.printStackTrace();
}catch(Exception e){

//Handle errors for Class.forName

e.printStackTrace();

}finally{

//finally block used to close resources

try{

if(stmt!=null)

stmt.close();

}catch(SQLException se2){

}// nothing we can do

try{

if(conn!=null)

conn.close();

}catch(SQLException se){

se.printStackTrace();

}//end finally try

}//end try

System.out.println("Goodbye!");

}//end main

}//end FirstExample

------ ---------------------------------------

- MySQl insert update


-
- ---- ---
import java.sql.*;

public class DBTest {


// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";

// Database credentials
static final String USER = "root";
static final String PASS = "";

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a connection


System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);

//STEP 4: Execute a query


System.out.println("Creating statement...");
stmt = conn.createStatement();
//String sql2 = "INSERT INTO EMPinfo " +
// "VALUES (4, 'Zara', 'Dhaka')";
//stmt.executeUpdate(sql2);
String sql3 = "Update EMPinfo " +
"SET Name='Sara' Where id=4";
stmt.executeUpdate(sql3);
String sql;
sql = "SELECT id, name, address FROM Empinfo";
ResultSet rs = stmt.executeQuery(sql);

//STEP 5: Extract data from result set


while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");

String name = rs.getString("name");


String address = rs.getString("address");

//Display values
System.out.print("ID: " + id);
//System.out.print(", Age: " + age);
System.out.print(", Name: " + name);
System.out.println(", addr: " + address);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample

---- -----
/**Design JFrame:

Textbox1

Textbox2

Jbutton1

---- --*/

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;

/**

* @author TOSHIBA

*/

public class DBTestForm extends javax.swing.JFrame {

/**

* Creates new form DBTestForm

*/

public DBTestForm() {

initComponents();

}
/**

* This method is called from within the constructor to initialize the form.

* WARNING: Do NOT modify this code. The content of this method is always

* regenerated by the Form Editor.

*/

@SuppressWarnings("unchecked")

// <editor-fold defaultstate="collapsed" desc="Generated Code">

private void initComponents() {

jTextField1 = new javax.swing.JTextField();

jTextField2 = new javax.swing.JTextField();

jButton1 = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jTextField1.setText("jTextField1");

jTextField2.setText("jTextField2");

jButton1.setText("jButton1");

jButton1.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton1ActionPerformed(evt);

}
});

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

getContentPane().setLayout(layout);

layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addGap(90, 90, 90)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(jButton1))

.addContainerGap(237, Short.MAX_VALUE))

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addGap(60, 60, 60)

.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

.addGap(31, 31, 31)

.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

.addGap(67, 67, 67)

.addComponent(jButton1)
.addContainerGap(79, Short.MAX_VALUE))

);

pack();

}// </editor-fold>

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

try

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

String database ="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" +


"E:\\BDTest1.accdb";

Connection conn = DriverManager.getConnection(database, "", "");

Statement s = conn.createStatement();

String selTable = "SELECT * FROM student";

s.execute(selTable);

ResultSet rs = s.getResultSet();

String s1,s2;

rs.next();

s1=rs.getString(1);

s2=rs.getString(2);

jTextField1.setText(s1);

jTextField2.setText(s2);
s.close();

conn.close();

catch(Exception ex)

ex.printStackTrace();

// TODO add your handling code here:

/**

* @param args the command line arguments

*/

public static void main(String args[]) {

/* Set the Nimbus look and feel */

//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">

/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.

* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html

*/

try {

for (javax.swing.UIManager.LookAndFeelInfo info :


javax.swing.UIManager.getInstalledLookAndFeels()) {

if ("Nimbus".equals(info.getName())) {

javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;

} catch (ClassNotFoundException ex) {

java.util.logging.Logger.getLogger(DBTestForm.class.getName()).log(java.util.logging.Level.SEVERE, null,
ex);

} catch (InstantiationException ex) {

java.util.logging.Logger.getLogger(DBTestForm.class.getName()).log(java.util.logging.Level.SEVERE, null,
ex);

} catch (IllegalAccessException ex) {

java.util.logging.Logger.getLogger(DBTestForm.class.getName()).log(java.util.logging.Level.SEVERE, null,
ex);

} catch (javax.swing.UnsupportedLookAndFeelException ex) {

java.util.logging.Logger.getLogger(DBTestForm.class.getName()).log(java.util.logging.Level.SEVERE, null,
ex);

//</editor-fold>

/* Create and display the form */

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

new DBTestForm().setVisible(true);

});

}
// Variables declaration - do not modify

private javax.swing.JButton jButton1;

private javax.swing.JTextField jTextField1;

private javax.swing.JTextField jTextField2;

// End of variables declaration

Hello servlet

-----------

/*

* To change this license header, choose License Headers in Project Properties.

* To change this template file, choose Tools | Templates

* and open the template in the editor.

*/

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.*;
import javax.servlet.*;

/**

* @author TOSHIBA

*/

@WebServlet(urlPatterns = {"/HelloServlet"})

public class HelloServlet extends GenericServlet {

public void service(ServletRequest request,

ServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter pw = response.getWriter();

pw.println("<B>Hello!");

pw.close();

-------

Java Servlet

---------

/*

* To change this license header, choose License Headers in Project Properties.

* To change this template file, choose Tools | Templates

* and open the template in the editor.

*/
import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.*;

import java.net.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.sql.*;

/**

* @author TOSHIBA

*/

@WebServlet(urlPatterns = {"/AssignmentServlet"})

public class AssignmentServlet extends HttpServlet {

/**

* Processes requests for both HTTP <code>GET</code> and <code>POST</code>

* methods.

* @param request servlet request


* @param response servlet response

* @throws ServletException if a servlet-specific error occurs

* @throws IOException if an I/O error occurs

*/

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

try (PrintWriter out = response.getWriter()) {

/* TODO output your page here. You may use following sample code. */

Statement stmt,stmt2;

Class.forName("com.mysql.jdbc.Driver");

String url =

"jdbc:mysql://localhost:3306/test";

Connection con =

DriverManager.getConnection(

url,"root", "");

stmt = con.createStatement();

stmt2=con.createStatement();

String query = "select * from prices";

String query2 = "select * from prices";

ResultSet rs = stmt.executeQuery(query);

ResultSet rs2 = stmt2.executeQuery(query2);


int maxprice=0,minprice=0;

int fch=0;

while (rs2.next()) {

int pprice = rs2.getInt("price");

if(fch==0)

maxprice=pprice;

minprice=pprice;

fch=1;

else

if(maxprice<pprice)

maxprice=pprice;

if(minprice>pprice)

minprice=pprice;

out.println("<br>");

out.println("<br>");

out.print("<FONT color=GREEN size=14>");


out.println(" Servlet with Database ");

out.print("</FONT>");

out.println("<br>");

out.println("<br>");

out.println("<table border=1 cellspacing=3 cellpadding=3 >");

out.println("<td width=200>"+" Name "+"</td>"+"<td width=200>"+" Vendor


"+"</td>"+"<td width=200>"+ "Year "+ "</td>"+"<td width=150>"+" Price "+"</td>"+"</tr>");

while (rs.next()) {

String pname = rs.getString("name");

String pvendor = rs.getString("vendor");

int pyear = rs.getInt("year");

int pprice = rs.getInt("price");

out.println("<td width=200>");

if(maxprice==pprice)

out.println("<FONT color=red>");

if(minprice==pprice)

out.println("<b>");

out.println(pname);

if(minprice==pprice)

out.println("</b>");

if(maxprice==pprice)

out.println("</FONT>");

out.println("</td>");
out.println("<td width=150>");

if(maxprice==pprice)

out.println("<FONT color=red>");

if(minprice==pprice)

out.println("<b>");

out.println(pvendor);

if(minprice==pprice)

out.println("</b>");

if(maxprice==pprice)

out.println("</FONT>");

out.println("</td>");

out.println("<td width=200>");

if(maxprice==pprice)

out.println("<FONT color=red>");

if(minprice==pprice)

out.println("<b>");

out.println(pyear);

if(minprice==pprice)

out.println("</b>");

if(maxprice==pprice)

out.println("</FONT>");

out.println("</td>");

out.println("<td width=100>");

if(maxprice==pprice)

out.println("<FONT color=red>");
if(minprice==pprice)

out.println("<b>");

out.println(pprice);

out.println("</td>");

out.println("</tr>");

out.println(" </table>");

out.println("<br>");

out.println("<br>");

out.println("<b>");

out.println(" Note: Red rows indicate the most expensive one and bold rows indicate the
cheapest one");

out.println("</b>");

stmt.close();

stmt2.close();

con.close();

out.println("<!DOCTYPE html>");

out.println("<html>");

out.println("<head>");

out.println("<title>Servlet AssignmentServlet</title>");

out.println("</head>");

out.println("<body>");

out.println("<h1>Servlet AssignmentServlet at " + request.getContextPath() + "</h1>");


out.println("</body>");

out.println("</html>");

}catch( Exception e ) {

//out.println("Something wrong happened with your request<hr>"+e);

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to


edit the code.">

/**

* Handles the HTTP <code>GET</code> method.

* @param request servlet request

* @param response servlet response

* @throws ServletException if a servlet-specific error occurs

* @throws IOException if an I/O error occurs

*/

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

/**

* Handles the HTTP <code>POST</code> method.

*
* @param request servlet request

* @param response servlet response

* @throws ServletException if a servlet-specific error occurs

* @throws IOException if an I/O error occurs

*/

@Override

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

/**

* Returns a short description of the servlet.

* @return a String containing servlet description

*/

@Override

public String getServletInfo() {

return "Short description";

}// </editor-fold>

You might also like