Thursday 2 June 2011

Switch Case example in java


import java.io.*;

public class SwitchExample{
public static void main(String[] args) throws Exception{
int x, y;
BufferedReader object = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter two numbers for operation:");
try{
x = Integer.parseInt(object.readLine());
y = Integer.parseInt(object.readLine());
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println("enter your choice:");
int a= Integer.parseInt(object.readLine());
switch (a){
case 1:
System.out.println("Enter the number one=" + (x+y));
break;
case 2:
System.out.println("Enter the number two=" + (x-y));
break;
case 3:
System.out.println("Enetr the number three="+ (x*y));
break;
case 4:
System.out.println("Enter the number four="+ (x/y));
break;
default:
System.out.println("Invalid Entry!:");
}
}
catch(NumberFormatException ne){
System.out.println(ne.getMessage() + " is not a numeric value.");
System.exit(0);
}

}
}


matrix multiplication using java


class MatrixMultiply{
public static void main(String[] args)  {
int array[][] = {{5,6,7},{4,8,9}};
int array1[][] = {{6,4},{5,7},{1,1}};
int array2[][] = new int[3][3];
int x= array.length;
System.out.println("Matrix 1 : ");
    for(int i = 0; i < x; i++) {
for(int j = 0; j <= x; j++) {
System.out.print(" "+ array[i][j]);
}
System.out.println();
}
int y= array1.length;
System.out.println("Matrix 2 : ");
    for(int i = 0; i < y; i++) {
for(int j = 0; j < y-1; j++) {
System.out.print(" "+array1[i][j]);
}
System.out.println();
        }

    for(int i = 0; i < x; i++) {
for(int j = 0; j < y-1; j++) {
for(int k = 0; k < y; k++){

array2[i][j] += array[i][k]*array1[k][j];
}
}
        }
System.out.println("Multiply of both matrix : ");
for(int i = 0; i < x; i++) {
for(int j = 0; j < y-1; j++) {
System.out.print(" "+array2[i][j]);
}
System.out.println();
        }
    }
}

Matrix Sum in java


class MatrixSum{
    public static void main(String[] args)  {
    int array[][]= {{4,5,6},{6,8,9}};
int array1[][]= {{5,4,6},{5,6,7}};
System.out.println("Number of Row= " + array.length);
System.out.println("Number of Column= " + array[1].length);
int l= array.length;
System.out.println("Matrix 1 : ");
    for(int i = 0; i < l; i++) {
for(int j = 0; j <= l; j++) {
System.out.print(" "+ array[i][j]);
}
System.out.println();
        }
int m= array1.length;
System.out.println("Matrix 2 : ");
    for(int i = 0; i < m; i++) {
for(int j = 0; j <= m; j++) {
System.out.print(" "+array1[i][j]);
}
System.out.println();
        }
System.out.println("Addition of both matrix : ");
    for(int i = 0; i < m; i++) {
for(int j = 0; j <= m; j++) {
System.out.print(" "+(array[i][j]+array1[i][j]));
}
System.out.println();
        }
    }
}


matrix example in java


class MatrixExample{
    public static void main(String[] args)  {
    int array[][]= {{1,3,5},{2,4,6}};
System.out.println("Row size= " + array.length);
System.out.println("Column size = " + array[1].length);
outputArray(array);
}
   
   public static void outputArray(int[][] array) {
  int rowSize = array.length;
  int columnSize = array[0].length;
  for(int i = 0; i <= 1; i++) {
  System.out.print("[");
  for(int j = 0; j <= 2; j++) {
  System.out.print(" " + array[i][j]);
  }
  System.out.println(" ]");
  }
  System.out.println();
   }
}


string buffer java program


import java.io.*;

public class stringBuffer{
public static void main(String[] args) throws Exception{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String str;
try{
System.out.print("Enter your name: ");
str = in.readLine();
str += ", This is the example of SringBuffer class and it's functions.";

//Create a object of StringBuffer class
StringBuffer strbuf = new StringBuffer();
System.out.print(strbuf.length());
strbuf.append(str);
System.out.println(strbuf);
strbuf.delete(0,str.length());

//append()
strbuf.append("Hello");
strbuf.append("World"); //print HelloWorld
System.out.println(strbuf);

//insert()
strbuf.insert(5,"_Java "); //print Hello_Java World
System.out.println(strbuf);

//reverse()
strbuf.reverse();
System.out.print("Reversed string : ");
System.out.println(strbuf); //print dlroW avaJ_olleH
strbuf.reverse();
System.out.println(strbuf); //print Hello_Java World

//setCharAt()
strbuf.setCharAt(5,' ');
System.out.println(strbuf); //prit Hello Java World

//charAt()
System.out.print("Character at 6th position : ");
System.out.println(strbuf.charAt(6)); //print J

//substring()
System.out.print("Substring from position 3 to 6 : ");
System.out.println(strbuf.substring(3,7)); //print lo J

//deleteCharAt()
strbuf.deleteCharAt(3);
System.out.println(strbuf); //print Helo java World

//capacity()
System.out.print("Capacity of StringBuffer object : ");
System.out.println(strbuf.capacity()); //print 21

//delete() and length()
strbuf.delete(6,strbuf.length());
System.out.println(strbuf); //no anything
}
catch(StringIndexOutOfBoundsException e){
System.out.println(e.getMessage());
}
}
}


Directory creation in java


import java.io.*;
class CreateDirectory
{
   public static void main(String args[])
{
      try{
String strDirectoy ="test";
String strManyDirectories="dir1/dir2/dir3";

// Create one directory
boolean success = (new File(strDirectoy)).mkdir();
if (success) {
System.out.println("Directory: " + strDirectoy + " created");
}


// Create multiple directories
success = (new File(strManyDirectories)).mkdirs();
if (success) {
System.out.println("Directories: " + strManyDirectories + " created");
}

}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}


Writing a File using java


import java.io.*;
class FileWrite
{
   public static void main(String args[])
{
      try{
// Create file
FileWriter fstream = new FileWriter("out.txt");
        BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}

output:
------------
out.txt

Copying a file using java


import java.io.*;

public class CopyFile{
private static void copyfile(String srFile, String dtFile){
try{
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);

//For Append the file.
// OutputStream out = new FileOutputStream(f2,true);

//For Overwrite the file.
OutputStream out = new FileOutputStream(f2);

byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
}
catch(FileNotFoundException ex){
System.out.println(ex.getMessage() + " in the specified directory.");
System.exit(0);
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void main(String[] args){
switch(args.length){
case 0: System.out.println("File has not mentioned.");
System.exit(0);
case 1: System.out.println("Destination file has not mentioned.");
System.exit(0);
case 2: copyfile(args[0],args[1]);
System.exit(0);
default : System.out.println("Multiple files are not allow.");
 System.exit(0);
}
}
}


Read a file using java


import java.io.*;
class FileRead
{
   public static void main(String args[])
{
      try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}



Output:
--------
Hello World !

math class in java


public class mathclass{
public static void main(String[] args){
//E and round()
Double a = Math.E;
System.out.println("e = " + Math.round(a*100)/100f);
//PI
System.out.println("pi = " + Math.round(Math.PI*100)/100f);
//abs()
System.out.println("Absolute number = " + Math.abs(Math.PI));
//ceil()
System.out.println("Smallest integer value but greater than the argument = " + Math.ceil(Math.PI));
//exp()
System.out.println("Exponent number powered by the argument = " + Math.exp(0));
//floor()
System.out.println("Largest integer value but less than the argument = " + Math.floor(Math.E));
//IEEEremainder()
System.out.println("Remainder = " + Math.IEEEremainder(5.3f,2.2f));
//max()
System.out.println("Maximum Number = " + Math.max(10,10.3));
//min()
System.out.println("Minimum Number = " + Math.min(10,10.3));
//pow()
System.out.println("Power = " + Math.pow(10,3));
//random()
System.out.println("Random Number = " + Math.random());
//rint()
System.out.println("Closest to the Argument = " + Math.rint(30));
//round()
System.out.println("Round = " + Math.round(Math.E));
//sqrt()
System.out.println("Square Root = " + Math.sqrt(400));
}
}

Deleting a file using java


import java.io.*;

public class DeleteFile{
private static void deletefile(String file){
File f1 = new File(file);
boolean success = f1.delete();
if (!success){
System.out.println("Deletion failed.");
System.exit(0);
}else{
System.out.println("File deleted.");
}
}
public static void main(String[] args){
switch(args.length){
case 0: System.out.println("File has not mentioned.");
System.exit(0);
case 1: deletefile(args[0]);
System.exit(0);
default : System.out.println("Multiple files are not allow.");
 System.exit(0);
}
}
}


Directory Listing in JAVA


import java.io.*;

public class  DirListing{
private static void dirlist(String fname){
File dir = new File(fname);
String[] chld = dir.list();
if(chld == null){
System.out.println("Specified directory does not exist or is not a directory.");
System.exit(0);
}else{
for(int i = 0; i < chld.length; i++){
String fileName = chld[i];
System.out.println(fileName);
}
}
}
public static void main(String[] args){
switch(args.length){
case 0: System.out.println("Directory has not mentioned.");
System.exit(0);
case 1: dirlist(args[0]);
System.exit(0);
default : System.out.println("Multiple files are not allow.");
 System.exit(0);
}
}
}