0% found this document useful (0 votes)
110 views

Objective

The document provides 11 code snippets showing examples of how to perform common file operations in Java, including: 1. Creating a new file 2. Writing content to a file using FileOutputStream 3. Reading content from a file using FileInputStream 4. Writing to a file using BufferedWriter 5. Reading from a file using BufferedReader 6. Getting a file's size and path 7. Deleting a file 8. Copying files 9. Printing/displaying a file's content 10. Another example of printing a file's content 11. Getting the last modification date and time of a file

Uploaded by

DEv Kaushal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
110 views

Objective

The document provides 11 code snippets showing examples of how to perform common file operations in Java, including: 1. Creating a new file 2. Writing content to a file using FileOutputStream 3. Reading content from a file using FileInputStream 4. Writing to a file using BufferedWriter 5. Reading from a file using BufferedReader 6. Getting a file's size and path 7. Deleting a file 8. Copying files 9. Printing/displaying a file's content 10. Another example of printing a file's content 11. Getting the last modification date and time of a file

Uploaded by

DEv Kaushal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 99

Q.1) Java program to create a new file.

import java.io.File;

public class CreateFile


{
public static void main(String args[])
{
final String fileName="file1.txt";

try
{
File objFile=new File(fileName);
if(objFile.createNewFile())
{
System.out.println("File created successfully.");
}
else
{
System.out.println("File creation failed!!!");
}
}
catch (Exception Ex)
{
System.out.println("Exception : " + Ex.toString());
}
}
}

OUTPUT-
Q.2) Java program to write content into file using FileOutputStream.

//Java program to write content into file using FileOutputStream.

import java.io.File;
import java.io.FileOutputStream;
import java.util.Scanner;

public class WriteFile


{
public static void main(String args[])
{
final String fileName="file1.txt";

try
{
File objFile=new File(fileName);
if(objFile.exists()==false)
{
if(objFile.createNewFile())
{
System.out.println("File created successfully.");
}
else
{
System.out.println("File creation failed!!!");
System.exit(0);
}
}

//writting data into file


String text;
Scanner SC=new Scanner(System.in);
System.out.println("Enter text to write into file: ");
text= SC.nextLine();

//object of FileOutputStream
FileOutputStream fileOut=new FileOutputStream(objFile);
//convert text into Byte and write into file
fileOut.write(text.getBytes());
fileOut.flush();
fileOut.close();
System.out.println("File saved.");
}
catch (Exception Ex)
{
System.out.println("Exception : " + Ex.toString());
}
}
}

OUTPUT-
Q.3) Java program to read content from file using FileInputStream

//Java program to read content from file using FileInputStream.

import java.io.File;
import java.io.FileInputStream;

public class ReadFile


{
public static void main(String args[])
{
final String fileName="file1.txt";

try
{
File objFile=new File(fileName);
if(objFile.exists()==false)
{
System.out.println("File does not exist!!!");
System.exit(0);
}

//reading content from file


String text;
int val;

//object of FileOutputStream
FileInputStream fileIn=new FileInputStream(objFile);
//read text from file
System.out.println("Content of the file is: ");
while((val=fileIn.read())!=-1)
{
System.out.print((char)val);
}

System.out.println();

fileIn.close();
}
catch (Exception Ex)
{
System.out.println("Exception : " + Ex.toString());
}
}
}

OUTPUT->
Q.4) Java program to write content into file using BufferedWriter.

//Java program to write content into file using BufferedWriter.

import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.util.Scanner;

public class ExBufferedWriter


{
public static void main(String args[])
{
final String fileName="file2.txt";

try
{
File objFile=new File(fileName);
if(objFile.exists()==false)
{
if(objFile.createNewFile())
{
System.out.println("File created successfully.");
}
else
{
System.out.println("File creation failed!!!");
System.exit(0);
}
}

//writting data into file


String text;
Scanner SC=new Scanner(System.in);

System.out.println("Enter text to write into file: ");


text= SC.nextLine();

//instance of FileWriter
FileWriter objFileWriter = new FileWriter(objFile.getAbsoluteFile());
//instnace (object) of BufferedReader with respect of FileWriter
BufferedWriter objBW = new BufferedWriter(objFileWriter);
//write into file
objBW.write(text);
objBW.close();

System.out.println("File saved.");
}
catch (Exception Ex)
{
System.out.println("Exception : " + Ex.toString());
}
}
}

OUTPUT->
Q.5) Java program to read content from file using BufferedReader.

//Java program to read content from file using BufferedReader.

import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;

public class ExBufferedReader


{
public static void main(String args[])
{
final String fileName="file2.txt";

try
{
File objFile=new File(fileName);
if(objFile.exists()==false)
{
System.out.println("File does not exist!!!");
System.exit(0);
}

//reading content from file


String text;
int val;

FileReader objFR=new FileReader(objFile.getAbsoluteFile());


BufferedReader objBR=new BufferedReader(objFR);
//read text from file
System.out.println("Content of the file is: ");
while((text=objBR.readLine())!=null)
{
System.out.println(text);
}

objBR.close();
}
catch (Exception Ex)
{
System.out.println("Exception : " + Ex.toString());
}
}
}

OUTPUT->
Q.6) Java program to get file size and file path.

//Java program to get file size and file path.

import java.io.File;

public class GetFilePathAndSize


{
public static void main(String args[])
{
final String fileName="file1.txt";
try
{
//File Object
File objFile=new File(fileName);

//getting file path


System.out.println("File path is: " + objFile.getAbsolutePath());
//getting filesize
System.out.println("File size is: " + objFile.length() + " bytes.");
}
catch (Exception Ex)
{
System.out.println("Exception: "+ Ex.toString());
}

}
}
OUTPUT->
Q.7) Java program to delete a file.

//Java program to get file size and file path.

import java.io.File;

public class ExDeleteFile


{
public static void main(String args[])
{
final String fileName="file3.txt";

//File class object


File objFile=new File(fileName);

//check file is exist or not, if exist delete it


if(objFile.exists()==true)
{
//file exists
//deleting the file
if(objFile.delete())
{
System.out.println(objFile.getName() + " deleted successfully.");
}
else
{
System.out.println("File deletion failed!!!");
}
}
else
{
System.out.println("File does not exist!!!");
}
}
}

OUTPUT->
Q.8) Java program to copy files.

//Java program to copy file.

import java.io.*;

public class FileCopy {


public static void main(String args[]) {
try {
//input file
FileInputStream sourceFile =new FileInputStream (args[0]);
//output file
FileOutputStream targetFile =new FileOutputStream(args[1]);

// Copy each byte from the input to output


int byteValue;
//read byte from first file and write it into second line
while((byteValue = sourceFile.read()) != -1)
targetFile.write(byteValue);

// Close the files!!!


sourceFile.close();
targetFile.close();

System.out.println("File copied successfully");


}
// If something went wrong, report it!
catch(IOException e) {
System.out.println("Exception: " + e.toString());
}
}
}
OUTPUT->
Q.9) Java - Print File Content, Display File using Java Program.

//Java - Print File Content, Display File using Java Program.

import java.io.*;

public class PrintFile{


public static void main(String args[]) throws IOException{
File fileName = new File("d:/sample.txt");

FileInputStream inFile = new FileInputStream("d:/sample.txt");


int fileLength =(int)fileName.length();

byte Bytes[]=new byte[fileLength];

System.out.println("File size is: " + inFile.read(Bytes));

String file1 = new String(Bytes);


System.out.println("File content is:\n" + file1);

//close file
inFile.close();
}
}
OUTPUT->
Q.10) Java Code Snippet - Print/Display File Content

//Java - Print File Content, Display File using Java Program.

import java.io.*;

public class PrintFile{


public static void main(String args[]) throws IOException{
File fileName = new File("d:/sample.txt");

FileInputStream inFile = new FileInputStream("d:/sample.txt");


int fileLength =(int)fileName.length();

byte Bytes[]=new byte[fileLength];

System.out.println("File size is: " + inFile.read(Bytes));

String file1 = new String(Bytes);


System.out.println("File content is:\n" + file1);

//close file
inFile.close();
}
}
OUTPUT->
Q.11) Java program to get the last modification date and time of a file

//this program will display date and time of last modification


//of the file IncludeHelp.txt

import java.io.*;
import java.util.Date;

public class LastModify


{
public static void main(String[] args)

{
// Enter the file name here.
File file = new File("E:/IncludeHelp.txt");

// lastModified is the predefined function of date class in java.


long lastModified = file.lastModified();

// will print when the file last modified.


System.out.println("File was last modified at : " + new
Date(lastModified));
}
}

OUTPUT->
Q.12) Java program to append text/string in a file

import java.io.*;

public class AppendFile


{
public static void main(String[] args)
{
//file name with path
String strFilePath = "E:/JAVA/IncludeHelp.txt";
try
{
//file output stream to open and write data
FileOutputStream fos = new FileOutputStream(strFilePath, true);
//string to be appended
String strContent = "Text to be appended.";

//appending text/string
fos.write(strContent.getBytes());
//closing the file
fos.close();
System.out.println("Content Successfully Append into File...");
}
catch(FileNotFoundException ex)
{
System.out.println("FileNotFoundException : " + ex.toString());
}
catch(IOException ioe)
{
System.out.println("IOException : " + ioe.toString());
}
catch (Exception e)
{
System.out.println("Exception: " + e.toString());
}
}
}

OUTPUT->
Q.13) Java program to determine number of bytes written to file using
DataOutputStream

import java.io.*;

public class ExToDetermineWrittenDataSize


{
//Java program to determine number of bytes written to file using
DataOutputStream
public static void main(String[] args){
try
{
FileOutputStream objFOS = new
FileOutputStream("E:/includehelp.txt");
DataOutputStream objDOS = new DataOutputStream(objFOS);

objDOS.writeBytes("IncludeHelp is for computer science


students.");
int bytesWritten = objDOS.size();
System.out.println("Total " + bytesWritten + " bytes are written to
stream.");
objDOS.close();
}
catch(Exception ex)
{
System.out.println("Exception: " + ex.toString());
}

}
}
OUTPUT->
Q.14) Java program to read text from file from a specified index or skipping byte
using FileInputStream

import java.io.*;

public class Skip


{
public static void main(String[] args)
{
//file class object
File file = new File("E:/JAVA/IncludeHelp.txt");
try
{
FileInputStream fin = new FileInputStream(file);
int ch;

System.out.println("File's content after 10 bytes is: ");


//skipping 10 bytes to read the file
fin.skip(10);
while( (ch = fin.read()) != -1 )
System.out.print((char) ch);
}
catch(FileNotFoundException ex)
{
System.out.println("FileNotFoundException : " + ex.toString());
}
catch(IOException ioe)
{
System.out.println("IOException : " + ioe.toString());
}
catch (Exception e)
{
System.out.println("Exception: " + e.toString());
}
}
}
OUTPUT->
Q.15) Java program to check whether a file is hidden or not

import java.io.*;

public class IsHidden


{
public static void main(String[] args)
{ // enter the file name here.
// create file object.
File file = new File("E:/includehelp.txt");

// this will check is the file hidden or not.


boolean blnHidden = file.isHidden();

// return result in true or false condition.


System.out.println("Is the file " + file.getPath() + " hidden ?: " + blnHidden);
}
}

OUTPUT->
Q.16) Java give file in bytes, kilobytes and megabytes program to get the size of

import java.io.*;

public class ReturnFileSize


{
public static void main(String[] args)
{
//create file object.
// enter the file name.
File file = new File("E:/includehelp.txt");

// calculate the size of the file.


long fileSize = file.length();

// return the file size in bytes,KB and MB.


System.out.println("File size in bytes is : " + fileSize);
System.out.println("File size in KB is : " + (double)fileSize/1024);
System.out.println("File size in MB is : " +
(double)fileSize/(1024*1024));
}
}
OUTPUT->
Q.17) Java program to create directory/folder in particular drive

import java.io.*;

public class CreateDirectory


{
public static void main(String[] args)
{
//object of File class with file path and name
File dir = new File("E:/IHelp");

//method 'mkdir' to create directroy and result


//is getting stored in 'isDirectoryCreated'
//which will be either 'true' or 'false'
boolean isDirectoryCreated = dir.mkdir();

//displaying results
if(isDirectoryCreated)
System.out.println("Directory successfully created: " + dir);
else
System.out.println("Directory was not created successfully: " +
dir)
}
}

OUTPUT->
Q.18) Java program to check whether a file can be read or not

import java.io.*;
public class DetermineFileCanBeRead
{
public static void main(String[] args)
{
String filePath = "E:/C.txt";
File file = new File(filePath);
if(file.canRead())
{
System.out.println("File " + file.getPath() +" can be read");
}
else
{
System.out.println("File " + file.getPath() +" can not be read");
}
}
}
OUTPUT->
Q.19) Java program to get the attributes of a file

import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.Scanner;

public class BasicAttributeOfFile


{
public static void main(String[] args) throws Exception
{
// create object of scanner.
Scanner KB=new Scanner(System.in);

// enter path here.


System.out.print("Enter the file path : ");
String A=KB.next();
Path path = FileSystems.getDefault().getPath(A);

// function is used to view file attribute.


BasicFileAttributeView view = Files.getFileAttributeView
(path,BasicFileAttributeView.class);
BasicFileAttributes attributes = view.readAttributes();

// all the attributes of the file.


System.out.println("Creation Time: " + attributes.creationTime());
System.out.println("Last Accessed Time: " +
attributes.lastAccessTime());
System.out.println("Last Modified Time: " +
attributes.lastModifiedTime());
System.out.println("File Key: " + attributes.fileKey());
System.out.println("Directory: " + attributes.isDirectory());
System.out.println("Other Type of File: " + attributes.isOther());
System.out.println("Regular File: " + attributes.isRegularFile());
System.out.println("Symbolic File: " + attributes.isSymbolicLink());
System.out.println("Size: " + attributes.size());
}
}

OUTPUT->
Q.20) Java program to read and print all files from a zip file

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class FindFileInZipFile


{
public void printFileList(String filePath)
{
// initializing the objects.
FileInputStream fis = null;
ZipInputStream Zis = null;
ZipEntry zEntry = null;
try
{
fis = new FileInputStream(filePath);
Zis = new ZipInputStream(new BufferedInputStream(fis));

// this will search the files while end of the zip.


while((zEntry = Zis.getNextEntry()) != null)
{
System.out.println(zEntry.getName());
}
Zis.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
//main function
public static void main(String a[])
{
// creating object of the file.
FindFileInZipFile fff = new FindFileInZipFile();
System.out.println("Files in the Zip are : ");

// enter the path of the zip file with name.


fff.printFileList("D:/JAVA.zip");
}
}

OUTPUT->
Q.21) Java program to get the file’s owner name

import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.Scanner;

public class OwnerOfFile


{
public static void main(String[] args) throws Exception
{
// create object of scanner.
Scanner KB=new Scanner(System.in);

// enter path here.


System.out.print("Enter the file path : ");
String A=KB.next();
Path path = Paths.get(A);

// create object of file attribute.


FileOwnerAttributeView view = Files.getFileAttributeView(path,
FileOwnerAttributeView.class);

// this will get the owner information.


UserPrincipal userPrincipal = view.getOwner();

// print information.
System.out.println("Owner of the file is :" +userPrincipal.getName());
}
}
OUTPUT->
Q.22) Java program to get the basic file attributes (specific to DOS)

import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.Scanner;

public class DosAttributeOfFile


{
public static void main(String[] args) throws Exception
{
// create object of scanner.
Scanner KB=new Scanner(System.in);

// enter path here.


System.out.print("Enter the file path : ");
String A=KB.next();
Path path = FileSystems.getDefault().getPath(A);

// create object of dos attribute.


DosFileAttributeView view =
Files.getFileAttributeView(path,DosFileAttributeView.class);

// this function read the attribute of dos file.


DosFileAttributes attributes = view.readAttributes();

System.out.println("isArchive: " + attributes.isArchive());


System.out.println("isHidden: " + attributes.isHidden());
System.out.println("isReadOnly: " + attributes.isReadOnly());
System.out.println("isSystem: " + attributes.isSystem());
}
}
OUTPUT->
Q.23) Java program to get file creation, last access and last modification time

import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.Calendar;
import java.util.Scanner;

public class TimeAttributeOfFile


{
public static void main(String[] args) throws Exception
{
// create object of scanner.
Scanner KB=new Scanner(System.in);

// enter path here.


System.out.print("Enter the file path : ");
String A=KB.next();
Path path = Paths.get(A);
BasicFileAttributeView view =
Files.getFileAttributeView(path,BasicFileAttributeView.class);

BasicFileAttributes attributes = view.readAttributes();

// calculate time of modification and creation.


FileTime lastModifedTime = attributes.lastModifiedTime();
FileTime createTime = attributes.creationTime();

long currentTime = Calendar.getInstance().getTimeInMillis();


FileTime lastAccessTime = FileTime.fromMillis(currentTime);

view.setTimes(lastModifedTime, lastAccessTime, createTime);

System.out.println("Creation time of file is : " +attributes.creationTime());


System.out.println("Last modification time of file is : "
+attributes.lastModifiedTime());
System.out.println("Last access time of file is : " +attributes.lastAccessTime());
}
}

OUTPUT->
Q.24) Java program to read content from one file and write it into another file

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

public class CopyFile {


public static void main(String[] args) {
try
{
boolean create=true;
Scanner KB=new Scanner(System.in);

System.out.print("Enter Source File Name:");


String sfilename=KB.next();
File srcfile=new File(sfilename);
if(!srcfile.exists())
{
System.out.println("File Not Found..");
}
else
{
FileInputStream FI=new FileInputStream(sfilename);
System.out.print("Enter Target File Name:");
String tfilename=KB.next();
File tfile=new File(tfilename);
if(tfile.exists())
{
System.out.print("File Already Exist OverWrite
it..Yes/No?:");
String confirm=KB.next();
if(confirm.equalsIgnoreCase("yes"))
{
create=true;
}
else
{
create=false;
}
}
if(create)
{
FileOutputStream FO=new
FileOutputStream(tfilename);
int b;
//read content and write in another file
while((b=FI.read())!=-1)
{
FO.write(b);
}
System.out.println("\nFile Copied...");
}
FI.close();
}
}
catch(IOException e)
{
System.out.println(e);
}
}
}
OUTPUT->
Q.25) Java program to read a file line by line

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;

public class ReadLineByLine


{
public static void main(String[] args)
{
// create object of scanner class.
Scanner Sc=new Scanner(System.in);

// enter file name.


System.out.print("Enter the file name:");
String sfilename=Sc.next();
Scanner Sc1= null;
FileInputStream fis=null;
try
{
FileInputStream FI=new FileInputStream(sfilename);
Sc1=new Scanner(FI);

// this will read data till the end of data.


while(Sc1.hasNext())
{
String data=Sc1.nextLine();

// print the data.


System.out.print("The file data is : " +data);
}
}
catch(IOException e)
{
System.out.println(e);
}
}

OUTPUT->
Q.26) Java program to traverse all files of a directory/folder

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Scanner;

public class TraverseFileSystem


{
public static void main(String[] args)
{
try
{
// create object of scanner.
Scanner KB=new Scanner(System.in);

// enter path here.


System.out.print("Enter path here : ");
String A=KB.next();
Path path = Paths.get(A);
ListFiles listFiles = new ListFiles();
Files.walkFileTree(path, listFiles);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

class ListFiles extends SimpleFileVisitor<Path>


{
private final int indentionAmount = 3;
private int indentionLevel;

public ListFiles()
{
indentionLevel = 0;
}

private void indent()


{
for (int i = 0; i < indentionLevel; i++)
{
System.out.print(' ');
}
}

public FileVisitResult visitFile(Path file, BasicFileAttributes attributes)


{
indent();
System.out.println("Visiting file:" + file.getFileName());
return FileVisitResult.CONTINUE;
}

public FileVisitResult postVisitDirectory(Path directory, IOException e)throws


IOException
{
indentionLevel = indentionAmount;
indent();
System.out.println("Finished with the directory: "+ directory.getFileName());
return FileVisitResult.CONTINUE;
}
public FileVisitResult preVisitDirectory(Path directory,BasicFileAttributes
attributes) throws IOException
{
indent();
System.out.println("About to traverse the directory: "+
directory.getFileName());
indentionLevel += indentionAmount;
return FileVisitResult.CONTINUE;
}

public FileVisitResult visitFileFailed(Path file, IOException exc)throws IOException


{
System.out.println("A file traversal error ocurred");
return super.visitFileFailed(file, exc);
}
}
OUTPUT->
Q.1) How to convert a character array to string in Java?

import java.lang.*;

public class ConvertCharArrayToStringPrg


{
public static void main(String []args)
{
// declare String object
String str="";
// declare character array
char [] chrArr= new char[]{'H','e','l','l','o'};

// convert char array to string


str= new String(chrArr);

//print string
System.out.println("str : "+str);
}
}

OUTPUT->
Q.2) How to calculate length of the string using String.length() method in Java?

import java.lang.*;

public class JavaStringLengthPrg


{
public static void main(String []args)
{
int len=0;

/*create string object*/


String str="includehelp.com";

//getting length of the string


len = str.length();

//printing length
System.out.println("String Length is = "+ len);
}
}

OUTPUT->
Q.3) How to trim a given string using String.trim() method in Java?

import java.lang.*;

public class StringTrimPrg


{
public static void main(String []args)
{
String str=" www.includehelp.com ";
System.out.println("String omitting leading and trailing spaces: "+
str.trim());
}
}
OUTPUT->
Q.4) How to spilt string in substrings using String.split() in Java?

public class JavaStringSplitPrg


{
public static void main(String []args)
{
try
{
String str1="www.includehelp.com";
int loop;

String [] arrStr1;

/*split string by delimiter ., to do this


* you have to provide \\. */
arrStr1 = str1.split("\\.");
// print substrings
for(loop=0;loop < arrStr1.length; loop++)
{
System.out.println(arrStr1[loop]);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}

OUTPUT->
Q.5) Java program to demonstrate example of String.startsWith() and
String.endsWith()?

Example of String.startsWith()

public class JavaStringStartsWithPrg{


public static void main(String args[])
{
String str="www.includehelp.com";

if(str.startsWith("www")==true)
System.out.println("String starts with www");
else
System.out.println("String does not start with www");
}
}

Example of String.endsWith()

public class JavaStringEndsWithPrg{


public static void main(String args[])
{
String str="www.includehelp.com";

if(str.endsWith(".com")==true)
System.out.println("String ends with .com");
else
System.out.println("String does not end with .com");
}
}

OUTPUT->
Q.6) How to replace string with another string in java using String.replace()
method?

//Java Program to replace a string with new one.

public class JavaStringReplacePrg


{
public static void main(String args[])
{
//string 1
String str1="www.includehelp.com";
//string 2
String str2="Hello World!";

//printing strings before replacing


System.out.println("\nStrings before replacing:");
System.out.println("str1: "+str1 +"\nstr2:" + str2);

//replacing string str1 with str2


str1=str1.replace(str1, str2);

//printing strings after replacing


System.out.println("\nStrings after replacing:");
System.out.println("str1: "+str1 +"\nstr2:" + str2);
}
}
OUTPUT->
Q.7) How to reverse a string in Java with and without using
StringBuffer.reverse() method?

import java.util.*;

public class ReverseString


{
public static void main(String args[])
{
//declare string object and assign string
StringBuffer str= new StringBuffer("Hello World!");

//reverse the string


str.reverse();

//print the reversed string


System.out.println("String after reversing:" + str);
}
}

OUTPUT->
Q.8) How to check whether a given string is empty or not in Java?

/*Java Program to check whether string is empty or not*/

public class JavaisEmptyPrg


{
public static void main(String args[])
{
String str1="www.includehelp.com";
String str2="";

if(str1.isEmpty()==true)
System.out.println("Str1 is an empty string.");
else
System.out.println("Str1 is not an empty string.");

if(str2.isEmpty()==true)
System.out.println("Str2 is an empty string.");
else
System.out.println("Str2 is not an empty string.");
}
}

OUTPUT->
Q.9) Java program to convert string to lowercase and uppercase

/*Java program to convert string into Lowercase and Uppercase*/


import java.util.*;
class ConvertCasePrg
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
String str="";

//input string
System.out.print("Enter any string: ");
str=sc.nextLine();

//declaring objects to store lowercase and uppercase strings


String lowerCaseString="",upperCaseString="";

//convert into lower case


lowerCaseString= str.toLowerCase();
//convert into upper case
upperCaseString= str.toUpperCase();

//printing the strings


System.out.println("Original String: "+str);
System.out.println("Lower Case String: "+lowerCaseString);
System.out.println("Upper Case String: "+upperCaseString);
}
}
OUTPUT->
Q.10) Java program to get sub string from a given string

import java.util.*;

class getSubstring
{
public static void main(String args[]) throws Exception
{
Scanner sc=new Scanner(System.in);
String str="";

int startIndex,endIndex;

//input string
System.out.print("Enter the string: ");
str=sc.nextLine();

//input start index and end index


System.out.print("Enter start index: ");
startIndex=sc.nextInt();
System.out.print("Enter end index: ");
endIndex=sc.nextInt();

/*get string from startIndex to endIndex*/


String temp;
temp= str.substring(startIndex, endIndex);
//printing substring
System.out.println("Substring is: "+temp);
}
}
OUTPUT->
Q.11) Java program to convert any type of value to string value using
String.valueOf() method

class ConvertIntoString
{
public static void main(String args[])
{
//define different type of values
int intVal=120;
float floatVal=12.34f;
double doubleVal=2345.0d;
boolean booleanVal=true;

System.out.println("After converting into string");

//printing values in string format


System.out.println("String value of intVal: "+ String.valueOf(intVal));
System.out.println("String value of floatVal: "+
String.valueOf(floatVal));
System.out.println("String value of doubleVal: "+
String.valueOf(doubleVal));
System.out.println("String value of booleanVal: "+
String.valueOf(booleanVal));
}
}
OUTPUT->
Q.12) Java program to compare two strings using String.compareTo() method

import java.util.*;

class CompareStrings
{
public static void main(String args[])
{
//declaring two string objects
String str1,str2;
//declaring input stream object
Scanner in = new Scanner(System.in);

//input strings
System.out.print("Enter first string: ");
str1 = in.nextLine();
System.out.print("Enter second string: ");
str2 = in.nextLine();

//comparing strings
if(str1.compareTo(str2)==0)
System.out.println("Strings are equal.");
else
System.out.println("Strings are not equal.");
}
}

OUTPUT->
Q.13) Java program to input a string from user and reverse each word of given
string

package com.includehelp.stringsample;

import java.util.Scanner;

/**
* program to input a string from user and reverse each word of given string
*/
public class ReverseEachWord {

/**
* Method to reverse each word in provided string
* @param inputString
* @return
*/
static String reverseWord(String inputString){
String[] strarray = inputString.split(" "); // Spilt String by Space
StringBuilder sb = new StringBuilder();
for(String s:strarray){
if(!s.equals("")){
StringBuilder strB = new StringBuilder(s);
String rev = strB.reverse().toString();
sb.append(rev+" ");
}
}
return sb.toString();

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.println("Enput String : ");
String str = sc.nextLine();
System.out.println("Input String : "+str);
System.out.println("String with Reverese Word : "+reverseWord(str));
}

OUTPUT->
Q.14) Easiest way to check Given String is Palindrome String or not in Java

package stringsample;

import java.util.Scanner;

/**
* Easiest way to check Given String is Palindrome String or not
*/
public class PalindromString {

static boolean isPalindromString(String inputStr){


StringBuilder sb = new StringBuilder(inputStr);
String reverseStr = sb.reverse().toString();

return (inputStr.equalsIgnoreCase(reverseStr));
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.println("Enter String : ");
String inString = sc.next();

if(isPalindromString(inString)){
System.out.println(inString +" is a Palindrom String");
}
else{
System.out.println(inString +" is not a Palindrom String");
}
}
}
OUTPUT->
Q.15) Java program to get string and count number of words in provided string

import java.util.Scanner;

/**
* program to get string and count no. of words in provided string
*/
public class CountWordsInString {

/**
* Method to count no. of words in provided String
* @param inputString
* @return
*/
static int countWords(String inputString){
String[] strarray = inputString.split(" "); // Spilt String by Space
StringBuilder sb = new StringBuilder();
int count=0;
for(String s:strarray){
if(!s.equals("")){
count++;
}
}
return count;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.println("Enter String : ");
String str = sc.nextLine();
System.out.println("No. of Words in String : "+countWords(str));
}
}
OUTPUT->
Q.16) Java program to check given strings are Anagram or not

import java.util.Arrays;
import java.util.Scanner;

/**
* program to check given strings are Anagram or not
*/
public class AnagramString {

/**
* Method to check two strings are anagram string or not
* @param str1
* @param str2
* @return
*/
static boolean isAnagrams(String str1,String str2){
if(str1.length()!=str2.length()){
return false;
}
char[] strArray1 = str1.toCharArray();
char[] strArray2 = str2.toCharArray();

Arrays.sort(strArray1);
Arrays.sort(strArray2);

String sortedStr1 = new String(strArray1);


String sortedStr2 = new String(strArray2);

if(sortedStr1.equals(sortedStr2)){
return true;
}
else{
return false;
}
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.println("Enter String1 : ");
String str1 = sc.next();
System.out.println("Enter String2 : ");
String str2 = sc.next();

if(isAnagrams(str1,str2)){
System.out.println("Anagram Strings !!");
}
else{
System.out.println("Strings are not Anagram !!");
}
}
}
OUTPUT->
Q.17) Java program to Encrypt/Decrypt String Using AES 128 bits Encryption
Algorithm

import java.util.Base64;
import java.util.Scanner;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
* Program to Encrypt/Decrypt String Using AES 128 bit Encryption Algorithm
*/
public class EncryptDecryptString {

private static final String encryptionKey = "ABCDEFGHIJKLMNOP";


private static final String characterEncoding = "UTF-8";
private static final String cipherTransformation = "AES/CBC/PKCS5PADDING";
private static final String aesEncryptionAlgorithem = "AES";

/**
* Method for Encrypt Plain String Data
* @param plainText
* @return encryptedText
*/
public static String encrypt(String plainText) {
String encryptedText = "";
try {
Cipher cipher = Cipher.getInstance(cipherTransformation);
byte[] key = encryptionKey.getBytes(characterEncoding);
SecretKeySpec secretKey = new SecretKeySpec(key,
aesEncryptionAlgorithem);
IvParameterSpec ivparameterspec = new IvParameterSpec(key);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivparameterspec);
byte[] cipherText = cipher.doFinal(plainText.getBytes("UTF8"));
Base64.Encoder encoder = Base64.getEncoder();
encryptedText = encoder.encodeToString(cipherText);

} catch (Exception E) {
System.err.println("Encrypt Exception : "+E.getMessage());
}
return encryptedText;
}

/**
* Method For Get encryptedText and Decrypted provided String
* @param encryptedText
* @return decryptedText
*/
public static String decrypt(String encryptedText) {
String decryptedText = "";
try {
Cipher cipher = Cipher.getInstance(cipherTransformation);
byte[] key = encryptionKey.getBytes(characterEncoding);
SecretKeySpec secretKey = new SecretKeySpec(key,
aesEncryptionAlgorithem);
IvParameterSpec ivparameterspec = new IvParameterSpec(key);
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivparameterspec);
Base64.Decoder decoder = Base64.getDecoder();
byte[] cipherText = decoder.decode(encryptedText.getBytes("UTF8"));
decryptedText = new String(cipher.doFinal(cipherText), "UTF-8");

} catch (Exception E) {
System.err.println("decrypt Exception : "+E.getMessage());
}
return decryptedText;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.println("Enter String : ");
String plainString = sc.nextLine();

String encyptStr = encrypt(plainString);


String decryptStr = decrypt(encyptStr);

System.out.println("Plain String : "+plainString);


System.out.println("Encrypt String : "+encyptStr);
System.out.println("Decrypt String : "+decryptStr);

}
}

OUTPUT->
Q.18) Java program to separate all tokens (words) using StringTokenizer

import java.util.Scanner;
import java.util.StringTokenizer;

public class CountTokens


{
public static void main(String[] args)
{
//create StringTokenizer object
String S;
Scanner scan = new Scanner (System.in);

// enter your string here.


System.out.print("Enter the string : ");

// will read string and store it in "S" for further process.


S = scan.nextLine();
StringTokenizer st = new StringTokenizer(S, " ");

// search for token while the string ends.


while(st.hasMoreTokens())
{
// print all the tokens.
System.out.println("Remaining are : " + st.countTokens());
System.out.println(st.nextToken());
}
}
}
OUTPUT->
Q.19) Java program to find occurrences of each character in a string

import java.io.*;
import java.util.Scanner;
public class FindDuplicateChar
{
public static void main(String[] args) throws IOException
{
// create object of the string.
String S;
Scanner scan = new Scanner (System.in);

// enter your statement here.


System.out.print("Enter the Statement : ");

// will read statement and store it in "S" for further process.


S = scan.nextLine();
int count=0,len=0;
do
{
try
{
// this loop will identify character and find how many
times it occurs.
char name[]=S.toCharArray();
len=name.length;
count=0;
for(int j=0;j<len;j++)
{
// use ASCII codes for searching.

if((name[0]==name[j])&&((name[0]>=65&&name[0]<=91)||(name[0]>=97&
&name[0]<=123)))
count++;
}
if(count!=0){
// print all the repeated characters.
System.out.println(name[0]+" "+count+" Times");
}
S=S.replace(""+name[0],"");
}
catch(Exception e)
{
System.out.println(e);
}
}
while(len!=1);
}
}
OUTPUT->
Q.20) Java program to reverse words of a string

import java.util.Scanner;
import java.util.StringTokenizer;

public class ReverseByWord


{
public static void main(String[] args)
{
// create object of the string.
String S;

Scanner scan = new Scanner (System.in);

// enter your string here.


System.out.print("Enter the string : ");
// will read string and store it in "S" for further process.
S = scan.nextLine();

StringTokenizer st = new StringTokenizer(S, " ");

// strReverseLine is the function used to reverse a string.


String strReversedLine = "";
try
{
while(st.hasMoreTokens())
{
strReversedLine = st.nextToken() + " " + strReversedLine;
}
System.out.println("Reversed string by word is : " +
strReversedLine);
}
catch(Exception e)
{
System.out.println(e);
}
}
}

OUTPUT->
Q.21) Java program to concatenate two strings

import java.util.Scanner;

public class StringConcatenation


{
public static void main(String args[])
{ // creating object of the string s1,s2.
String s1,s2;
Scanner sc=new Scanner(System.in);
// enter both the string one by one.
System.out.print("Enter First String : ");
s1=sc.nextLine();

System.out.print("Enter Second String : ");


s2=sc.nextLine();

// here we print the whole string after concatenation.


System.out.println("String After Concatenation : " +s1.concat(s2));
}
}

OUTPUT->
Q.22) Java program to get the last index of any given character in a string

import java.util.Scanner;

public class StringLastValue


{
public static void main(String[] arg)
{
// create object of string and scanner class.
String S;
Scanner SC=new Scanner(System.in);

// enter the string.


System.out.print("Enter the string : ");
S=SC.nextLine();
int index = 0;

// enter the element for last occurence.


index = S.lastIndexOf('l');

System.out.println("Last index is : " +index);


}
}

OUTPUT->
Q.23) Java program to make first alphabet capital of each word in a string

import java.util.Scanner;

public class MakeCapitalFirstWordInLine


{
public static void main(String[] args)
{
// create object of scanner class.
Scanner in = new Scanner(System.in);

// enter sentence here


System.out.print("Enter sentence here : ");
String line = in.nextLine();
String upper_case_line = "";

// this is for the new line which is generated after conversion.


Scanner lineScan = new Scanner(line);
while(lineScan.hasNext())
{
String word = lineScan.next();
upper_case_line += Character.toUpperCase(word.charAt(0)) +
word.substring(1) + " ";
}

// print original line with output.


System.out.println("Original sentence is : " +line);
System.out.println("Sentence after convert : "
+upper_case_line.trim());
}
}
OUTPUT->
Q.24) Java program to concatenate two strings without using library function

import java.util.Scanner;

class ConcatenateString{
public static void main(String[] args){
/* create Scanner class object */
Scanner sc = new Scanner(System.in);

/* Display message for user to take first


string input from keyboard */
System.out.println("Enter First String :");
String firstStr = sc.next();

/* Display message for user to take first


string input from keyboard */
System.out.println("Enter Second String :");
String secondStr = sc.next();

/* Display message for displaying result */


System.out.println("Result after concatenation:");

/* '+' operator concatenate string */


System.out.println(firstStr+ " " + secondStr);
}
}
OUTPUT->
Q.25) Lowercase to uppercase conversion without using any library function in
Java

// Lowercase to uppercase conversion without using


// any library function in Java

public class Main {


static String LowerToUpper(String s) {
String result = "";
char ch = ' ';
for (int i = 0; i < s.length(); i++) {

//check valid alphabet and it is in lowercase


if (s.charAt(i) >= 'a' && s.charAt(i) <= 'z') {
ch = (char)(s.charAt(i) - 32);
}
//else keep the same alphabet or any character
else {
ch = (char)(s.charAt(i));
}

result += ch; // concatenation, append c to result


}
return result;
}

public static void main(String[] args) {


System.out.println(LowerToUpper("IncludeHelp.com"));
System.out.println(LowerToUpper("www.example.com"));
System.out.println(LowerToUpper("123abcd@9081"));
System.out.println(LowerToUpper("OKAY@123"));
}
}
OUTPUT->
Q.26) Uppercase to lowercase conversion without using any library function in
Java

// Uppercase to lowercase conversion without using


// any library function in Java

public class Main {


static String UpperToLower(String s) {
String result = "";
char ch = ' ';
for (int i = 0; i < s.length(); i++) {

//check valid alphabet and it is in Uppercase


if (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z') {
ch = (char)(s.charAt(i) + 32);
}
//else keep the same alphabet or any character
else {
ch = (char)(s.charAt(i));
}

result += ch; // concatenation, append c to result


}
return result;
}

public static void main(String[] args) {


System.out.println(UpperToLower("IncludeHelp.com"));
System.out.println(UpperToLower("www.example.com"));
System.out.println(UpperToLower("123ABCD@9081"));
System.out.println(UpperToLower("OKAY@123"));
}
}
OUTPUT->
Q.27) Comparing Strings with equals() and compareTo() methods in Java

// Comparing Strings with equals() and compareTo()


// methods in Java

public class Main {


public static void main(String[] args) {
//strings
String str1 = new String("ABC");
String str2 = new String("PQR");

//comparing strings using equals() method


System.out.println(str1.equals(str2));
System.out.println(str1.equals(str1));

//comparing strings using == operator


System.out.println(str1 == str1);
System.out.println(str1 == str2);

//comparing strings using compareTo() method


System.out.println(str1.compareTo(str1));
System.out.println(str1.compareTo(str2));
}
}

OUTPUT->
Q.28) String palindrome program in Java

// Java code for checking string palindrome

public class Main {


//function to check whether string is Palindrome or not
public static boolean isPalindrome(String str) {
// Checking for null
if (str == null) {
throw new IllegalArgumentException("String is null.");
}

// length of the string


// if there is one character string - returing true
int len = str.length();
if (len <= 1) {
return true;
}

// Converting the string into uppercase


// to make the comparisons case insensitive
String strU = str.toUpperCase();

// result variable
// default initializing it with true
boolean result = true;

for (int i = 0; i < len / 2; i++) {


if (strU.charAt(i) != strU.charAt(len - 1 - i)) {
result = false;
// break the loop if the condition is true
break;
}
}
return result;
}

//main code
public static void main(String[] args) {
String str1 = "Hello world!";
if (isPalindrome(str1)) {
System.out.println(str1 + " is a palindrome string ");
} else {
System.out.println(str1 + " is not a palindrome string ");
}

String str2 = "ABCxCBA";


if (isPalindrome(str2)) {
System.out.println(str2 + " is a palindrome string ");
} else {
System.out.println(str2 + " is not a palindrome string ");
}
String str3 = "noon";
if (isPalindrome(str3)) {
System.out.println(str3 + " is a palindrome string ");
} else {
System.out.println(str3 + " is not a palindrome string ");
}
String str4 = "nooN";
if (isPalindrome(str4)) {
System.out.println(str4 + " is a palindrome string ");
} else {
System.out.println(str4 + " is not a palindrome string ");
}
}
}
OUTPUT->
Q.29) String comparison using Collator and String classes in Java

// importing Collator and Locale classes


import java.text.Collator;
import java.util.Locale;

public class Main {


//function to print strings (comparing & printing)
public static void printString(int diff, String str1, String str2) {
if (diff < 0) {
System.out.println(str1 + " comes before " + str2);
} else if (diff > 0) {
System.out.println(str1 + " comes after " + str2);
} else {
System.out.println(str1 + " and " + str2 + " are the same strings.");
}
}

public static void main(String[] args) {


// Creating a Locale object for US english
Locale USL = new Locale("en", "US");

// Getting collator instance for USL (Locale)


Collator col = Collator.getInstance(USL);
String str1 = "Apple";
String str2 = "Banana";

// comparing strings and getting the difference


int diff = col.compare(str1, str2);

System.out.print("Comparing strings (using Collator class): ");


printString(diff, str1, str2);
System.out.print("Comparing strings (using String class): ");
diff = str1.compareTo(str2);
printString(diff, str1, str2);
}
}

OUTPUT->
Q.30) String concatenation with primitive data type values in Java

// Java code for string concatenation with


// primitive data type values

public class Main {


public static void main(String[] args) {
boolean isMarried = false;
boolean isQualified = true;
int age = 21;
double weight = 67.85;
char gender = 'M';
String name = "Shivang Yadav";
String result = null;

result = "isMarried: " + isMarried;


System.out.println(result);

result = "isQualified: " + isQualified;


System.out.println(result);

result = name + " is " + age + " years old.";


System.out.println(result);

result = name + " weight is " + weight + " kg.";


System.out.println(result);

result = "His gender is: " + gender;


System.out.println(result);
}
}
OUTPUT->
Q.1) Program to implement thread using runnable interface

public class ExampleClass implements Runnable {

public void run() {


System.out.println("Thread has ended");
}

public static void main(String[] args) {


ExampleClass ex = new ExampleClass();
Thread t1= new Thread(ex);
t1.start();
System.out.println("Hi");
}
}
OUTPUT->
Q.2) Program to creating multiple thread

class Multi extends Thread


{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi();
t1.start();
Multi t2=new Multi();
t2.start();
}
}

OUTPUT->
Q.3) Program to set priorities of thread

class TestMultiPriority1 extends Thread


{
public void run()
{
System.out.println("running thread name is:"+Thread.currentThread().getN
ame());
System.out.println("running thread priority is:"+Thread.currentThread().get
Priority());

}
public static void main(String args[])
{
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();

}
}

OUTPUT->
Q.4) Program to display all running thread

class TestMultiPriority1 extends Thread


{
public void run()
{
System.out.println("running thread name is:"+Thread.currentThread().getN
ame());
System.out.println("running thread priority is:"+Thread.currentThread().get
Priority());

}
public static void main(String args[])
{
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.start();
m2.start();

}
}

OUTPUT->

You might also like