write a java program for a) Using javap, view the methods of the following classes from the lang package: java.lang.Object , java.lang.String and java.util.Scanner. and also Compile sample program 8. Type the following command and view the bytecodes. javap -c MyClass.

 write a java program for a) Using javap, view the methods of the following classes from the lang package: java.lang.Object , java.lang.String and java.util.Scanner. and also Compile sample program 8. Type the following command and view the bytecodes. javap -c MyClass.


Here's a Java program that uses javap to view the methods of the java.lang.Object, java.lang.String, and java.util.Scanner classes and also compiles a sample program and displays its bytecode using javap -c command:

public class JavapDemo {
    public static void main(String[] args) {
        // View methods of java.lang.Object class
        System.out.println("Methods of java.lang.Object class:");
        viewMethods(Object.class);

        // View methods of java.lang.String class
        System.out.println("\nMethods of java.lang.String class:");
        viewMethods(String.class);

        // View methods of java.util.Scanner class
        System.out.println("\nMethods of java.util.Scanner class:");
        viewMethods(Scanner.class);

        // Compile and display bytecode of MyClass
        System.out.println("\nBytecode of MyClass:");
        compileAndDisplayBytecode("MyClass.java", "MyClass");
    }

    // Method to view methods of a class using javap
    public static void viewMethods(Class clazz) {
        try {
            Runtime.getRuntime().exec("javap -p " + clazz.getName()).waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Method to compile and display bytecode of a Java program
    public static void compileAndDisplayBytecode(String fileName, String className) {
        try {
            // Compile the Java program using the command line
            Process process = Runtime.getRuntime().exec("javac " + fileName);
            process.waitFor();

            // Display the bytecode using javap
            Process bytecodeProcess = Runtime.getRuntime().exec("javap -c " + className);
            BufferedReader reader = new BufferedReader(new InputStreamReader(bytecodeProcess.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


The program first uses javap to view the methods of the java.lang.Object, java.lang.String, and java.util.Scanner classes by calling the viewMethods method. Then, it compiles a sample program named MyClass.java using the compileAndDisplayBytecode method and displays its bytecode using the javap -c command.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.