"" Basic Java coding-related Question Part-1

Basic Java coding-related Question Part-1


Q1.Write a short Java method, inputAllBase Types, that inputs a different value of each base type from the standard input device and prints it back to the standard output device.

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        inputAllBaseTypes();

    }

   

    public static void inputAllBaseTypes() {

        Scanner scanner = new Scanner(System.in);

       

        System.out.print("Enter a boolean value: ");

        boolean boolValue = scanner.nextBoolean();

       

        System.out.print("Enter a byte value: ");

        byte byteValue = scanner.nextByte();

       

        System.out.print("Enter a short value: ");

        short shortValue = scanner.nextShort();

        System.out.print("Enter an int value: ");

        int intValue = scanner.nextInt();

       

        System.out.print("Enter a long value: ");

        long longValue = scanner.nextLong();

       

        System.out.print("Enter a float value: ");

        float floatValue = scanner.nextFloat();

       

        System.out.print("Enter a double value: ");

        double doubleValue = scanner.nextDouble();

       

        System.out.print("Enter a char value: ");

        char charValue = scanner.next().charAt(0);

       

        System.out.println("Boolean value: " + boolValue);

        System.out.println("Byte value: " + byteValue);

        System.out.println("Short value: " + shortValue);

        System.out.println("Int value: " + intValue);

        System.out.println("Long value: " + longValue);

        System.out.println("Float value: " + floatValue);

        System.out.println("Double value: " + doubleValue);

        System.out.println("Char value: " + charValue);

       

        scanner.close();

    }}

Q2 Suppose that we create an array A of GameEntry objects, which has an integer scores field, and we clone A and store the result in an array B. If we then im- mediately set A[4].score equal to 550, what is the score value of the GameEntry object referenced by B[4]?

If we clone array A and store the result in array B, both arrays will initially contain references to the same GameEntry objects. Therefore, if we modify a GameEntry object in array A, the corresponding object in array B will also be affected because they point to the same memory location.

 

In this case, when we set A[4].score equal to 550, the score value of the corresponding GameEntry object referenced by B[4] will also be updated to 550. This is because both A[4] and B[4] reference the same GameEntry object in memory.

 

In other words, any changes made to the GameEntry objects in array A will be reflected in the corresponding GameEntry objects in array B since they share the same references.

 

Q3 Write a short Java method, isMultiple, that takes two long values, n and m, and returns true if and only if n is a multiple of m, that is, n = mi for some integer i.

public class Main {

    public static void main(String[] args) {

        long n = 15;

        long m = 3;

        boolean result = isMultiple(n, m);

        System.out.println(result);

    }

   

    public static boolean isMultiple(long n, long m) {

        if (m == 0) {

            throw new IllegalArgumentException("Cannot divide by zero");

        }

        

        return n % m == 0;

    }

}

 

Q4 Write a short Java method, isEven, that takes int i and returns true if and only if i is even. Your method cannot use the multiplication, modulus, or division operators, however.

public class Main {

    public static void main(String[] args) {

        int i = 10;

        boolean result = isEven(i);

        System.out.println(result);

    }

    public static boolean isEven(int i) {

        return (i & 1) == 0;

    }

}

n this example, the isEven method takes an integer i as input. It uses the bitwise AND operator (&) to check the LSB of i by ANDing it with the binary value 1. If the LSB is 0, it means that i is even, and the method returns true. Otherwise, it returns false.

You can change the value of i in the main method to test different scenarios.

 

Q5 Write a short Java method that takes an integer n and returns the sum of all positive integers less than or equal to n.

public class Main {

    public static void main(String[] args) {

        int n = 5;

        int sum = sumOfPositiveIntegers(n);

        System.out.println(sum);

    }

   

    public static int sumOfPositiveIntegers(int n) {

        if (n <= 0) {

            throw new IllegalArgumentException("Input must be a positive integer");

        }

       

        int sum = 0;

        for (int i = 1; i <= n; i++) {

            sum += i;

        }

       

        return sum;

    } }

 

Q6 Write a short Java method that takes an integer n and returns the sum of all the odd positive integers less than or equal to n.

public class Main {

    public static void main(String[] args) {

        int n = 10;

        int sum = sumOfOddPositiveIntegers(n);

        System.out.println(sum);

    }

   

    public static int sumOfOddPositiveIntegers(int n) {

        if (n <= 0) {

            throw new IllegalArgumentException("Input must be a positive integer");

        }

       

        int sum = 0;

        for (int i = 1; i <= n; i += 2) {

            sum += i;

        }

       

        return sum;

    }

}

 

R-1.7 Write a short Java method that takes an integer n and returns the sum of the squares of all positive integers less than or equal to n.

public class Main {

    public static void main(String[] args) {

        int n = 5;

        int sum = sumOfSquares(n);

        System.out.println(sum);

    }

   

    public static int sumOfSquares(int n) {

        if (n <= 0) {

            throw new IllegalArgumentException("Input must be a positive integer");

        }

       

        int sum = 0;

        for (int i = 1; i <= n; i++) {

            sum += i * i;

        }

       

        return sum;

    }

}

 

R-1.8 Write a short Java method that counts the number of vowels in a given character string.

public class Main {

    public static void main(String[] args) {

        String str = "Hello, World!";

        int vowelCount = countVowels(str);

        System.out.println(vowelCount);

    }

   

    public static int countVowels(String str) {

        if (str == null) {

            throw new IllegalArgumentException("Input string cannot be null");

        }

       

        int count = 0;

        str = str.toLowerCase(); // Convert the string to lowercase for case-insensitive matching

       

        for (int i = 0; i < str.length(); i++) {

            char c = str.charAt(i);

            if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {

                count++;

            }

        }

       

        return count;

    }

}

 

R-1.9 Write a short Java method that uses a StringBuilder instance to remove all the punctuation from a string s storing a sentence, for example, transforming the string "Let's try, Mike!" to "Lets try Mike".

public class Main {

    public static void main(String[] args) {

        String s = "Let's try, Mike!";

        String result = removePunctuation(s);

        System.out.println(result);

    }

   

    public static String removePunctuation(String s) {

        if (s == null) {

            throw new IllegalArgumentException("Input string cannot be null");

        }

       

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < s.length(); i++) {

            char c = s.charAt(i);

            if (Character.isLetterOrDigit(c) || Character.isWhitespace(c)) {

                sb.append(c);

            }

        }

       

        return sb.toString();

    }

}

 

R-1.10 Write a Java class, Flower, that has three instance variables of type String, int, and float, which respectively represent the name of the flower, its number of petals, and price. Your class must include a constructor method that initializes each variable to an appropriate value, and your class should include methods for setting the value of each type, and getting the value of each type.

public class Flower {

    private String name;

    private int numberOfPetals;

    private float price;

   

    public Flower(String name, int numberOfPetals, float price) {

        this.name = name;

        this.numberOfPetals = numberOfPetals;

        this.price = price;

    }

   

    public void setName(String name) {

        this.name = name;

    }

   

    public void setNumberOfPetals(int numberOfPetals) {

        this.numberOfPetals = numberOfPetals;

    }

   

    public void setPrice(float price) {

        this.price = price;

    }

   

    public String getName() {

        return name;

    }

   

    public int getNumberOfPetals() {

        return numberOfPetals;

    }

   

    public float getPrice() {

        return price;

    }

   

    public static void main(String[] args) {

        Flower flower = new Flower("Rose", 10, 4.99f);

       

        System.out.println("Flower name: " + flower.getName());

        System.out.println("Number of petals: " + flower.getNumberOfPetals());

        System.out.println("Price: $" + flower.getPrice());

       

        flower.setName("Lily");

        flower.setNumberOfPetals(6);

        flower.setPrice(2.99f);

       

        System.out.println("\nUpdated flower details:");

        System.out.println("Flower name: " + flower.getName());

        System.out.println("Number of petals: " + flower.getNumberOfPetals());

        System.out.println("Price: $" + flower.getPrice());

    }

}

 

p-1.26 Write a short Java program that takes all the lines input to standard input and writes them to standard output in reverse order. That is, each line is output in the correct order, but the ordering of the lines is reversed.

import java.util.ArrayList;

import java.util.Scanner;

 

public class ReverseLines {

    public static void main(String[] args) {

        ArrayList<String> lines = readLines();

        printLinesInReverse(lines);

    }

   

    public static ArrayList<String> readLines() {

        ArrayList<String> lines = new ArrayList<>();

        Scanner scanner = new Scanner(System.in);

       

        System.out.println("Enter lines of text (Enter blank line to stop):");

        String line;

        while (!(line = scanner.nextLine()).isEmpty()) {

            lines.add(line);

        }

       

        scanner.close();

        return lines;

    }

   

    public static void printLinesInReverse(ArrayList<String> lines) {

        System.out.println("\nLines in reverse order:");

        for (int i = lines.size() - 1; i >= 0; i--) {

            System.out.println(lines.get(i));

        }

    }

}

 

P-1.27 Write a Java program that can simulate a simple calculator, using the Java console as the exclusive input and output device. That is, each input to the calculator, be it a number, like 12.34 or 1034, or an operator, like + or =, can be done on a separate line. After each such input, you should output to the Java console what would be displayed on your calculator.

import java.util.Scanner;

 

public class SimpleCalculator {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        double result = 0.0;

       

        System.out.println("Simple Calculator");

        System.out.println("Enter 'q' to quit.");

        System.out.println("Enter a number or an operator (+, -, *, /):");

       

        while (true) {

            String input = scanner.nextLine();

           

            if (input.equalsIgnoreCase("q")) {

                System.out.println("Calculator has been quit.");

                break;

            }

           

            try {

                double value = Double.parseDouble(input);

                result = value;

                System.out.println("Result: " + result);

            } catch (NumberFormatException e) {

                result = calculate(result, input);

                System.out.println("Result: " + result);

            }

        }

       

        scanner.close();

    }

   

    public static double calculate(double currentValue, String operator) {

        Scanner scanner = new Scanner(System.in);

        double operand;

       

        switch (operator) {

            case "+":

                System.out.print("Enter the number to add: ");

                operand = scanner.nextDouble();

                currentValue += operand;

                break;

            case "-":

                System.out.print("Enter the number to subtract: ");

                operand = scanner.nextDouble();

                currentValue -= operand;

                break;

            case "*":

                System.out.print("Enter the number to multiply: ");

                operand = scanner.nextDouble();

                currentValue *= operand;

                break;

            case "/":

                System.out.print("Enter the number to divide: ");

                operand = scanner.nextDouble();

                if (operand != 0) {

                    currentValue /= operand;

                } else {

                    System.out.println("Error: Cannot divide by zero.");

                }

                break;

            default:

                System.out.println("Error: Invalid operator.");

                break;

        }

       

        scanner.nextLine(); // Consume the remaining new line character

       

        return currentValue;

    }

}

 

P-1.28 A common punishment for school children is to write out a sentence multiple times. Write a Java stand-alone program that will write out the following sentence one hundred times: "I will never spam my friends again." Your program should number each of the sentences and it should make eight different random- looking types.

import java.util.Random;

 

public class SentenceWriter {

    public static void main(String[] args) {

        String sentence = "I will never spam my friends again.";

       

        for (int i = 1; i <= 100; i++) {

            System.out.print(i + ". ");

            String modifiedSentence = addTypos(sentence);

            System.out.println(modifiedSentence);

        }

    }

   

    public static String addTypos(String sentence) {

        Random random = new Random();

        StringBuilder modifiedSentence = new StringBuilder();

       

        for (int i = 0; i < sentence.length(); i++) {

            char c = sentence.charAt(i);

            boolean makeTypo = random.nextInt(8) == 0; // 1/8 chance of making a typo

           

            if (makeTypo && Character.isLetter(c)) {

                char modifiedChar = generateRandomChar(c);

                modifiedSentence.append(modifiedChar);

            } else {

                modifiedSentence.append(c);

            }

        }

       

        return modifiedSentence.toString();

    }

   

    public static char generateRandomChar(char originalChar) {

        Random random = new Random();

        char modifiedChar;

       

        do {

            modifiedChar = (char) (random.nextInt(26) + 'a'); // Generate a random lowercase letter

        } while (modifiedChar == originalChar); // Ensure the modified char is different from the original char

       

        return modifiedChar;

    }

}

 

P-1.29 The birthday paradox says that the probability that two people in a room will have the same birthday is more than half, provided n, the number of people in the room, is more than 23. This property is not really a paradox, but many people find it surprising. Design a Java program that can test this paradox by a series of experiments on randomly generated birthdays, which test this paradox for n= 5, 10, 15, 20,..., 100.

import java.util.HashSet;

import java.util.Random;

import java.util.Set;

 

public class BirthdayParadoxTester {

    public static void main(String[] args) {

        int[] numberOfPeople = { 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100 };

       

        for (int n : numberOfPeople) {

            int numExperiments = 10000; // Number of experiments to run for each number of people

            int numMatches = 0; // Count of experiments where at least two people have the same birthday

           

            for (int i = 0; i < numExperiments; i++) {

                if (hasMatchingBirthdays(n)) {

                    numMatches++;

                }

            }

           

            double probability = (double) numMatches / numExperiments;

           

            System.out.printf("For %d people, the probability of a shared birthday is %.2f%%%n", n, probability * 100);

        }

    }

   

    public static boolean hasMatchingBirthdays(int n) {

        Random random = new Random();

        Set<Integer> birthdays = new HashSet<>();

        

        for (int i = 0; i < n; i++) {

            int birthday = random.nextInt(365); // Assume 365 possible birthdays (excluding leap years)

           

            if (birthdays.contains(birthday)) {

                return true; // Found a matching birthday

            }

           

            birthdays.add(birthday);

        }

       

        return false; // No matching birthday found

    }

}

 

Write a pseudo code description of a method that reverses an array of n integers, so that the numbers are listed in the opposite order than they were before, and compare this method to an equivalent Java method for doing the same thing.

public static void reverseArray(int[] array) {

    int start = 0;

    int end = array.length - 1;

 

    while (start < end) {

        int temp = array[start];

        array[start] = array[end];

        array[end] = temp;

        start++;

        end--;

    }

}

 

 C-1.15 Write a pseudo code description of a method for finding the smallest and larger numbers in an array of integers and compare that to a Java method that would do the same thing.

public static int[] findMinMax(int[] array) {

    if (array.length == 0) {

        return null;

    }

 

    int smallest = array[0];

    int largest = array[0];

 

    for (int i = 1; i < array.length; i++) {

        if (array[i] < smallest) {

            smallest = array[i];

        }

 

        if (array[i] > largest) {

            largest = array[i];

        }

    }

 

    return new int[]{smallest, largest};

}

 

C-1.16 Write a short java program that takes as input three integers, a, b, and c, from the lava console and determines if they can be used in a correct arithmetic formula (in the given order), like "a+b=c," "a=b-c," or "a *b=c."

import java.util.Scanner;

 

public class ArithmeticFormulaChecker {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

 

        System.out.print("Enter the first integer (a): ");

        int a = scanner.nextInt();

 

        System.out.print("Enter the second integer (b): ");

        int b = scanner.nextInt();

 

        System.out.print("Enter the third integer (c): ");

        int c = scanner.nextInt();

 

        boolean isValid = checkArithmeticFormula(a, b, c);

 

        if (isValid) {

            System.out.println("The integers can be used in a correct arithmetic formula.");

        } else {

            System.out.println("The integers cannot be used in a correct arithmetic formula.");

        }

    }

 

    public static boolean checkArithmeticFormula(int a, int b, int c) {

        return (a + b == c) || (a == b - c) || (a * b == c);

    }

}

 

C-1.19 Write a Java program that can take a positive integer greater than 2 as input and write out the number of times one must repeatedly divide this number by 2 before getting a value less than 2.

import java.util.Scanner;

 

public class DivideByTwoCounter {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

 

        System.out.print("Enter a positive integer greater than 2: ");

        int number = scanner.nextInt();

 

        int count = countDivideByTwo(number);

 

        System.out.println("Number of divisions by 2 before getting a value less than 2: " + count);

    }

 

    public static int countDivideByTwo(int number) {

        int count = 0;

 

        while (number >= 2) {

            number /= 2;

            count++;

        }

 

        return count;

    }

}

 

C-1.20 Write a Java method that takes an array of float values and determines if all the numbers are different from each other (that is, they are distinct).

public static boolean areAllDistinct(float[] array) {

    for (int i = 0; i < array.length; i++) {

        for (int j = i + 1; j < array.length; j++) {

            if (array[i] == array[j]) {

                return false; // Found a duplicate

            }

        }

    }

 

    return true; // All numbers are distinct

}

 

C-1 23 Write a short Java program that takes two arrays a and b of length n storing int values, and returns the dot product of a and b. That is, it returns an array c of length n such that c[i]=a[i] b[i], for i = 0,...,n-1.

public class DotProductCalculator {

    public static void main(String[] args) {

        int[] a = {1, 2, 3}; // Example array a

        int[] b = {4, 5, 6}; // Example array b

 

        int[] result = calculateDotProduct(a, b);

 

        System.out.println("Dot Product: " + java.util.Arrays.toString(result));

    }

 

    public static int[] calculateDotProduct(int[] a, int[] b) {

        if (a.length != b.length) {

            throw new IllegalArgumentException("Arrays must have the same length");

        }

 

        int n = a.length;

        int[] c = new int[n];

 

        for (int i = 0; i < n; i++) {

            c[i] = a[i] * b[i];

        }

 

        return c;

    }

}

 

C-1.21 Write a Java method that takes an array containing the set of all integers in the range 1 to 52 and shuffles it into random order. Your method should output each possible order with equal probability.

import java.util.Arrays;

import java.util.Random;

 

public class ArrayShuffler {

    public static void main(String[] args) {

        int[] array = createArray(52); // Create an array with integers from 1 to 52

        shuffleArray(array); // Shuffle the array

        System.out.println(Arrays.toString(array)); // Print the shuffled array

    }

 

    public static int[] createArray(int size) {

        int[] array = new int[size];

        for (int i = 0; i < size; i++) {

            array[i] = i + 1;

        }

        return array;

    }

 

    public static void shuffleArray(int[] array) {

        Random random = new Random();

 

        for (int i = array.length - 1; i > 0; i--) {

            int j = random.nextInt(i + 1);

 

            int temp = array[i];

            array[i] = array[j];

            array[j] = temp;

        }

    }

}

 

Post a Comment

0 Comments