Friday, March 24, 2006 

Program to reverse a string

/*This is a program to reverse a given string that is taken from keyboard as input*/
#include<stdio.h>
#define length 20
main(){
int a[length];
int c=getchar();
int i=0,k=0;
while((c!='\n'))
{
a[i]=c;
i++;
c=getchar();
}
for(k=i-1;k>=0;k--)
printf("%c",a[k]);

}

Tuesday, March 14, 2006 

XML Parser in Java

// Team 1
// XML Parser

package book;
import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.*;
import java.util.*;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

class XMLParser
{
public Hashtable getBooks()
{
Hashtable listBooks= new Hashtable();;
try
{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("e:/input.xml"));

// normalize text representation
doc.getDocumentElement ().normalize ();
NodeList totallistBooks = doc.getElementsByTagName("books");
int totalBooks = totallistBooks.getLength();


for(int s=0; s<totallistBooks.getLength() ; s++){


Node firstPersonNode = totallistBooks.item(s);
if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){


Element firstPersonElement = (Element)firstPersonNode;

//-------
NodeList firstNameList = firstPersonElement.getElementsByTagName("bookId");
Element firstNameElement = (Element)firstNameList.item(0);

NodeList textFNList = firstNameElement.getChildNodes();

NodeList lastNameList = firstPersonElement.getElementsByTagName("bookName");
Element lastNameElement = (Element)lastNameList.item(0);

NodeList textLNList = lastNameElement.getChildNodes();


//inserting into hashtable key value pairs

listBooks.put(((Node)textLNList.item(0)).getNodeValue().trim(),((Node)textFNList.item(0)).getNodeValue().trim());


}//end of if clause



}//end of for loop with s var




}
catch (SAXParseException err)
{
System.out.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
System.out.println(" " + err.getMessage ());

}
catch (SAXException e)
{
Exception x = e.getException ();
((x == null) ? e : x).printStackTrace ();

}
catch (Throwable t)
{
t.printStackTrace ();
}

return listBooks;
}
}

Sunday, March 12, 2006 

Algorithms Used in Garbage collection

Post-HotSpot JVM:
The Exact VM (JVM 1.2.2) introduced exact garbage collection. Sun then improved the exact GC design in JVM 1.3 and renamed it generational GC. Java HotSpot VM 1.3.1's GC is fully accurate, guaranteeing that:

1)You can reliably reclaim all inaccessible objects' memory
2)You can relocate all objects to compact memory, eliminating object memory fragmentation

Three types of collection algorithms:
• Copy/scavenge collection
• Mark-compact collection
• Incremental (train) collection

The HotSpot JVM provides three GC algorithms, each tuned for a specific type of collection within a specific generation. The copy collection quickly cleans up short-lived objects in the new generation heap. The mark-compact algorithm employs a slower, more robust technique to collect longer-lived objects in the old generation heap. The incremental algorithm attempts to improve old generation collection by performing robust GC while minimizing pauses.

Copy/scavenge collection:
Using the copy algorithm, the JVM reclaims most objects in the new generation object space simply by making small scavenges . Longer-lived objects are ultimately copied, or tenured, into the old object space.

Mark-compact collection:
As more objects become tenured, the old object space begins to reach maximum occupancy. The mark-compact algorithm, used to collect objects in the old object space, has different requirements than the copy collection algorithm used in the new object space.

The mark-compact algorithm first scans all objects, marking all reachable objects. It then compacts all remaining gaps of dead objects. The mark-compact algorithm occupies more time than the copy collection algorithm; however, it requires less memory and eliminates memory fragmentation.

Incremental (train) collection:
The new generations copy/scavenge and the old generation mark-compact algorithms can't eliminate all JVM pauses. Such pauses are proportional to the number of live objects. To address the need for pause less GC, the Hotspot JVM also offers incremental, or train, collection.

Incremental collection breaks up old object collection pauses into many tiny pauses even with large object areas. Instead of just a new and an old generation, this algorithm has a middle generation comprising many small spaces. There is some overhead associated with incremental collection; you might see as much as a 10-percent speed degradation.

Saturday, March 11, 2006 

Lower Case to Uppre Case Conversion

//PROGRAM FOR PRINTING CHARACTER IN UPPER CASE GIVEN THE CHARACTER IN LOWER CASE
//AUTHOR:SIVAPHANINDRA.VEMURI

import java.io.*; /*IMPORTING THE EXISTING CLASSES*/
class Task1d /*CLASS NAMED Task1d*/
{
public static void main(String[] args)throws IOException /*MAIN FUNCTION WHICH
THROWS AN IOEXCEPTION IF SATISFIES THE CONDITION*/
{
char c; //FOR STORING THE READ CHARCATER FROM THE USER
BufferedReader br=new BufferedReader (new InputStreamReader(System.in));/*BUFFERED READER FOR TAKING THE INPUT FROM THE USER*/
System.out.println("Enter Character To Quit Press 'q'");
do
{
c=(char)br.read(); /*READ FUNCTION TO READ CHARACTER WITH "br" AS AN OBJECT OF BEFFEREDREADER*/
if(c==10||c==13) /*TO ELIMINATE THE SPACE AND ENTER UNNECESSARY CHARACTERS*/
{}
else if(c=='q')
return;
else
System.out.println("UPPER CASE IS:"+(char)(c-32)); /*CONVERTING THE GIVEN CHARACTER INTO UPPER CASE*/
}while(c!='q'); /*REPEAT UNTIL GIVEN CHARACTER IS NOT EQUAL TO 'q'*/
}
}

 

PRINTING THE NON-PRIMES

//PROGRAM FOR PRINTING THE NON-PRIMES INTO A FILE
//AUTHOR:SIVAPHANINDRA.VEMURI

import java.io.*; /*IMPORTING SECTION*/
class Task1e1 /* DECLARING A CLASS NAMED Task1e1*/
{
public static void main(String args[]) /*MAIN FUNCTION*/
{
FileOutputStream file_out=null; /* CREATING STREAMS FOR DIRECTING IT TO THE OUTPUT FILE*/
PrintStream pno=null;
try{
file_out=new FileOutputStream("non-primes.txt",false);
pno = new PrintStream(file_out,true);
}catch(FileNotFoundException e){ /* TO CATCH EXCEPTIONS */
System.out.println();
return;
}
catch(IOException e){
System.out.println("IOEXCEPTION");
return;
}
int num=2;
do
{
for(int i=2;i <num;i++)
{
if((num%i)==0) /*CHECKING FOR NON PRIMES*/
{

pno.println(num); /*FOR WRITING TO THE FILE */
pno.println();
break;
}
}
num++;
}while(num!=500); /*TO PRINT ALL THE NON PRIMES BETWEEN 1-500*/
}
}

 

PRIME FACTORS OF ALL NON-PRIMES BELOW 500

/*TO PRINT THE PRIME FACTORS OF ALL NON-PRIMES BELOW 500*/
/*AUTHOR:SIVAPHANINDRA.VEMURI*/

import java.io.*; /*IMPORTING SECTION*/
class Task1e2 /* DECLARING A CLASS NAMED Task1e2*/
{
public static void main(String args[])throws IOException /*MAIN METHOD THROWING IOEXCEPTION*/
{
int i,j=0;
int a[]=new int [500]; /*ALLOCATING MEMORY FOR ARRAY A OF 500 SIZE*/
String fp; /* CREATING AN OBJECT FOR STRING*/
BufferedReader br=new BufferedReader (new FileReader("non-primes.txt"));
while((fp=br.readLine())!=null)
{
a[j]=Integer.parseInt(fp);
j++;
fp=br.readLine();
}
br.close();
PrintStream ps= new PrintStream(new FileOutputStream ("non-primes.txt"),true); /*CREATING AN OBJECT FOR PRINT STRAM*/
for(i=0;i {
ps.print(a[i]+":");
int prmfact = 2;
while (a[i] > 1)
{
if (a[i] % prmfact == 0)
{
ps.print(prmfact+"*"); /*PRINITING THE PRIMEFACTOR TO THE FILE*/
a[i] = a[i] / prmfact;
}
else
{
prmfact = prmfact + 1;
}
if (prmfact * prmfact > a[i])
{
ps.print(a[i]+" ");
ps.println();
break;
}
}
ps.println();
}

}
}

Friday, March 10, 2006 

What is Garbage Collection & Why is Garbage Collection?

The name garbage collection implies that objects no longer needed by the program are "garbage" and can be thrown away. When an object is no longer referenced by the program, the heap space it occupies can be recycled so that the space is made available for new objects. The garbage collector must somehow determine which objects are no longer referenced by the program and make available the heap space occupied by such unreferenced objects. In the process of freeing unreferenced objects, the garbage collector must run any finalizers of objects being freed.

In addition to freeing unreferenced objects, a garbage collector may also combat heap fragmentation. Heap fragmentation occurs through the course of normal program execution. New objects are allocated, and unreferenced objects are freed such that free portions of heap memory are left in between portions occupied by live objects. Requests to allocate new objects may have to be filled by extending the size of the heap even though there is enough total unused space in the existing heap. This will happen if there is not enough contiguous free heap space available into which the new object will fit.

Garbage collection relieves you from the burden of freeing allocated memory. Knowing when to explicitly free allocated memory can be very tricky. Giving this job to the Java virtual machine has several advantages. First, it can make you more productive. When programming in non-garbage-collected languages you can spend many hours on elusive memory problem. A second advantage of garbage collection is that it helps ensure program integrity. Garbage collection is an important part of Java's security strategy. Java programmers are unable to accidentally (or purposely) crash the Java virtual machine by incorrectly freeing memory.

A potential disadvantage of a garbage-collected heap is that it adds an overhead that can affect program performance. The Java virtual machine has to keep track of which objects are being referenced by the executing program, and finalize and free unreferenced objects on the fly. This activity will likely require more CPU time than would have been required if the program explicitly freed unnecessary memory. In addition, programmers in a garbage-collected environment have less control over the scheduling of CPU time devoted to freeing objects that are no longer needed.

 

Public static void main (String args[])

The public keyword is an access specifier, which allows the programmer to control the visibility of class members. When a class member is preceded by public, then that member may be accessed by code outside the class in which it is declared.In this case, main( ) must be declared as public, since it must be called by code outside of its class when the program is started. The keyword static allows main( ) to be called without having to instantiate a particular instance of the class. This is necessary since main( ) is called by the Java interpreter before any objects are made. The keyword void simply tells the compiler that main( ) does not return a value. As you will see, methods may also return values.
As stated, main( ) is the method called when a Java application begins. Keep in mind that Java is case-sensitive. Thus, Main is different from main. It is important to understand that the Java compiler will compile classes that do not contain a main( ) method. But the Java interpreter has no way to run these classes. So, if you had typed Main instead of main, the compiler would still compile your program. However, the Java interpreter would report an error because it would be unable to find the main( ) method.
Any information that you need to pass to a method is received by variables specified within the set of parentheses that follow the name of the method. These variables are called parameters. If there are no parameters required for a given method, you still need to include the empty parentheses. In main( ), there is only one parameter, albeit a complicated one. String args[ ] declares a parameter named args, which is an array of instances of the class String. Objects of type String store character strings. In this case, args receives any command-line arguments present when the program is executed.

Thursday, March 09, 2006 

Delete and Update values in MySql Using Java

/* A Sample program to Delete and Update values from and to a table Using Java*/

import java.sql.*;
import java.util.*;

public class DeleteUpdate
{
public static void main(String args[]) {
try {
/* Test loading driver */

Hashtable members = new Hashtable();

// Load the JDBC driver
Class.forName("com.mysql.jdbc.Driver");

// Establish a connection
String url = "jdbc:mysql://localhost/test"; //here "test" is the name of the database in use
Connection connection = DriverManager.getConnection( url, "root", "kris" ); //root and password is name


/* Create a statement*/
Statement statement = connection.createStatement();


/*process to insert values into database test where phani is the tablename*/


String Delete = "delete from phani where name like '" + "Vemuri" + "'";
int j = statement.executeUpdate(Delete);

System.out.println("--------Values Deleted from table Successfully----------"+j);

/*process to Update values in your database test where phani is the tablename */

String Update = "update phani set name = '" + "aaaaaaa" +"' where ID = '" + "1000" +"'";
int updateCount = statement.executeUpdate(Update);

System.out.println("--------Values Updated Successfully----------"+ updateCount);



}
catch( Exception x ) {
x.printStackTrace();
}
}
}

/* Prerequisites you need to have Mysql installed in your system with a data base named "test"
and with username "root" and password "name"*/
/* Javac DeleteUpdate.java */
/* Java DeleteUpdate */

 

Insert values into table Using Java

/* A Sample program to Insert values to a table Using Java*/

import java.sql.*;
import java.util.*;

public class Insert
{
public static void main(String args[]) {
try {
/* Test loading driver */

Hashtable members = new Hashtable();

// Load the JDBC driver
Class.forName("com.mysql.jdbc.Driver");

// Establish a connection
String url = "jdbc:mysql://localhost/test"; //here "test" is the name of the database in use
Connection connection = DriverManager.getConnection( url, "root", "kris" ); //root and password is name


/* Create a statement*/
Statement statement = connection.createStatement();


/* Execute a statement for selecting values from database here details is the tables name in database "test"*/
String name[]={"Siva","Phanindra","Vemuri"};
String ID[]={"1000","9000","1232"};

/*process to insert values into database*/

for(int i=0;i<name.length;i++){
String INSERT = "insert into phani(name,ID)values ('" + name[i] + "','" +
ID[i] + "')";
int j = statement.executeUpdate(INSERT);
}

System.out.println("--------Values Inserted into table Successfully----------");


}
catch( Exception x ) {
x.printStackTrace();
}
}
}

/* Prerequisites you need to have Mysql installed in your system with a data base named "test"
and with username "root" and password "name"*/
/* Javac Insert.java */
/* Java Insert */

Wednesday, March 08, 2006 

Program to Retrive values from Mysql Using Java

/* A Sample program to connect to Mysql Using Java*/

import java.sql.*;

public class Test
{
public static void main(String args[]) {
try {
/* Test loading driver */

Hashtable members = new Hashtable();
String driver = "com.mysql.jdbc.Driver";
System.out.println( "----->loading driver:------->" );
Class.forName( driver );

/* Test the connection Here test is the name of the database you want to connect to*/
String url = "jdbc:mysql://localhost/test";

/*root is the user name and kris is the password of MYSql*/
DriverManager.getConnection( url, "root", "kris" );
System.out.println("connection established");

/* Create a statement*/
Statement statement = connection.createStatement();


/* Execute a statement for selecting values from database here details is the tables name in database "test"*/
ResultSet resultSet = statement.executeQuery("select * from details");
while (resultSet.next()){
members.put(resultSet.getString(1),resultSet.getString(2));
System.out.println(resultSet.getString(1) + "\t" +
resultSet.getString(2) );

}
catch( Exception x ) {
x.printStackTrace();
}
}
}

Tuesday, March 07, 2006 

Java Mysql Connectivity

Download mysql-connector-java-3.1.12.zip from www.mysql.com Extart the files and copy "mysql-connector-java-3.0.8-stable-bin.jar" and in C:\j2sdk1.4.2_04\jre\lib create a folder with name "java-mysql-connector" and place the jar file in it, next you need to set the Classpath You should also add the complete path to this JAR file in your CLASSPATH environment variable. In case if you don't know how to do that, go to Start -> Settings -> Control Panel -> System -> Advanced (tab) -> Environment Variables. Double-click 'CLASSPATH' if it is already listed there or click 'New' to create one with the name of 'CLASSPATH'. If you already had a 'CLASSPATH environment variable listed, simply type in (or paste) the complete path including file name in the window that opens up *at the end of* existing CLASSPATH values. If you are creating a new 'CLASSPATH' environment variable then simple enter '.;' and then append the complete path to Connector/J's JAR file.Note: The CLASSPATH variable contains a list of semi-colon separated folders and JAR files where JVM will search for Java class files. You should always separate paths with semi-colon (;) so that JVM can understand where one path ends and next one begins. Also keep in mind that in CLASSPATH variable paths, the first path is always '.' (single dot) which means current folder, so that JVM starts the search for Java class files from the current folder.

Monday, March 06, 2006 

Program to Delete Files in a Given Directory

import java.io.File;

/**
* Program to delete files in a directory.
*
* @author vsphanindra
*/


public class DeleteDirectory {

public static void function (File dir,String a){
String[] info = dir.list();
for (int i = 0; i < info.length; i++) {
File n = new File(a + dir.separator + info[i]);
if (!n.isFile())
continue;
System.out.println("Removed:" + n.getPath());
if (!n.delete())
System.err.println("Couldn't remove:" + n.getPath());
}
}
public static void main(String[] argv) {
if (argv.length != 1) {
System.err.println("Enter in this format :::-------- java Empty DeleteDirectory and its path ");
System.exit(1);
}

File dir = new File(argv[0]);
if (!dir.exists()) {
System.out.println(argv[0] + " Directory does not exist");
return;
}
function(dir,argv[0]);

}
}

/* javac DeleteDirectory.java */
/* java DeleteDirectory pathofthedirectory */

Sunday, March 05, 2006 

Program to Write to a file

/* * FileOutputDemo * Using PrintStream classes * */

/* This program writes a given string to file named output.txt */
import java.io.*;
class FileOutputDemo
{
public static void main(String args[])
{
String a = "phanindra";
try {
FileOutputStream out = new FileOutputStream("output.txt");
PrintStream p = new PrintStream( out );
p.println (a);
p.close();
}
catch (Exception e) {
System.err.println ("Error writing to file");
}
}
}

Saturday, March 04, 2006 

Program to Rename Files in a given Directory

import java.io.File;

/**
* Program to rename the files in a given Floder
*
* @author vsphanindra
*/
public class Rename {
public static void main(String[] argv) {
if (argv.length != 1) { // no progname in argv[0]
System.err.println("usage: Empty dirname");
System.exit(1);
}

File dir = new File(argv[0]);
if (!dir.exists()) {
System.out.println(argv[0] + " does not exist");
return;
}
String[] info = dir.list();
for (int i = 0; i < info.length; i++) {
File n = new File(argv[0] + dir.separator + info[i]);
/* this is the place where we will change the name of the file's
with the extension we wishin the given folder*/
String str= argv[0] + dir.separator+"Scene"+i+".jpg";
n.renameTo(new File(str));
}
}
}

/* javac Rename.java */

/*java Rename "absolute path of the directory which you want to change the file name in" */

About me

  • I'm phanindra
  • From Hyderabad, Andhra Pradesh, India
  • An Alumini of JNTU Hyd into happening IT industry...
My profile

Visitors
Bloggeries Blog Directory BlogRankings.com singapore blog directory blog search directory
Google
 
Web conceptoftheday.blospot.com