Java File 35 Programs
Java File 35 Programs
Java File 35 Programs
Reference Books:
1. Java, The complete Reference, H. Schildt, 7th Edition, TMH.
2. Data Analytics using R, Seema Acharya, TMH.
1. Write a program to perform following operations on two numbers
input by the user:
1) Addition 2) subtraction 3) multiplication 4) division
import java.util.Scanner;
public class JavaProgram
{
public static void main(String args[])
{
int first, second, add, subtract, multiply;
float divide;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Two Numbers : ");
first = scanner.nextInt();
second = scanner.nextInt();
add = first + second;
subtract = first - second;
multiply = first * second;
divide = (float) first / second;
System.out.println("Sum = " + add);
System.out.println("Difference = " + subtract);
System.out.println("Multiplication = " + multiply);
System.out.println("Division = " + divide);
}
}
OUTPUT:
2. Write a Java program to print result of the following
operations.
1. -15 +58 * 45
2. (35+8) % 6
3. 24 + -5*3 / 7
4. 15 + 18 / 3 * 2 - 9 % 3
package com.company;
public class Main
{
public static void main(String args[])
{
int a,b,c,d;
a=-15 +58 * 45;
b=(35+8) % 6;
c=24 + -5*3 / 7;
d=15 + 18 / 3 * 2 - 9 % 3;
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
}
OUTPUT:
3. Write a Java program to compute area of:
1) Circle2) rectangle 3) triangle 4) square
package com.company;
public class Main {
void calculateArea(float x) {
System.out.println("Area of the square: " + x * x + " sq units");
}
void calculateArea(float x, float y) {
System.out.println("Area of the rectangle: " + x * y + " sq units");
}
void calculateArea(double r) {
double area = 3.14 * r * r;
System.out.println("Area of the circle: " + area + " sq units");
}
void calculateArea(int x, int y) {
double area = (x * y) / 2;
System.out.println("Area of the triangle: " + area + " sq units");
}
public static void main(String args[]) {
Main obj = new Main();
obj.calculateArea(6.1f);
obj.calculateArea(10, 22);
obj.calculateArea(6.1);
obj.calculateArea(12, 5);
}
}
OUTPUT:
4. Write a program to convert temperature from Fahrenheit to Celsius degree
using Java
package com.company;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
double celsius, fahrenheit;
Scanner s = new Scanner(System.in);
System.out.print("Enter temperature in Fahrenheit:");
fahrenheit = s.nextDouble();
celsius = (fahrenheit-32)*(0.5556);
System.out.println("Temperature in Celsius:"+celsius);
}
}
OUTPUT:
5. Write a program through Java that reads a number in inches, converts it to
meters.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter length in inches");
int inches = in.nextInt();
double meters = 0.0254 * inches;
System.out.println("inches is equal to=" + meters);
}
}
OUTPUT:
6. Write a program to convert minutes into a number of years and days
package com.company;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
double minutesInYear = 60 * 24 * 365;
Scanner input = new Scanner(System.in);
System.out.print("Input the number of minutes: ");
double min=input.nextDouble();
long years = (long) (min / minutesInYear);
int days = (int) (min / 60 / 24) % 365;
System.out.println((int) min + " minutes is approximately " + years + " years and " + days + " days");
}
}
OUTPUT:
7. Write a Java program that prints current time in GMT
package com.company;
import java.util.*;
import java.text.*;
public class Main {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss zzz");
Date date = new Date();
System.out.println("Local Time: " + sdf.format(date));
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("GMT Time : " + sdf.format(date));
}
}
OUTPUT:
8. Design a program in Java to solve quadratic equations using if, if else
package com.company;
import java.util.Scanner;
public class Main{
public static void main(String[] Strings) {
Scanner input = new Scanner(System.in);
System.out.print("Input a: ");
double a = input.nextDouble();
System.out.print("Input b: ");
double b = input.nextDouble();
System.out.print("Input c: ");
double c = input.nextDouble();
double result = b * b - 4.0 * a * c;
if (result > 0.0) {
double r1 = (-b + Math.pow(result, 0.5)) / (2.0 * a);
double r2 = (-b - Math.pow(result, 0.5)) / (2.0 * a);
System.out.println("The roots are " + r1 + " and " + r2);
}
else if (result == 0.0) {
double r1 = -b / (2.0 * a);
System.out.println("The root is " + r1);
}
else {
System.out.println("The equation has no real roots.");
}
}
}
OUTPUT:
9. Write a Java program to determine greatest number of three numbers
package com.company;
import java.util.Scanner;
public class Main{
public static void main(String[] Strings) {
int a, b, c, largest, temp;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first number:");
a = sc.nextInt();
System.out.println("Enter the second number:");
b = sc.nextInt();
System.out.println("Enter the third number:");
c = sc.nextInt();
temp=a>b?a:b;
largest=c>temp?c:temp;
System.out.println("The largest number is: "+largest);
}
}
OUTPUT:
10. Write program that gets a number from the user and generates an integer
between 1and 7 subsequently should display the name of the weekday as per
that number
package com.company;
import java.util.Scanner;
public class Main{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Input number: ");
int day = in.nextInt();
System.out.println(getDayName(day));
}
public static String getDayName(int day) {
String dayName = "";
switch (day) {
case 1: dayName = "Monday"; break;
case 2: dayName = "Tuesday"; break;
case 3: dayName = "Wednesday"; break;
case 4: dayName = "Thursday"; break;
case 5: dayName = "Friday"; break;
case 6: dayName = "Saturday"; break;
case 7: dayName = "Sunday"; break;
default:dayName = "Invalid day range";
}
return dayName;
}
}
OUTPUT:
11. Construct a Java program to find the number of days in a month
package com.company;
import java.util.Scanner;
public class Main{
public static void main(String[] strings) {
Scanner input = new Scanner(System.in);
int number_Of_DaysInMonth = 0;
String MonthOfName = "Unknown";
switch (month) {
case 1:
MonthOfName = "January";
number_Of_DaysInMonth = 31;
break;
case 2:
MonthOfName = "February";
if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
number_Of_DaysInMonth = 29;
} else {
number_Of_DaysInMonth = 28;
}
break;
case 3:
MonthOfName = "March";
number_Of_DaysInMonth = 31;
break;
case 4:
MonthOfName = "April";
number_Of_DaysInMonth = 30;
break;
case 5:
MonthOfName = "May";
number_Of_DaysInMonth = 31;
break;
case 6:
MonthOfName = "June";
number_Of_DaysInMonth = 30;
break;
case 7:
MonthOfName = "July";
number_Of_DaysInMonth = 31;
break;
case 8:
MonthOfName = "August";
number_Of_DaysInMonth = 31;
break;
case 9:
MonthOfName = "September";
number_Of_DaysInMonth = 30;
break;
case 10:
MonthOfName = "October";
number_Of_DaysInMonth = 31;
break;
case 11:
MonthOfName = "November";
number_Of_DaysInMonth = 30;
break;
case 12:
MonthOfName = "December";
number_Of_DaysInMonth = 31;
}
System.out.print(MonthOfName + " " + year + " has " + number_Of_DaysInMonth + " days\n");
}
}
OUTPUT:
12. Write a program to sum values of an Single Dimensional array
package com.company;
import java.util.Arrays;
import java.util.Scanner;
public class Main{
public static void main(String args[]){
System.out.println("Enter the required size of the array :: ");
Scanner s = new Scanner(System.in);
int size = s.nextInt();
int myArray[] = new int [size];
int sum = 0;
System.out.println("Enter the elements of the array one by one ");
for(int i=0; i<size; i++){
myArray[i] = s.nextInt();
sum = sum + myArray[i];
}
System.out.println("Elements of the array are: "+Arrays.toString(myArray));
System.out.println("Sum of the elements of the array ::"+sum);
}
}
OUTPUT:
13. Design & execute a program in Java to sort a numeric array and a string
array
package com.company;
import java.util.Arrays;
import java.util.Scanner;
public class Main{
public static void main(String[] args){
int[] my_array1 = {
10, 2, 34, 56, 20,
58, 24, 12, 72, 65,
14, 21, 1, 29};
String[] my_array2 = {
"Java",
"Python",
"PHP",
"C Programming",
};
System.out.println("Original numeric array : "+Arrays.toString(my_array1));
Arrays.sort(my_array1);
System.out.println("Sorted numeric array : "+Arrays.toString(my_array1));
OUTPUT:
14. Calculate the average value of array elements through Java Program.
package com.company;
import java.util.Arrays;
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("Enter array size: ");
int size = s.nextInt();
int[] array = new int[size];
System.out.println("Enter array values : ");
for (int i = 0; i < size; i++) {
int value = s.nextInt();
array[i] = value;
}
int length = array.length;
int sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
double average = sum / length;
System.out.println("Average of array : " + average);
}
}
OUTPUT:
15. Write a Java program to test if an array contains a specific value
package com.company;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String args[]){
int[] myArray = {55, 45, 69, 44};
int num = 55;
for(int i = 0; i<myArray.length; i++){
if(num == myArray[i]){
System.out.println("Array contains the given element");
}
}
}
}
OUTPUT:
16. Find the index of an array element by writing a program in Java
package com.company;
import java.util.Scanner;
public class Main {
static int findIndex (int[] my_array, int t) {
if (my_array == null) return -1;
int len = my_array.length;
int i = 0;
while (i < len) {
if (my_array[i] == t) return i;
else i=i+1;
}
return -1;
}
public static void main(String[] args) {
int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};
System.out.println("Index position of 25 is: " + findIndex(my_array, 25));
System.out.println("Index position of 77 is: " + findIndex(my_array, 77));
}
}
OUTPUT:
17. Write a Java program to remove a specific element from an array
package com.company;
import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = {3,1,6,5,2,8,4};
int[] newArr = null;
int elementToBeDeleted = 5;
System.out.println("Original Array is: "+Arrays.toString(arr));
OUTPUT:
OUTPUT:
2) Count string length
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String args[]){
String s1="java";
String s2="python";
System.out.println("string length is: "+s1.length());
System.out.println("string length is: "+s2.length());
}
}
OUTPUT:
3) Convert upper case to lower case & vice versa
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String str1="Java Programming";
StringBuffer newStr=new StringBuffer(str1);
for(int i = 0; i < str1.length(); i++) {
if(Character.isLowerCase(str1.charAt(i))) {
newStr.setCharAt(i, Character.toUpperCase(str1.charAt(i)));
}
else if(Character.isUpperCase(str1.charAt(i))) {
newStr.setCharAt(i, Character.toLowerCase(str1.charAt(i)));
}
}
System.out.println("String after case conversion : " + newStr);
}
}
OUTPUT:
4) Concatenate two strings
package com.company;
public class Main {
public static void main(String args[]){
String s1="Java ";
String s2="Programming";
String s3=s1.concat(s2);
System.out.println(s3);
}
}
OUTPUT:
5) Print a substring
package com.company;
public class Main {
public static void main(String args[]){
String s="JavaProgramming";
System.out.println("Original String: " + s);
System.out.println("Substring starting from index 4: " +s.substring(4));
System.out.println("Substring starting from index 0 to 4: "+s.substring(0,4));
}
}
OUTPUT:
21. Developed Program & design a method to find the smallest number among
three numbers.
import java.util.Scanner;
public class Exercise1 {
Output
22. Compute the average of three numbers through a Java Program.
import java.util.Scanner;
public class JavaExample {
OUTPUT
23. Write a Program & design a method to count all vowels in a string
import java.util.Scanner;
public class CountingVowels {
public static void main(String args[]){
int count = 0;
System.out.println("Enter a sentence :");
Scanner sc = new Scanner(System.in);
String sentence = sc.nextLine();
OUTPUT
Enter a sentence :
Hi how are you? welcome to JAVA
Number of vowels in the given sentence is 12
24. Write a Java method to count all words in a string
import java.util.Scanner;
public class Exercise5 {
OUTPUT
Input the string: The quick brown fox jumps over the lazy dog
Number of words in the string: 9
25 . Write a method in Java program to count all words in a string.
OUTPUT
B) Array Index Out Of B bound Exception
class Program1 {
public static void main(String[] args)
{
try {
int number[] = new int[20];
number[21] = 30 / 9;
// this statement will throw
// ArrayIndexOutOfBoundsException e
}
catch (ArrayIndexOutOfBoundsException
| ArithmeticException e) {
System.out.println(e.getMessage());
// print the message
}
}
}
OUTPUT
27. To represent the concept of Multithreading write a Java program
// Java code for thread creation by extending
// the Thread class
class MultithreadingDemo extends Thread {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}
// Main Class
public class Program1 {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}
OUTPUT
28. To represent the concept of all types of inheritance supported by Java, design a program
package com.company;
class Student {
String name = "ROHIT"; int
age =19;
String city = "Mohali"; int
marks = 55;
String tutorial = "JAVA";
public void show() {
System.out.println("Student inheriting properties from Person:"); } } class Main
extends Student {
int marks = 65;
String tutorial = "TechVidvan Tutorial of Java"; public
static void main(String[] args) {
Student obj = new Student();
obj.show();
System.out.println("Name of the student is: " + obj.name); System.out.println("Age
of the student is: " + obj.age); System.out.println("Student lives in: " + obj.city);
System.out.println("Student learns from: " + obj.tutorial);
System.out.println("Marks obtained by the student is: " + obj.marks);} }
OUTPUT
29. Write a program to implement Multiple Inheritance using interface
interface Printable{
void print();
}
interface Showable{
void show();
}
class Program1 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
OUTPUT
31. To write and read a plain text file, write a Java program.
import java.io.BufferedInputStream;
import java.io.FileInputStream;
class B {
public static void main(String[] args) {
try {
// Creates a FileInputStream
FileInputStream file = new FileInputStream("input.txt");
// Creates a BufferedInputStream
BufferedInputStream input = new BufferedInputStream(file);
while (i != -1) {
System.out.print((char) i);
catch (Exception e) {
e.getStackTrace();
}
}
}
32. Write a Java program to append text to an existing file.
import java.io.*;
public class Program32 {
new File("C:\\Users\\CC\\IdeaProjects\\Java-
learning\\src\\com\\learning\\textfile.txt");
BufferedReader br = new BufferedReader(new FileReader((file))); String
before;
System.out.println("***Before Append text***"); while
((before=br.readLine())!=null){
System.out.println(before);
}String str1 = "\nappend text";
String filename = "C:\\Users\\CC\\IdeaProjects\\Java- learning\\
src\\com\\learning\\textfile.txt";
BufferedWriter bw = new BufferedWriter(new FileWriter(filename,true));
bw.write(str1);
bw.close();
BufferedReader b_read = new BufferedReader(new FileReader((file))); String
after;
System.out.println("***After Append text***"); while
((after=b_read.readLine())!=null){
System.out.println(after);
}}}
OUTPUT:
33. Design a program in Java to get a list of all file/directory names from the given.
import java.io.File;
public class Program33 {
public static void main(String[] args) { File
filePath = new File("C:\\Users"); String[]
contents = filePath.list();
System.out.println("List of files and directories in the specified path:"); assert
contents != null;
for (String content : contents)
{ System.out.println(content);
}
}
}
OUTPUT
34. Develop a Java program to check if a file or directory specified by pathname exists or not.
import java.io.File;
public class {
public static void main(String[] args) { try {
File file = new File("C:\\Users\\CC\\IdeaProjects\\Java- learning\\
src\\com\\learning\\textfile.txt");
System.out.println(file.exists());
} catch(Exception e)
{ e.printStackTrace();
}
}
}
OUTPUT
35.Write a Java program to check if a file or directory has read and write
permission.
import java.io.File;
public class Program35 {
public static void main(String[] args) {
File file = new File("C:\\Users\\CC\\IdeaProjects\\
Java- learning\\src\\com\\learning\\textfile.txt");
if (file.canWrite()){
System.out.println(file.getAbsolutePath() + " can write.\n");
} else {
System.out.println(file.getAbsolutePath() + " cannot write.\n");
}
if (file.canRead()){
System.out.println(file.getAbsolutePath() + " can read.\n");
} else {
System.out.println(file.getAbsolutePath() + " cannot read.\n");
}
}
}
OUTPUT