Java programs for beginners, list of programs in java on various topics, interesting programs in java. Java programs on various topics
Friday, June 12, 2015
Monday, April 14, 2014
FileInputStream Demo in Java
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
*
* @author MALAR-KSP
*/
public class FileInputStreamDemo {
public static void readFileContents(String location,String fileName)
{
if(location!=null&&fileName!=null)
{
FileInputStream fis= null;
try {
String file = location+File.separator+fileName;
fis = new FileInputStream(file);
BufferedInputStream bis= new BufferedInputStream(fis);
int readContent = 0;
while((readContent=bis.read())!=-1)
{
System.out.print((char)readContent);
}
System.out.println("\nRead Completed....");
} catch (FileNotFoundException ex) {
System.out.println(""+ex.toString());
} catch (IOException ex) {
System.out.println(""+ex.toString());
} finally {
try {
fis.close();
} catch (IOException ex) {
System.out.println(""+ex.toString());
}
}
}
}
public static void main(String[] args) {
String location="K:";
String fileName = "TestFile.doc";
readFileContents(location, fileName);
}
}
FileOutputStream Example in Java
Whenever data needs to be written into file dont just write using fileoutputstream. Use BufferedOutputStream
to increase the efficiency and reduce the performance complexity.
#Whenever data is written into file using any outputstream we need to flush the stream and close the stream properly. Otherwise it will lead to memory leak and data writing gets failed.
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
/**
*
* @author Saravanan K
*/
public class FileOutputStreamDemo{
public static void createAndWriteIntoFile(String fileLocation,String fileName,String content)
{
if(fileLocation!=null&&fileName!=null)
{
FileOutputStream fos = null;
try {
String file = fileLocation+File.separator+fileName;
fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bos.write(content.getBytes());
bos.flush();
bos.close();
} catch (FileNotFoundException ex) {
System.out.println(""+ex.toString());
} catch (IOException ex) {
System.out.println(""+ex.toString()); }
finally {
try {
fos.close();
} catch (IOException ex) {
System.out.println(""+ex.toString());
}
}
} else {
System.out.println("Sorry.Filename cannot be empty...");
}
System.out.println("File wrote success");
}
public static void main(String[] args) {
String location="K:";
String fileName = "TestFile.doc";
String content = "Hi this is FileOutputStreamDemo...";
createAndWriteIntoFile(location, fileName, content);
}
}
Wednesday, March 19, 2014
Remove Numbers in String - Java Program
public String removeNumbersInString(String str) {
String temp = "";
String regexp = "^[0-9]";
Pattern pattern = Pattern.compile(regexp);
Matcher matcher;
if(!str.isEmpty()){
for (int i = 0; i < str.length(); i++) {
matcher = pattern.matcher(str.charAt(i) + "");
if (!matcher.matches()) {
temp = temp + str.charAt(i) + "";
}
}}
System.out.println("" + temp);
return temp;
}
Remove String in Numbers-Java Program
public String removeStringInNumbers(String str) {
String temp = "";
String regexp = "^[a-zA-Z]";
Pattern pattern = Pattern.compile(regexp);
Matcher matcher;
if(!str.isEmpty()){
for (int i = 0; i < str.length(); i++) {
matcher = pattern.matcher(str.charAt(i) + "");
if (!matcher.matches()) {
temp = temp + str.charAt(i) + "";
}
}}
System.out.println("" + temp);
return temp;
}
Saturday, March 1, 2014
Write an example that counts the number of times a particular character, such as e, appears in a file. The character can be specified at the command line.
import java.io.BufferedInputStream;
import java.io.FileInputStream;
class GetOccurrences{
public static void main(String args[])
{
try{
FileInputStream fis=new FileInputStream("C:\\Users\\SAN-MCA-ME-MTECH-MS\\Documents\\SAN\\Temp.txt");
BufferedInputStream bis=new BufferedInputStream(fis);
int i;
int occurs=0;
while((i=bis.read())!=-1)
{
char a=(char)i;
if(a==args[0].charAt(0))
{
occurs++;
}
}
System.out.println("Letter e is "+occurs+" of times repeated in the file");
}catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
Saturday, February 23, 2013
Java Connect to Oracle XE Database
In order to connect to oracle database you need to add ojdbc14.jar file in your eclipse project as a external jar file.... Download from web.
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class OracleConnect {
/**
* @param args
*/
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","saravanan","saravanan");
System.out.println("Connected Successfully To Oracle");
Statement stmt;
ResultSet rs;
stmt=con.createStatement();
rs=stmt.executeQuery("select * from saran");
while(rs.next())
{
System.out.println(rs.getString("empname")+"--"+rs.getInt("salary"));
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
Simple java program for connecting to DATABASE(mysql)
In order to connect to database you need to add mysql-connector-java-5.1.22.jar file in your eclipse project as a external jar file....
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SqlSample {
/**
* @param args
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws SQLException
*/
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
// TODO Auto-generated method stub
Connection con;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/saran","root","root");
Statement stmt;
ResultSet rs;
stmt=con.createStatement();
rs=stmt.executeQuery("select * from employee;");
while(rs.next())
{
System.out.println(rs.getString("empname")+rs.getInt("salary"));
}
}
}
Servlet Program for Retrieving data from Table
In order to connect to database you need to add mysql-connector-java-5.1.22.jar file in your eclipse project as a external jar file....
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class HelloServlet
*/
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public
class HelloServlet extends HttpServlet {
public void doGet (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<head><title>Students List</title></head>");
out.println("<body>");
try {
// The newInstance() call is a work around for some
// broken Java implementations
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch (Exception E) {
out.println("Unable to load driver.");
E.printStackTrace();
}
out.println("<br><center><p style=color:purple;font-size:30px;>STUDENTS DATABASE</p></center><hr>");
try {
Connection Conn =
DriverManager.getConnection("jdbc:mysql://localhost/saran","root","root");
// Do something with the Connection
Statement Stmt = Conn.createStatement();
ResultSet RS = Stmt.executeQuery("SELECT * from student");
out.println("<center><table border='1' style=color:purple;font-size:20px;><th>Name</th><th>Area</th><th>Course</th>");
while (RS.next()) {
out.println("<tr><td>"+RS.getString("name")+"<td>"+RS.getString("area")+"<td>"+RS.getString("course")+"</td></tr>");
}
out.println("</table></center>");
out.println("<center><form action='index.htm'><input type='submit' value='Home'></form></center>");
// Clean up after ourselves
RS.close();
Stmt.close();
Conn.close();
}
catch (SQLException E) {
}
out.println("</body></html>");
}
}
Friday, February 22, 2013
Compare Two Integer Arrays
This program will compare two integer arrays and return a result number of matching numbers in those arrays :
public void arrayMatcher(int a[], int b[])
{
int count=0;
for(int i=0;i<a.length;i++)
{
for(int j=0;j<b.length;j++)
{
if((a[i])==(b[j]))
{
count++;
}
}
}
System.out.println(count+" numbers matches in two arrays");
}
CONTENT WARNING:This is my own program.. It is for Educational purposes only. Please do not republish or reproduce with another name in online.
public void arrayMatcher(int a[], int b[])
{
int count=0;
for(int i=0;i<a.length;i++)
{
for(int j=0;j<b.length;j++)
{
if((a[i])==(b[j]))
{
count++;
}
}
}
System.out.println(count+" numbers matches in two arrays");
}
CONTENT WARNING:This is my own program.. It is for Educational purposes only. Please do not republish or reproduce with another name in online.
Sort Letters in a String Object
public void doSorting(String str)
{
char array[]=str.toCharArray();
char temp;
System.out.print("Given name :");
for(int i=0;i<array.length;i++)
{
System.out.print(array[i]);
}
System.out.println();
for(int i=0;i<array.length;i++)
{
for(int j=0;j<i;j++)
{
if(array[i]<array[j])
{
temp=array[j];
array[j]=array[i];
array[i]=temp;
}
}
}
CONTENT WARNING:This is my own program.. It is for Educational purposes only. Please do not republish or reproduce with another name in online.
{
char array[]=str.toCharArray();
char temp;
System.out.print("Given name :");
for(int i=0;i<array.length;i++)
{
System.out.print(array[i]);
}
System.out.println();
for(int i=0;i<array.length;i++)
{
for(int j=0;j<i;j++)
{
if(array[i]<array[j])
{
temp=array[j];
array[j]=array[i];
array[i]=temp;
}
}
}
CONTENT WARNING:This is my own program.. It is for Educational purposes only. Please do not republish or reproduce with another name in online.
Reverse String in JAVA
This is the method which will reverse the given STRING :
public void myOwnstringReversing(String str)
{
for(int i=str.length()-1;i>=0;i--)
{
System.out.print(str.charAt(i));
}
}
CONTENT WARNING:
This is my own program.. It is for Educational purposes only. Anyone do not republish in your website will be punished offensively.
Wednesday, December 19, 2012
Thread Program four in Java
public class Thread_Demo extends Thread{
public void run(){
System.out.println("Some text");
}
public static void main(String[] args) throws InterruptedException{
Thread_Demo t=new Thread_Demo();
Thread_Demo td1=new Thread_Demo();
t.start();
System.out.println("ISALIVE :"+t.isAlive());
t.sleep(500);
System.out.println("ISALIVE :"+t.isAlive());
//t.destroy();
t.resume();
System.out.println("ISALIVE :"+t.isAlive());
}
}
Thread Program three in Java
What is out put?
public class Thread_Demo extends Thread{
public void run(){
System.out.println("Some text");
}
public static void main(String[] args) throws InterruptedException {
Thread_Demo t=new Thread_Demo();
Thread_Demo td1=new Thread_Demo();
t.run();
System.out.println("ISALIVE :"+t.isAlive());
t.sleep(500);
System.out.println("ISALIVE :"+t.isAlive());
t.destroy();
System.out.println("ISALIVE :"+t.isAlive());
}
}
Thread Program Two in Java
What is output?
public class Thread_Demo extends Thread{
public void run(){
System.out.println("Some text");
}
public static void main(String[] args) throws InterruptedException {
Thread_Demo t=new Thread_Demo();
Thread_Demo td1=new Thread_Demo();
t.start();
System.out.println("ISALIVE :"+t.isAlive());
t.sleep(500);
System.out.println("ISALIVE :"+t.isAlive());
t.destroy();
System.out.println("ISALIVE :"+t.isAlive());
}
}
public class Thread_Demo extends Thread{
public void run(){
System.out.println("Some text");
}
public static void main(String[] args) throws InterruptedException {
Thread_Demo t=new Thread_Demo();
Thread_Demo td1=new Thread_Demo();
t.start();
System.out.println("ISALIVE :"+t.isAlive());
t.sleep(500);
System.out.println("ISALIVE :"+t.isAlive());
t.destroy();
System.out.println("ISALIVE :"+t.isAlive());
}
}
Thread Program in Java
What is out put?
public class Thread_Demo extends Thread{
public void run(){
System.out.println("Some text");
}
public static void main(String[] args) throws InterruptedException {
Thread_Demo td=new Thread_Demo();
Thread_Demo td1=new Thread_Demo();
/*Thread t=new Thread(td);*/
td.start();
td.setPriority(10);
System.out.println(td.getName()+td.getPriority());
td1.run();
System.out.println(td1.getName()+td1.getPriority());
}
}
public class Thread_Demo extends Thread{
public void run(){
System.out.println("Some text");
}
public static void main(String[] args) throws InterruptedException {
Thread_Demo td=new Thread_Demo();
Thread_Demo td1=new Thread_Demo();
/*Thread t=new Thread(td);*/
td.start();
td.setPriority(10);
System.out.println(td.getName()+td.getPriority());
td1.run();
System.out.println(td1.getName()+td1.getPriority());
}
}
Sunday, December 16, 2012
File Creation in java
import java.io.File;
import java.io.IOException;
public class FileCreatin {
public static void main(String args[]) throws IOException
{
File f=new File("F:/java.txt");
if(!f.exists())
{
f.createNewFile();
System.out.println("file created successfully");
}
else
System.out.println("File already exists");
}
}
import java.io.IOException;
public class FileCreatin {
public static void main(String args[]) throws IOException
{
File f=new File("F:/java.txt");
if(!f.exists())
{
f.createNewFile();
System.out.println("file created successfully");
}
else
System.out.println("File already exists");
}
}
Simple Java programs
1.
Question :
Given two non-negative int values, return true if they have the same last digit, such as with 27 and 57. Note that the % "mod" operator computes remainders, so 17 % 10 is 7.
Ans:
public boolean lastDigit(int a, int b) {
int r=a%10;
int r1=b%10;
if(r==r1)
{
System.out.println(true);
} // These programs for educational purpose only. Dont copy and publish in your blog or website..
else
System.out.println(false);
}
2.
Question :Given 2 int values, return true if one is negative and one is positive. Except if the parameter "negative" is true, then return true only if both are negative.
Ans:
public boolean posNeg(int a, int b, boolean negative) {
if((a<0&b>0&negative==false)|(a>0&b<0&negative==false))
{
System.out.println(true);
}
else if(a<0&b<0&negative==true)
System.out.println(true);
else
System.out.println(false);
} // These programs for educational purpose only. Dont copy and publish in your blog or website..
3.
Question :
Given two temperatures, return true if one is less than 0 and the other is greater than 100.
icyHot(120, -1) → true
icyHot(-1, 120) → true
icyHot(2, 120) → false
Answer:
public boolean icyHot(int temp1, int temp2) {
if((temp1<0&temp2>100)|(temp1>100&temp2<0))
{
System.out.println(true);
}
else
System.out.println(false);
} // These programs for educational purpose only. Dont copy and publish in your blog or website..
Question :
Given two non-negative int values, return true if they have the same last digit, such as with 27 and 57. Note that the % "mod" operator computes remainders, so 17 % 10 is 7.
Ans:
public boolean lastDigit(int a, int b) {
int r=a%10;
int r1=b%10;
if(r==r1)
{
System.out.println(true);
} // These programs for educational purpose only. Dont copy and publish in your blog or website..
else
System.out.println(false);
}
2.
Question :Given 2 int values, return true if one is negative and one is positive. Except if the parameter "negative" is true, then return true only if both are negative.
Ans:
public boolean posNeg(int a, int b, boolean negative) {
if((a<0&b>0&negative==false)|(a>0&b<0&negative==false))
{
System.out.println(true);
}
else if(a<0&b<0&negative==true)
System.out.println(true);
else
System.out.println(false);
} // These programs for educational purpose only. Dont copy and publish in your blog or website..
3.
Question :
Given two temperatures, return true if one is less than 0 and the other is greater than 100.
icyHot(120, -1) → true
icyHot(-1, 120) → true
icyHot(2, 120) → false
Answer:
public boolean icyHot(int temp1, int temp2) {
if((temp1<0&temp2>100)|(temp1>100&temp2<0))
{
System.out.println(true);
}
else
System.out.println(false);
} // These programs for educational purpose only. Dont copy and publish in your blog or website..
OCJP Constructor and method overloading....
1.An java program with Constructor and method overloading
public class Workout {
public void workout(){
System.out.println("Constructor in Workout");
}
public Workout(){
Workout.main("hi");
System.out.println("Over loaded constructor in Workout");
} public static void main(String string) {
System.out.println(string);
new Workout();
}
public static void main(Integer args[])
{
Workout.main("hi");
}
public static void main(String args[])
{
new Workout();//An program with constructor and method overloading......by k.saravanan
// program for educational purposes only.. Dont copy and post in your blog or ur website ....
}
}
What is output?
Prints hi continuously and stack overflow error will occur.....
public class Workout {
public void workout(){
System.out.println("Constructor in Workout");
}
public Workout(){
Workout.main("hi");
System.out.println("Over loaded constructor in Workout");
} public static void main(String string) {
System.out.println(string);
new Workout();
}
public static void main(Integer args[])
{
Workout.main("hi");
}
public static void main(String args[])
{
new Workout();//An program with constructor and method overloading......by k.saravanan
// program for educational purposes only.. Dont copy and post in your blog or ur website ....
}
}
What is output?
Prints hi continuously and stack overflow error will occur.....
SCJP Questions with Answers Part -1
1. String compare using == operator
public void stringConvert(){
if("java".toUpperCase()=="java".toUpperCase())
{
System.out.println(true);
}
else
System.out.println(false);
}
2. String compare using equals :
public void stringEquals(){
if("java".toLowerCase().equals("JAVA".toLowerCase()))
{
System.out.println("true");
}
else
System.out.println(false);
}
3.
public void stringSubstring(){
String str="java programming";
str.substring(0,4);
str.replace('a', 'j');
String stra="welcome to "+str;
System.out.println(stra);
}
4.
public void zero(){
if(-00.0==+0.000)
{
System.out.println(true);
}
else
System.out.println(false);
ANSWERS:
1.false -> == operator check objects not contents...
2.true -> equals modifier checks only content...
3.welcome to java programming-> value of string replaced but not stored in anywhere.... So sting original contents not replaced...
4.true...-> there is nothing called negative and positive zero in java.. all zeros are treated equally..
public void stringConvert(){
if("java".toUpperCase()=="java".toUpperCase())
{
System.out.println(true);
}
else
System.out.println(false);
}
2. String compare using equals :
public void stringEquals(){
if("java".toLowerCase().equals("JAVA".toLowerCase()))
{
System.out.println("true");
}
else
System.out.println(false);
}
3.
public void stringSubstring(){
String str="java programming";
str.substring(0,4);
str.replace('a', 'j');
String stra="welcome to "+str;
System.out.println(stra);
}
4.
public void zero(){
if(-00.0==+0.000)
{
System.out.println(true);
}
else
System.out.println(false);
ANSWERS:
1.false -> == operator check objects not contents...
2.true -> equals modifier checks only content...
3.welcome to java programming-> value of string replaced but not stored in anywhere.... So sting original contents not replaced...
4.true...-> there is nothing called negative and positive zero in java.. all zeros are treated equally..
Subscribe to:
Comments (Atom)