Wednesday, 30 December 2015

ServletContext example to get the initialization parameter from web.xml file



import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class First
 */
@WebServlet("/First")
public class First extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub

response.setContentType("text/html");
PrintWriter pw = response.getWriter();
ServletContext context=getServletContext();
String drivername = context.getInitParameter("dname");
pw.println("Driver Name is" +drivername);
pw.close();
}

}


web.xml
<web-app>  
  
<servlet>  
<servlet-name>First</servlet-name>  
<servlet-class>First</servlet-class>  
</servlet>  
  
<context-param>  
<param-name>dname</param-name>  
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>  
</context-param>  
  
<servlet-mapping>  
<servlet-name>First</servlet-name>  
<url-pattern>/context</url-pattern>  
</servlet-mapping>  
  
</web-app>  

Output:-

ServletConfig example to get initialization parameter from web.xml



import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class First
 */
@WebServlet("/First")
public class First extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   
   ServletConfig config=getServletConfig();
   String driver=config.getInitParameter("driver");
   out.print("Driver is: "+driver);
       
   out.close();


}

}


Web.xml
<web-app>  
  
<servlet>  
<servlet-name>First</servlet-name>  
<servlet-class>First</servlet-class>  
  
<init-param>  
<param-name>driver</param-name>  
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>  
</init-param>  
  
</servlet>  
  
<servlet-mapping>  
<servlet-name>First</servlet-name>  
<url-pattern>/servlet1</url-pattern>  
</servlet-mapping>  
  
</web-app>  

Output:-

Create a servlet example using (Implementing) Servlet interface



import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class First
 */
@WebServlet("/First")
//public class First extends HttpServlet {
// private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
// protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// }

//}




public class First implements Servlet{

ServletConfig con = null;

public void init(ServletConfig con){
this.con = con;
System.out.println("I am in init");
}

public void service(ServletRequest req,ServletResponse res) throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.print("<html><body>");
out.print("<b>I am in Service</b>");
out.print("</html></body>");
}

public void destroy(){
System.out.println("I am in Destroy");
}
public ServletConfig getServletConfig(){return con;}
public String getServletInfo(){return "copyright 2007-1010";}
}


Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Abc</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>


Output:-

First Java Servlet Program



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;

/**
 * Servlet implementation class Hello
 */
@WebServlet("/Hello")
public class Hello extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<html><body>");
out.print("<b>I am in Service</b>");
out.print("</html></body>");

}

}

Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SecondServlet</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>


Output:-

Monday, 30 November 2015

MySQL Upadate PreparedStatement example

import java.sql.*;

public class First {

public static void main(String[] args) {
// TODO Auto-generated method stub
Connection con=null;
try{
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
PreparedStatement stmt = con.prepareStatement("update second set empid=? where rollno=?");
stmt.setInt(1,200);
stmt.setInt(2,1);
stmt.executeUpdate();
con.close();

}catch (SQLException e) {
e.printStackTrace();
}
}

}


output:-

Sunday, 29 November 2015

MySql PreparedStatement to insert rows second example

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class First {

public static void main(String[] args) {
// TODO Auto-generated method stub
try{
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
PreparedStatement stmt = con.prepareStatement("insert into second values (?,?)");
for(int i=0;i<20;i++){
stmt.setInt(1,i);
stmt.setInt(2,i);
stmt.executeUpdate();
}
con.close();
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


output:-

MySql PreparedStatment to insert rows


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class First {

public static void main(String[] args) {
// TODO Auto-generated method stub
Connection con=null;

try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
PreparedStatement stmt = con.prepareStatement("insert into first values (?)");
long t1 = System.currentTimeMillis();
for(int i=1;i<=10;i++){
stmt.setInt(1, i);
stmt.executeUpdate();
}
long t2 = System.currentTimeMillis();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}


Output:-

MySql setFetchSize in java



import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class First {

public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Connection con=null;
Statement stmt=null;
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
stmt = con.createStatement();
stmt.setFetchSize(1);
long t1 = System.currentTimeMillis();
ResultSet rs = stmt.executeQuery("select * from first");
while(rs.next()){
System.out.println(rs.getInt(1));
}
long t2 = System.currentTimeMillis();
//System.out.println("The time is");
System.out.println("The time is " +(t2-t1));
con.close();

} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}


output:-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
The time is 3

Time taken by MySql Driver to insert 49 values (int values into MYSQL DB)

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class First {

//@SuppressWarnings("null")
public static void main(String[] args) {

// TODO Auto-generated method stub

    try {
Connection con=null;
Statement stmt=null;
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
stmt=con.createStatement();
long t1 = System.currentTimeMillis();
for(int j=1;j<50;j++){
stmt.executeUpdate("insert into first values ("+j+")");
}
long t2 = System.currentTimeMillis();
System.out.println("Time is " +(t2-t1));
con.close();

} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}

}


Output:-
Time is 21



Friday, 27 November 2015

java program with MySQL to retrieve database records using select


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Second {

public static void main(String[] args) {
// TODO Auto-generated method stub
String query = "select * from persons";
Connection con = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test",
"root", "root");
stmt = con.createStatement();
ResultSet res = stmt.executeQuery(query);
//System.out.println("No.of Inserted Records == > " + i);

while(res.next()){
System.out.println(res.getInt(1));
System.out.println(res.getString(2));
System.out.println(res.getString(3));
System.out.println(res.getString(4));
System.out.println(res.getString(5));
System.out.println("================");

}

} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {

try {
stmt.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}

Output:-
1
sai
prasad
Kasturi Nagr
bangalore
================
2
Prasad
ram
Ram Nagar
Bangalore
================
3
Prasad
ram
Ram Nagar
Bangalore
================
4
babu
ram
Krishna Nagar
Bangalore
================
5
Chaya
Prasad
Banishankari
Bangalore
================
6
Krishna
Prasad babau
Banishankari stage
Mangalore
================

Java program to connect to MYSQL database and insert records


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Second {

public static void main(String[] args) {
// TODO Auto-generated method stub
String query = "insert into persons values ('6','Krishna','Prasad babau','Banishankari stage','Mangalore')";
Connection con = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test",
"root", "root");
stmt = con.createStatement();
int i = stmt.executeUpdate(query);
System.out.println("No.of Inserted Records == > " + i);

} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {

try {
stmt.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}



output:-

Monday, 23 November 2015

MYSQL DB Connectivity with java program


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Second {

public static void main(String[] args) {
// TODO Auto-generated method stub
String query = "insert into sample values('sai123')";
Connection con = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/prasad",
"root", "root");
stmt = con.createStatement();
int i = stmt.executeUpdate(query);
System.out.println("No.of Inserted Records == > " + i);

} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {

try {
stmt.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}

Output:-
No.of Inserted Records == > 1


Tuesday, 3 November 2015

Basic HTML

HTML

HTML stands for Hyper Text Markup Language developed to describe the web documents(web pages).It is described by HTML Tags and each tag describes different document content.

HTML Example:-

<!DOCTYPE html>
<html>
<head>
<title>My First Page</title>
</head>
<body>

<h1>My First Heading Line</h1>
<p>My First Paragraph</p>

</body>
</html>


Wednesday, 21 October 2015

Java Thread example two


public class First {

public static void main(String[] args) {
// TODO Auto-generated method stub
Second sec = new Second(1);
Thread t = new Thread(sec);
Thread t1 = new Thread(sec);
t.start();
t1.start();
}

}



public class Second extends Thread{
int avail=1;
int req;
Second(int i){
this.req=i;
}
public void run(){
synchronized(this){
if((avail>0)&&(req==1)){
System.out.println("Allocating the seat");
avail=req-1;
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
System.out.println("No Seats");
}
}
}
}


output:-
Allocating the seat
No Seats

Java Thread example

public class First {

public static void main(String[] args) {
// TODO Auto-generated method stub
Second obj = new Second("I am a Tea cup");
Second obj1 = new Second("I am a Coffee cup");
Thread t = new Thread(obj);
Thread t1 = new Thread(obj1);
t.start();
t1.start();
}
}

public class Second implements Runnable {
String str1;
Second(String str){
this.str1=str;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<10;i++){
System.out.println("The value of string is " +str1);
}
    }
}

output:-
The value of string is I am a Tea cup
The value of string is I am a Coffee cup
The value of string is I am a Tea cup
The value of string is I am a Coffee cup
The value of string is I am a Tea cup
The value of string is I am a Coffee cup
The value of string is I am a Tea cup
The value of string is I am a Coffee cup
The value of string is I am a Tea cup
The value of string is I am a Coffee cup
The value of string is I am a Coffee cup
The value of string is I am a Coffee cup
The value of string is I am a Coffee cup
The value of string is I am a Tea cup
The value of string is I am a Coffee cup
The value of string is I am a Tea cup
The value of string is I am a Coffee cup
The value of string is I am a Tea cup
The value of string is I am a Tea cup
The value of string is I am a Tea cup

Thread implementation Runnable in java example

import java.io.IOException;


public class First {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Second obj = new Second();
Thread t = new Thread(obj);
t.start();
System.in.read();
obj.i = true;
}

}



public class Second implements Runnable{
public boolean i = false;

@Override
public void run() {
// TODO Auto-generated method stub
for(int j=0;j<2000000;j++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("I am J " +j);
if(this.i)return;
}
}
}

output:-
I am J 0
I am J 1
I am J 2

I am J 3

Implementing threads in java


public class First {

public static void main(String[] args) {
// TODO Auto-generated method stub
Sec obj = new Sec();
Thread t = new Thread(obj);
t.start();
}

}


public class Sec extends Thread{

public void run(){
for(int i=0;i<10;i++){
System.out.println("The value of i is " +i);
}
}
}

output:-
The value of i is 0
The value of i is 1
The value of i is 2
The value of i is 3
The value of i is 4
The value of i is 5
The value of i is 6
The value of i is 7
The value of i is 8
The value of i is 9

Thread example in java (Java Threads)

import java.lang.Thread;
public class First {

public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Initial Thread demo example");
Thread t = Thread.currentThread();
System.out.println("The current thread is " +t);
System.out.println("Its name is " +t.getName());


}

}


output:-
Initial Thread demo example
The current thread is Thread[main,5,main]
Its name is main

Monday, 19 October 2015

Serialization example in java

import java.io.*;
public class First {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//Employee e;
Employee j[] = new Employee[10];
int k;
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
FileOutputStream fout = new FileOutputStream("file.txt");
ObjectOutputStream obj = new ObjectOutputStream(fout);
FileInputStream fin = new FileInputStream("file.txt");
ObjectInputStream obj1 = new ObjectInputStream(fin);
//k = Integer.parseInt(br.readLine());
//System.out.println("How many objects do you need to creat?");

for(int i=0;i<10;i++){
j[i]=new Employee(10,"Sai");
obj.writeObject(j[i]);
}
obj.close();

Employee e;
try {
while((e = (Employee)obj1.readObject())!= null){
e.display();

}
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
System.out.println("The value of Obj is");
e1.printStackTrace();
}

catch (EOFException e1) {
// TODO Auto-generated catch block
System.out.println("Reached EOF");
e1.printStackTrace();
}


}
}

import java.io.*;
public class Employee implements Serializable {
private int age;
private String name;
Employee(int i,String s){
this.age=i;
this.name=s;
}
void display(){
System.out.println("The values of the object are " +name +"\t" +age );
}
}

output:-

Writing into the file using FileWriter in java

import java.io.*;

public class FileRead{
public static void main(String args[])throws IOException{
String str = "This is Performance engineering blog";
FileWriter fw = new FileWriter("test.txt");
for(int i=0;i<str.length();i++){
fw.write(str.charAt(i));
}
fw.close();
}
}



output(file content):-
This is Performance engineering blog

Reading from a file using FileReader in java

import java.io.*;
public class First {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int ch;
FileReader fr = null;
try{
fr = new FileReader("test.txt");
}
catch(FileNotFoundException fe){
System.out.println("File Not found");
}
//finally{
// fr.close();
// }
while((ch=fr.read())!=-1){
System.out.println((char)ch);
}
fr.close();
}

}


Output:-
P
e
r
f
o
r
m
a
n
c
e
 
B
l
o
g




Text file contents:-
Performance Blog

Writing into the file using BufferedOutputStream in java

import java.io.*;
public class First {

public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub

DataInputStream dis = new DataInputStream(System.in);
FileOutputStream fout = new FileOutputStream("test.txt",true);
BufferedOutputStream bout = new BufferedOutputStream(fout,1024);
char ch;
while((ch = (char)dis.read())!='*'){
bout.write(ch);
}
bout.close();
}
}


output:-
Sr.Performance engineer
Sai Nagendra Bhavani Prasad
Java Profiles
APM Tools
*

Text file contents:-
Sr.Performance engineer
Sai Nagendra Bhavani Prasad
Java Profiles
APM Tools

Reading from the file using FileInputStream in java

import java.io.*;
public class First {

public static void main(String[] args) throws IOException,FileNotFoundException {
// TODO Auto-generated method stub
FileInputStream fin = new FileInputStream("test.txt");
int ch;
while((ch=fin.read())!=-1){
System.out.println("the values in the file are " +(char)ch);

}
}

}


output:-
the values in the file are B
the values in the file are a
the values in the file are t
the values in the file are t
the values in the file are i
the values in the file are p
the values in the file are a
the values in the file are t
the values in the file are i
the values in the file are
the values in the file are s
the values in the file are a
the values in the file are i
the values in the file are
the values in the file are N
the values in the file are a
the values in the file are g
the values in the file are e
the values in the file are n
the values in the file are d
the values in the file are r
the values in the file are a
the values in the file are
the values in the file are B
the values in the file are h
the values in the file are a
the values in the file are v
the values in the file are a
the values in the file are n
the values in the file are i
the values in the file are
the values in the file are P
the values in the file are r
the values in the file are a
the values in the file are s
the values in the file are a
the values in the file are d
the values in the file are

the values in the file are

the values in the file are S
the values in the file are r
the values in the file are .
the values in the file are P
the values in the file are e
the values in the file are r
the values in the file are f
the values in the file are o
the values in the file are r
the values in the file are m
the values in the file are a
the values in the file are n
the values in the file are c
the values in the file are e
the values in the file are
the values in the file are E
the values in the file are n
the values in the file are g
the values in the file are i
the values in the file are n
the values in the file are e
the values in the file are e
the values in the file are r
the values in the file are

the values in the file are

writing data into the file usinf FileOutputStream in java

import java.io.*;
public class First {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
DataInputStream dis = new DataInputStream(System.in);
FileOutputStream fout = new FileOutputStream("test.txt");
char ch;
while((ch = (char)dis.read())!='*'){
fout.write(ch);
}
fout.close();
}

}


Output:-
q
w
e
r
t
y
u
i
*

In text file:-
q
w
e
r
t
y
u
i

Sorting using Arrays.sort()

import java.util.*;
import java.io.*;
public class First {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
First oj = new First();
int arry[] = new int[10];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for(int i=0;i<10;i++){
arry[i] = Integer.parseInt(br.readLine());
}
oj.display(arry);
Arrays.sort(arry);
System.out.println("After sorting the values");
oj.display(arry);

}

void display(int arr[]){
for(int k : arr){
System.out.println("The value of array is " +k);
}

}

}


output:-
11
33
55
77
33
21
54
00
56
40
The value of array is 11
The value of array is 33
The value of array is 55
The value of array is 77
The value of array is 33
The value of array is 21
The value of array is 54
The value of array is 0
The value of array is 56
The value of array is 40
After sorting the values
The value of array is 0
The value of array is 11
The value of array is 21
The value of array is 33
The value of array is 33
The value of array is 40
The value of array is 54
The value of array is 55
The value of array is 56
The value of array is 77

Thursday, 15 October 2015

Arraylist example in java

import java.util.*;
public class First {

public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<String> obj = new ArrayList<String>();
obj.add("India");
obj.add("Bombay");
obj.add("Test");
Iterator it = obj.iterator();
while(it.hasNext()){
System.out.println("The value of arraylist is " +it.next());

}
}

}

output:-
The value of arraylist is India
The value of arraylist is Bombay
The value of arraylist is Test

HashMap example in java

import java.util.*;
public class First {

public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap<String,Integer> obj = new HashMap<String,Integer>();
obj.put("battipati", 1);
obj.put("Sai", 2);
obj.put("Nagendra", 3);
obj.put("Bhavani", 4);
obj.put("Prasad",5);
Iterator it = obj.entrySet().iterator();
while(it.hasNext()){
Map.Entry a = (Map.Entry) it.next();
System.out.println("The values are  " +a);
System.out.println(a.getKey() + " = " + a.getValue());
}
}
}


output:-
The values are  Bhavani=4
Bhavani = 4
The values are  Prasad=5
Prasad = 5
The values are  battipati=1
battipati = 1
The values are  Nagendra=3
Nagendra = 3
The values are  Sai=2
Sai = 2

Stack example in java

import java.util.*;
public class First {

public static void main(String[] args) {
// TODO Auto-generated method stub
Stack<String> st = new Stack<String>();
st.add("India");
st.add("Nepal");
st.add("Sri Lanka");
st.add("Country");
for (String s : st){
System.out.println("the value of st is " +s);
}
boolean i = st.empty();
System.out.println("The value of i is " +i);
String s1 = st.peek();
System.out.println("the value of top most element is " +s1);
String s2 = st.pop();
System.out.println("the value of top most element is " +s2);
int j = st.search("Country");
System.out.println("the value of j is " +j);
String s3 = st.peek();
System.out.println("the value of top most element is " +s3);
}
}


output:-
the value of st is India
the value of st is Nepal
the value of st is Sri Lanka
the value of st is Country
The value of i is false
the value of top most element is Country
the value of top most element is Country
the value of j is -1
the value of top most element is Sri Lanka


Vector example in java

import java.util.*;
public class First {

public static void main(String[] args) {
// TODO Auto-generated method stub
Vector<String> obj = new Vector<String>();
obj.add("India");
obj.add("Digital");
obj.add("Message");
obj.add("Super");
Iterator it = obj.iterator();
while(it.hasNext()){
System.out.println("the values are " +it.next());

}

}
}

output:-
the values are India
the values are Digital
the values are Message
the values are Super

LinkedList example in java

import java.util.*;


public class First {

public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedList<Integer> obj = new LinkedList<Integer>();
obj.add(10);
obj.add(12);
obj.add(13);
obj.add(23);
obj.add(13);
Iterator it = obj.iterator();
while(it.hasNext()){
System.out.println("The value is  " +it.next());
}
obj.remove(2);
System.out.println("The value is  " +obj);
int l = obj.size();
System.out.println("the value of l is " +l);
}
}


output:-
The value is  10
The value is  12
The value is  13
The value is  23
The value is  13
The value is  [10, 12, 23, 13]
the value of l is 4

LinkedHashSet example in java

import java.util.*;


public class First {

public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedHashSet<String> hs = new LinkedHashSet<String>();
hs.add("Digital");
hs.add("India");
System.out.println("The value of hs is " +hs);
for(String s : hs){
System.out.println("the value of s is " +s);
}
Iterator<String> it = hs.iterator();
while(it.hasNext()){
System.out.println("the value through iterator is " +(String)it.next());
}
}
}


output:-
The value of hs is [Digital, India]
the value of s is Digital
the value of s is India
the value through iterator is Digital
the value through iterator is India

Hashset example in java (using for-each loop)

import java.util.*;
public class First {

public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet<String> hs = new HashSet<String>();
hs.add("Digital");
hs.add("India");
hs.add("Hello");
hs.add("World");
for(String st: hs){
System.out.println("The string value is " +st);
}

}

}


output:-
The string value is Hello
The string value is Digital
The string value is World
The string value is India

HashSet example in java

import java.util.*;
public class First {

public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet<String> hs = new HashSet<String>();
hs.add("India");
hs.add("Amrica");
hs.add("Singapore");
hs.add("Nepal");
System.out.println("The value of HashSet is " +hs);
Iterator<String> it = hs.iterator();
while(it.hasNext()){
String s = it.next();
System.out.println("the value is " +s);
}
}

}

output:-
The value of HashSet is [Amrica, Singapore, Nepal, India]
the value is Amrica
the value is Singapore
the value is Nepal
the value is India

Wednesday, 14 October 2015

Array example in java


public class First {

public static void main(String[] args) {
// TODO Auto-generated method stub
Employee array[] = new Employee[5];
for(int i=0;i<5;i++){
array[i]=new Employee(i,"Sai"+i);
System.out.println("The array values are " +array[i].age +"\t" +array[i].name );
}
}

}



public class Employee {
int age;
String name;
Employee(int i,String s){
age=i;
name=s;
}
}


output:-
The array values are 0 Sai0
The array values are 1 Sai1
The array values are 2 Sai2
The array values are 3 Sai3
The array values are 4 Sai4

Wrapper Class examples in java

import java.io.*;

public class First {

public static void main(String[] args) {
// TODO Auto-generated method stub
Byte obj = new Byte((byte) 10);
Byte obj1 = new Byte("10");
Character obj2= new Character('A');
byte j=obj1.byteValue();
byte i=obj.byteValue();
int k = obj.compareTo(obj1);
System.out.println("The value of K is " +k);
System.out.println("The value of i is " +i);
System.out.println("The value of j is " +j);
char ch = obj2.charValue();
System.out.println("The value of char is " +ch);
Character obj3 = Character.valueOf(ch);
System.out.println("The value of char is " +obj3);


}
}


output:-
The value of K is 0
The value of i is 10
The value of j is 10
The value of char is A
The value of char is A