Java Questions Part9 - Programs on File Handling, Date etc..

1.Write a Java program where input- today date and output- week day or weekend

Answer:
import java.time.DayOfWeek;

import java.time.LocalDate;

import java.time.Month;

import java.time.temporal.ChronoField;

 public class InputDayOutputWeekDayWeekend {

                public static void main(String[] argv) {

                                System.out.println("Enter Any Date below:");

                                int enterYear = 2016;

                                int enterMonth = 01;

                                int enterDay = 04;

                                LocalDate localDate = LocalDate.of(enterYear, enterMonth, enterDay);

                                // LocalDate date = LocalDate.now();

                                DayOfWeek day = DayOfWeek.of(localDate.get(ChronoField.DAY_OF_WEEK));

                                switch (day) {

                                case SATURDAY:

                                                System.out.println("Weekend - Saturday");

                                                break;

                                case SUNDAY:

                                                System.out.println("Weekend - Sunday");

                                                break;

                                default:

                                                System.out.println("Day of the week is: " + day);

                                                System.out.println("Not a Weekend");

                                                break;

                                }

                }

}

Output:
Enter Any Date below:

Day of the week is: MONDAY

Not a Weekend

2. Write a Java program to print the command line arguments?

3. Write a Java program to print the input from scanner?

Answer:
public class Input {

    public static void main(String[] args) {

                Scanner input = new Scanner(System.in);

                System.out.print("Enter an integer: ");

                int number = input.nextInt();

                System.out.println("You entered " + number);

    }

}

Output:
Enter an integer: 12

You entered 12

4. Write a Java program to convert from Fahrenheit to Celsius?

Answer:
import java.util.Scanner;

public class FC

{
                public static void main(String arg[])         

                {
                    double f,c;

                    Scanner sc=new Scanner(System.in);

                    System.out.println("Choose type of conversion \n 1.Fahrenheit to Celsius  \n 2.Celsius to Fahrenheit");

                   int ch=sc.nextInt();

                    switch(ch)

                    {

                    case 1:  System.out.println("Enter  Fahrenheit temperature");

                                  f=sc.nextDouble();

                                  c=(f-32)*5/9;

                                  System.out.println("Celsius temperature is = "+c);

                                  break;

                    case 2:  System.out.println("Enter  Celsius temperature");

                                  c=sc.nextDouble();

                                  f=((9*c)/5)+32;

                                  System.out.println("Fahrenheit temperature is = "+f);

                                  break;

                   default:  System.out.println("please choose valid choice");

                   } 

                }

}

Output:
1.Fahrenheit to Celsius 

2.Celsius to Fahrenheit

1

Enter  Fahrenheit temperature

190

Celsius temperature is = 87.77777777777777

5. Write a Java program to demonstrate indexOf() ?

Answer:
public class IndexOfExample {

                public static void main(String[] args) {

                                String s1="this is index of example"; 

                                //passing substring 

                                int index1=s1.indexOf("is");//returns the index of is substring 

                                int index2=s1.indexOf("index");//returns the index of index substring 

                                System.out.println(index1+"  "+index2);//2 8

                                //passing substring with from index 

                                int index3=s1.indexOf("is",4);//returns the index of is substring after 4th index 

                                System.out.println(index3);//5 i.e. the index of another is 

                                //passing char value 

                                int index4=s1.indexOf('s');//returns the index of s char value 

                                System.out.println(index4);//3 

                }

}

Output:
2  8

5

3

6. Write a Java program to print date and time?

Answer:
import java.util.Calendar;

import java.util.GregorianCalendar;

public class GetCurrentDateAndTime

{
                   public static void main(String args[])

                   {

                      int day, month, year;

                      int second, minute, hour;

                      GregorianCalendar date = new GregorianCalendar();

                      day = date.get(Calendar.DAY_OF_MONTH);

                      month = date.get(Calendar.MONTH);

                      year = date.get(Calendar.YEAR);

                      second = date.get(Calendar.SECOND);

                      minute = date.get(Calendar.MINUTE);

                      hour = date.get(Calendar.HOUR);

                      System.out.println("Current date is  "+day+"/"+(month+1)+"/"+year);

                      System.out.println("Current time is  "+hour+" : "+minute+" : "+second);

                   }

                } 
 
Output:
Current date is  4/1/2020

Current time is  7 : 9 : 12

7. Write a Java program to demonstrate SQL Date?

Answer: The java.sql.Date class represents only date in java. It inherits java.util.Date class.
The java.sql.Date instance is widely used in JDBC because it represents the date that can be stored in database.
public class SQLDateExample{ 

    public static void main(String[] args) { 

        long millis=System.currentTimeMillis(); 

        java.sql.Date date=new java.sql.Date(millis); 

        System.out.println(date); 

    } 

} 

Output:
2020-01-04

8. Write a Java program to demonstrate Date format?

Answer: The java.text.SimpleDateFormat class provides methods to format and parse date and time in java. The SimpleDateFormat is a concrete class for formatting and parsing date which inherits java.text.DateFormat class. Notice that formatting means converting date to string and parsing means converting string to date.
import java.text.SimpleDateFormat;
import java.util.Date.

public class SimpleDateFormatExample { 

public static void main(String[] args) { 

    Date date = new Date(); 

    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); 

    String strDate= formatter.format(date); 

    System.out.println(strDate); 

} 

} 

Output:
04/01/2020

9. Write a Java program to write data into the text files?

Answer:
import java.io.BufferedOutputStream;

import java.io.BufferedWriter;

import java.io.DataOutputStream;

import java.io.FileOutputStream;

import java.io.FileWriter;

import java.io.IOException;

import java.io.PrintWriter;

import java.io.RandomAccessFile;

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;



public class WriteIntoFile {

                public static void usingFileChannel() throws IOException {

                                String fileContent = "Write into File Using FileChannel";

                                RandomAccessFile stream = new RandomAccessFile("D:\\Sample.txt", "rw");

                                FileChannel channel = stream.getChannel();

                                byte[] strBytes = fileContent.getBytes();

                                ByteBuffer buffer = ByteBuffer.allocate(strBytes.length);

                                buffer.put(strBytes);

                                buffer.flip();

                                channel.write(buffer);

                                stream.close();

                                channel.close();

                }

                public static void usingDataOutputStream() throws IOException {

                                String fileContent = "Write into File Using DataOutputStream";

                                FileOutputStream outputStream = new FileOutputStream("D:\\Sample1.txt");

                                DataOutputStream dataOutStream = new DataOutputStream(new                    BufferedOutputStream(outputStream));

                                dataOutStream.writeUTF(fileContent);

                                dataOutStream.close();

                }

                public static void usingFileOutputStream() throws IOException {

                                String fileContent = "Write into File using usingFileOutputStream";

                                FileOutputStream outputStream = new FileOutputStream("D:\\Sample2.txt");

                                byte[] strToBytes = fileContent.getBytes();

                                outputStream.write(strToBytes);

                                outputStream.close();

                }

                public static void usingFileWriter() throws IOException {

                                String fileContent = "Write into File using usingFileWriter";

                                FileWriter fileWriter = new FileWriter("D:\\Sample3.txt");

                                fileWriter.write(fileContent);

                                fileWriter.close();

                }

                public static void usingPrintWriter() throws IOException {

                                String fileContent = "Write into File using usingPrintWriter";

                                FileWriter fileWriter = new FileWriter("D:\\Sample4.txt");

                                PrintWriter printWriter = new PrintWriter(fileWriter);

                                printWriter.print(fileContent);

                                printWriter.close();

                }

                public static void usingBufferedWritter() throws IOException {

                                String fileContent = "Write into File using usingBufferedWritter";

                                BufferedWriter writer = new BufferedWriter(new FileWriter("D:\\Sample5.txt"));

                                writer.write(fileContent);

                                writer.close();

                }

                public static void main(String[] args) throws IOException {

                                System.out.println("Write File using FileChannel");

                                usingFileChannel();

                                System.out.println("Write File using DataOutputStream");

                                // usingDataOutputStream();

                                System.out.println("Write File using usingFileOutputStream");

                                usingFileOutputStream();

                                System.out.println("Write File using usingFileWriter");

                                usingFileWriter();

                                System.out.println("Write File using usingPrintWriter");

                                usingPrintWriter();

                                System.out.println("Write File using usingBufferedWritter");

                                usingBufferedWritter();

                }

}

10. Write a Java program to read data from the text files?

Answer:
import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.util.Scanner;



public class Readfile {

                public static void main(String[] args) throws IOException {

                                fileReader();

                                bufferedReader();

                                usingScanner();

                }

                public static void fileReader() throws IOException {

                                String fileName = "D:\\Sample2.txt";

                                File file = new File(fileName);

                                FileReader fr = new FileReader(file);

                                BufferedReader br = new BufferedReader(fr);

                                String line;

                                while ((line = br.readLine()) != null) {

                                                // process the line

                                                System.out.println(line);

                                }

                }

                public static void bufferedReader() throws IOException {

                                String fileName = "D:\\Sample2.txt";

                                File file = new File(fileName);

                                FileInputStream fis = new FileInputStream(file);

                                InputStreamReader isr = new InputStreamReader(fis);

                                BufferedReader br = new BufferedReader(isr);

                                String line;

                                while ((line = br.readLine()) != null) {

                                                // process the line

                                                System.out.println(line);

                                }

                                br.close();

                }



                public static void usingScanner() throws IOException {

                                Path path = Paths.get("D:\\Sample2.txt");

                                Scanner scanner = new Scanner(path);

                                System.out.println("Read text file using Scanner");

                                // read line by line

                                while (scanner.hasNextLine()) {

                                                // process each line

                                                String line = scanner.nextLine();

                                                System.out.println(line);

                                }

                                scanner.close();

                }

}

11. Program to display sysdate and time in text file (using file handling)?

Answer:
import java.io.FileWriter;

import java.io.IOException;

import java.text.SimpleDateFormat;

import java.util.Date;

public class WriteDateTimeIntoFile {

                public static void main(String[] args) throws IOException {

                                Date date = new Date();

                                SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

                                System.out.println(formatter.format(date));

                                FileWriter fileWriter = new FileWriter("D:\\Sample3.txt");

                                fileWriter.write(formatter.format(date));

                                fileWriter.close();

                }

}

12. Write a Java program to demonstrate creating a constructor?

Answer: Please refer answer given in question#13

13. Write a Java program to demonstrate constructor overloading?

Answer:
public class ConstructorOverloading {

                private int stuID;

                private String stuName;

                private int stuAge;

                public ConstructorOverloading(int num1, String str, int num2) {

                                // Parameterized constructor

                                stuID = num1;

                                stuName = str;

                                stuAge = num2;

                }

                public ConstructorOverloading() {

                                // Default constructor

                                stuID = 100;

                                stuName = "John";

                                stuAge = 18;

                }

                // Getter and setter methods

                public int getStuID() {

                                return stuID;

                }

                public void setStuID(int stuID) {

                                this.stuID = stuID;

                }
                public String getStuName() {

                                return stuName;

                }

                public void setStuName(String stuName) {

                                this.stuName = stuName;

                }

                public int getStuAge() {

                                return stuAge;

                }

                public void setStuAge(int stuAge) {

                                this.stuAge = stuAge;

                }

                public static void main(String args[]) {

                                // This object creation would call the default constructor

                                ConstructorOverloading myobj = new ConstructorOverloading();

                                System.out.println("Student Name is: " + myobj.getStuName());

                                System.out.println("Student Age is: " + myobj.getStuAge());

                                System.out.println("Student ID is: " + myobj.getStuID());

                                /*

                                 * This object creation would call the parameterized constructor

                                 * StudentData(int, String, int)

                                 */

                                ConstructorOverloading myobj2 = new ConstructorOverloading(555, "Robert", 25);

                                System.out.println("Student Name is: " + myobj2.getStuName());

                                System.out.println("Student Age is: " + myobj2.getStuAge());

                                System.out.println("Student ID is: " + myobj2.getStuID());

                }

}

Output:
Student Name is: John

Student Age is: 18

Student ID is: 100

Student Name is: Robert

Student Age is: 25

Student ID is: 555

14. Write a Java program to demonstrate the creation of Interface ?

Answer: An interface in java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.
Java Interface also represents the IS-A relationship. There are mainly three reasons to use interface. They are given below. It is used to achieve abstraction. By interface, we can support the functionality of multiple inheritance. It can be used to achieve loose coupling.

In this example, the Drawable interface has only one method. Its implementation is provided by Rectangle and Circle classes. In a real scenario, an interface is defined by someone else, but its implementation is provided by different implementation providers. Moreover, it is used by someone else. The implementation part is hidden by the user who uses the interface.
//Interface declaration: by first user.

 

interface Drawable{ 

void draw(); 

} 

//Implementation: by second user 

class Rectangle implements Drawable{ 

public void draw(){System.out.println("drawing rectangle");} 

} 

class Circle implements Drawable{ 

public void draw(){System.out.println("drawing circle");} 

} 

//Using interface: by third user 

class TestInterface1{ 

public static void main(String args[]){ 

Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable() 

d.draw(); 

}} 

Output:
drawing circle

15. Write a Java program to demonstrate garbage collection?

Answer:
public class GarbageCollectionExample {

                public void finalize() {

                                System.out.println("object is garbage collected");

                }

                public static void main(String args[]) {

                                GarbageCollectionExample s1 = new GarbageCollectionExample();

                                GarbageCollectionExample s2 = new GarbageCollectionExample();

                                s1 = null;

                                s2 = null;

                                System.gc();

                }

}

Output:
object is garbage collected

object is garbage collected

16. Write a Java program to get the IP Address of own machine?

Answer:
import java.net.InetAddress;

import java.net.UnknownHostException;

public class GetIPAddress {

                public static void main(String[] args) throws UnknownHostException {

                                InetAddress IP = InetAddress.getLocalHost();

        System.out.println("IP of my system is := "+IP.getHostAddress());

                }

}

Output:
IP of my system is := 192.168.0.15

17. Write a Java program to open a notepad?

Answer:
import java.io.IOException;

public class NotePad {

                public static void main(String[] args) {

                                Runtime rs = Runtime.getRuntime();

                                try {

                                                rs.exec("notepad");

                                } catch (IOException e) {

                                                System.out.println(e);

                                }

                }

}

18. Write a Java program to check Regular Expressions?

Answer:
import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class RegularExpressions {

                public static void main(String args[]) {

                                // 1st way

                                Pattern p = Pattern.compile(".s");// . represents single character

                                Matcher m = p.matcher("as");

                                boolean b = m.matches();

                                // 2nd way

                                boolean b2 = Pattern.compile(".s").matcher("as").matches();

                                // 3rd way

                                boolean b3 = Pattern.matches(".s", "as");

                                System.out.println(b + " " + b2 + " " + b3);

                }

}

Output:

true true true

No comments:

Post a Comment