└── answers /answers: -------------------------------------------------------------------------------- 1 | 47.1.1 2 | In non-static init block 1 3 | In non-static init block 2 4 | In constructor 5 | value = 3 6 | In non-static init block 1 7 | In non-static init block 2 8 | In constructor 9 | value = 3 10 | 11 | 47.1.2 12 | Before any constructor is called, every time an instance of the class is created. 13 | 14 | 47.1.3 15 | 16 | import java.util.Scanner; 17 | 18 | class Person { 19 | private String name; 20 | private int age; 21 | private String address; 22 | 23 | public Person(String name, int age, String address) { 24 | this.name = name; 25 | this.age = age; 26 | this.address = address; 27 | } 28 | 29 | 30 | public String getName() { 31 | return name; 32 | } 33 | 34 | public int getAge() { 35 | return age; 36 | } 37 | 38 | public String getAddress() { 39 | return address; 40 | } 41 | } 42 | 43 | class PersonManager { 44 | private Person person; 45 | 46 | { 47 | Scanner scanner = new Scanner(System.in); 48 | System.out.print("Enter name:"); 49 | String name = scanner.nextLine(); 50 | System.out.print("Enter age:"); 51 | int age = scanner.nextInt(); 52 | scanner.nextLine(); // consume newline 53 | System.out.print("Enter address:"); 54 | String address = scanner.nextLine(); 55 | 56 | person = new Person(name, age, address); 57 | } 58 | 59 | public void printPersonDetails() { 60 | System.out.println("Name: " + person.getName()); 61 | System.out.println("Age: " + person.getAge()); 62 | System.out.println("Address: " + person.getAddress()); 63 | } 64 | } 65 | 66 | public class PersonMain { 67 | public static void main(String[] args) { 68 | PersonManager manager = new PersonManager(); 69 | manager.printPersonDetails(); 70 | } 71 | } 72 | 73 | 74 | 75 | 47.2.1 76 | 77 | In static init block 1 78 | In static init block 2 79 | In constructor 80 | In constructor 81 | 82 | 83 | 47.2.2 84 | import java.util.Scanner; 85 | 86 | public class StaticInitializationExample { 87 | // Static variable declaration 88 | static int x; 89 | 90 | // Static initialization block 91 | static { 92 | Scanner scanner = new Scanner(System.in); 93 | System.out.print("value of x: "); 94 | x = scanner.nextInt(); 95 | System.out.println("Static block initialized with x = " + x); 96 | } 97 | 98 | public static void main(String[] args) { 99 | System.out.println("Inside main method"); 100 | System.out.println("Value of x: " + x); 101 | } 102 | } 103 | 104 | 47.2.3 105 | 106 | import java.util.Scanner; 107 | 108 | public class MultipleStaticBlocksDemo { 109 | static int a; 110 | 111 | static { 112 | Scanner scanner = new Scanner(System.in); 113 | System.out.print("value for a: "); 114 | a = scanner.nextInt(); 115 | System.out.println("First static block executed"); 116 | } 117 | 118 | static { 119 | System.out.println("Second static block executed"); 120 | } 121 | 122 | public static void main(String[] args) { 123 | System.out.println("Static block initialized with a = " + a); 124 | } 125 | } 126 | 127 | 48.1.1 128 | 129 | 130 | class A { 131 | static int aStaticField; // static field 132 | int instanceField; // instance field 133 | 134 | // Constructor to initialize instance field 135 | A(int instanceFieldValue) { 136 | this.instanceField = instanceFieldValue; 137 | } 138 | } 139 | 140 | public class StaticFieldDemo { 141 | public static void main(String[] args) { 142 | A a1 = new A(3); 143 | A a2 = new A(4); 144 | 145 | // Accessing static field using class name 146 | A.aStaticField = 5; 147 | 148 | // Printing the values of instanceField and aStaticField for each instance 149 | System.out.println("a1 = A [instanceField = " + a1.instanceField + ", aStaticField = " + A.aStaticField + "]"); 150 | System.out.println("a2 = A [instanceField = " + a2.instanceField + ", aStaticField = " + A.aStaticField + "]"); 151 | System.out.println("A.aStaticField = " + A.aStaticField); 152 | } 153 | } 154 | 48.1.2 155 | 156 | public class CounterTest { 157 | private static int count = 1; 158 | 159 | public static void increment() { 160 | count++; 161 | } 162 | 163 | public static void decrement() { 164 | count--; 165 | } 166 | 167 | public static void displayCount() { 168 | System.out.println("Current value of count is: " + count); 169 | } 170 | 171 | public static void main(String[] args) { 172 | // Test case 1 173 | displayCount(); // Initial value of count is 0 174 | 175 | increment(); // Increment count by 1 176 | displayCount(); // Current value of count is 1 177 | 178 | 179 | decrement(); // Decrement count by 1 180 | displayCount(); // Current value of count is 1 181 | } 182 | } 183 | 184 | 48.1.3 185 | import java.util.Scanner; 186 | 187 | public class Quiz { 188 | private static double averageScore = 0; 189 | private static int numQuizzes = 0; 190 | 191 | public static void updateAverage(double score) { 192 | averageScore = (averageScore * numQuizzes + score) / (numQuizzes + 1); 193 | numQuizzes++; 194 | System.out.println("Current average score: " + averageScore); 195 | } 196 | 197 | public static void main(String[] args) { 198 | Scanner scanner = new Scanner(System.in); 199 | while (true) { 200 | System.out.print("Enter quiz score (or type 'q' to quit): "); 201 | String input = scanner.nextLine(); 202 | if (input.equalsIgnoreCase("q")) { 203 | break; 204 | } 205 | try { 206 | double score = Double.parseDouble(input); 207 | updateAverage(score); 208 | } catch (NumberFormatException e) { 209 | System.out.println("Invalid input. Please enter a valid number or 'q' to quit."); 210 | } 211 | } 212 | scanner.close(); 213 | } 214 | } 215 | 216 | 217 | 48.2.1 218 | 219 | class A { 220 | private int instanceField; 221 | private static int counter = 0; // Static field to keep track of instances 222 | 223 | public A(int instanceField) { 224 | this.instanceField = instanceField; 225 | counter++; // Increment the counter for each instance created 226 | } 227 | 228 | public static int getInstanceCount() { 229 | return counter; // Static method to access the static field 230 | } 231 | 232 | @Override 233 | public String toString() { 234 | return "A [instanceField = " + instanceField + ", counter = " + counter + "]"; 235 | } 236 | } 237 | 238 | public class StaticMethodDemo { 239 | public static void main(String[] args) { 240 | A a1 = new A(3); 241 | A a2 = new A(4); 242 | 243 | System.out.println("a1 = " + a1); 244 | System.out.println("a2 = " + a2); 245 | // Accessing static method correctly using class name 246 | System.out.println("A.getInstanceCount() = " + A.getInstanceCount()); 247 | } 248 | } 249 | 48.2.2 250 | 251 | //write the code 252 | public static int add(int x, int y) { 253 | return x + y; 254 | } 255 | 256 | 48.2.3 257 | import java.util.Scanner; 258 | 259 | class A { 260 | public static String concatenate(String str1, String str2) { 261 | return str1 + str2; 262 | } 263 | } 264 | 265 | public class StringUtils { 266 | public static void main(String[] args) { 267 | Scanner scanner = new Scanner(System.in); 268 | 269 | 270 | String str1 = scanner.nextLine(); 271 | 272 | 273 | String str2 = scanner.nextLine(); 274 | 275 | String result = A.concatenate(str1, str2); 276 | System.out.println( result); 277 | 278 | scanner.close(); 279 | } 280 | } 281 | 282 | 48.3.1 283 | 284 | // Define the main class StaticClassDemo 285 | public class StaticClassDemo { 286 | 287 | // Define the main method 288 | public static void main(String[] args) { 289 | // Create instances of the nested static class A 290 | A a1 = new A(3); 291 | A a2 = new A(4); 292 | 293 | // Print string representation of a1 and a2 294 | System.out.println("a1 = " + a1); 295 | System.out.println("a2 = " + a2); 296 | } 297 | 298 | // Define a static nested class A 299 | static class A { 300 | // Private integer variable value 301 | private int value; 302 | 303 | // Constructor for class A 304 | public A(int value) { 305 | this.value = value; 306 | } 307 | 308 | // Override toString method to return string representation 309 | @Override 310 | public String toString() { 311 | return "A [value = " + value + "]"; 312 | } 313 | } 314 | } 315 | 316 | 317 | 48.3.2 318 | 319 | import java.util.Scanner; 320 | 321 | public class MathMain { 322 | public static void main(String[] args) { 323 | Scanner scanner = new Scanner(System.in); 324 | 325 | 326 | int a = scanner.nextInt(); 327 | 328 | 329 | int b = scanner.nextInt(); 330 | 331 | scanner.close(); 332 | 333 | System.out.println("Addition: " + MathUtils.add(a, b)); 334 | System.out.println("Subtraction: " + MathUtils.subtract(a, b)); 335 | System.out.println("Multiplication: " + MathUtils.multiply(a, b)); 336 | } 337 | 338 | static class MathUtils { 339 | public static int add(int a, int b) { 340 | return a + b; 341 | } 342 | 343 | public static int subtract(int a, int b) { 344 | return a - b; 345 | } 346 | 347 | public static int multiply(int a, int b) { 348 | return a * b; 349 | } 350 | } 351 | } 352 | 353 | 354 | 49.1.1 355 | public class Namer { 356 | private String name; 357 | 358 | public Namer(String name) { 359 | this.name = name; 360 | } 361 | 362 | class Prefixer { 363 | public String getCompleteName(String prefix) { 364 | return prefix + " " + Namer.this.name; 365 | } 366 | } 367 | 368 | public static void main(String[] args) { 369 | Namer nameObj = new Namer("Doodle"); 370 | Namer.Prefixer prefixer = nameObj.new Prefixer(); 371 | System.out.println(prefixer.getCompleteName("Mr.")); 372 | } 373 | } 374 | 375 | 49.1.2 376 | import java.util.Scanner; 377 | 378 | public class EvenNumberChecker { 379 | private int number; 380 | 381 | public EvenNumberChecker(int number) { 382 | this.number = number; 383 | } 384 | 385 | // Inner class to check if a number is even 386 | class EvenCheck { 387 | public boolean isEven() { 388 | return number % 2 == 0; 389 | } 390 | } 391 | 392 | public static void main(String[] args) { 393 | Scanner scanner = new Scanner(System.in); 394 | 395 | int num = scanner.nextInt(); 396 | 397 | EvenNumberChecker evenNumberChecker = new EvenNumberChecker(num); 398 | EvenCheck evenCheck = evenNumberChecker.new EvenCheck(); 399 | 400 | if (evenCheck.isEven()) { 401 | System.out.println("Even"); 402 | } else { 403 | System.out.println("Odd"); 404 | } 405 | 406 | scanner.close(); 407 | } 408 | } 409 | 410 | 411 | 49.2.1 412 | 413 | class A { 414 | class B { 415 | B() { 416 | System.out.println("In inner class B's constructor"); 417 | } 418 | } 419 | 420 | static class C { 421 | C() { 422 | System.out.println("In static nested class C's constructor"); 423 | } 424 | } 425 | 426 | public static void main(String[] args) { 427 | A outer = new A(); 428 | A.B inner = outer.new B(); 429 | A.C nested = new A.C(); 430 | } 431 | } 432 | 433 | 49.2.2 434 | 435 | import java.util.Scanner; 436 | 437 | class MathUtils { 438 | static class Geometry { 439 | // Method to calculate the area of a circle 440 | public static double circleArea(double radius) { 441 | return Math.PI * radius * radius; 442 | } 443 | 444 | // Method to calculate the area of a rectangle 445 | public static double rectangleArea(double length, double width) { 446 | return length * width; 447 | } 448 | } 449 | 450 | public static void main(String[] args) { 451 | Scanner scanner = new Scanner(System.in); 452 | 453 | // Input for circle radius 454 | double radius = scanner.nextDouble(); 455 | 456 | // Input for rectangle length 457 | double length = scanner.nextDouble(); 458 | 459 | // Input for rectangle width 460 | double width = scanner.nextDouble(); 461 | 462 | // Calculate area of circle 463 | double circleArea = Geometry.circleArea(radius); 464 | System.out.println("Area of circle: " + String.format("%.2f", circleArea)); 465 | 466 | // Calculate area of rectangle 467 | double rectangleArea = Geometry.rectangleArea(length, width); 468 | System.out.println("Area of rectangle: " + String.format("%.2f", rectangleArea)); 469 | 470 | scanner.close(); 471 | } 472 | } 473 | 474 | 49.2.3 475 | import java.util.Scanner; 476 | 477 | public class ArrayMain { 478 | 479 | // Static nested class ArrayUtils 480 | static class ArrayUtils { 481 | 482 | // Method to find the maximum element in an array 483 | public static int findMax(int[] arr) { 484 | int max = arr[0]; 485 | for (int i = 1; i < arr.length; i++) { 486 | if (arr[i] > max) { 487 | max = arr[i]; 488 | } 489 | } 490 | return max; 491 | } 492 | 493 | // Method to find the minimum element in an array 494 | public static int findMin(int[] arr) { 495 | int min = arr[0]; 496 | for (int i = 1; i < arr.length; i++) { 497 | if (arr[i] < min) { 498 | min = arr[i]; 499 | } 500 | } 501 | return min; 502 | } 503 | } 504 | 505 | public static void main(String[] args) { 506 | Scanner scanner = new Scanner(System.in); 507 | 508 | // Read the size of the array from the user 509 | System.out.print("Size: "); 510 | int size = scanner.nextInt(); 511 | 512 | // Initialize the array with the given size 513 | int[] array = new int[size]; 514 | 515 | // Read the elements of the array from the user 516 | System.out.println("Elements of the array:"); 517 | for (int i = 0; i < size; i++) { 518 | System.out.print("Element " + (i + 1) + ": "); 519 | array[i] = scanner.nextInt(); 520 | } 521 | 522 | // Call the methods from the ArrayUtils class and display the results 523 | System.out.println("Maximum element: " + ArrayUtils.findMax(array)); 524 | System.out.println("Minimum element: " + ArrayUtils.findMin(array)); 525 | 526 | // Close the scanner 527 | scanner.close(); 528 | } 529 | } 530 | 531 | 532 | 50.1.1 533 | 534 | class A { 535 | private int value = 5; // Instance member of the enclosing class A 536 | 537 | class B { // Inner class 538 | B() { 539 | System.out.println("In inner class B's constructor"); 540 | } 541 | } 542 | 543 | static class C { // Static nested class 544 | C() { 545 | System.out.println("In static nested class C's constructor"); 546 | } 547 | } 548 | 549 | public void someMethodInClassA() { 550 | final int localVar = 2; // Local variable, final so it can be accessed by the local class 551 | 552 | class D { // Local class 553 | D() { 554 | System.out.println("In local class D's constructor"); 555 | // Accessing the instance member of the enclosing class A 556 | System.out.println("value = " + (value + localVar)); // localVar is accessible because it's final 557 | } 558 | } 559 | 560 | D localClassInstance = new D(); // Instantiating the local class D 561 | } 562 | 563 | public static void main(String[] args) { 564 | A outerClassInstance = new A(); // Creating an instance of the top-level class A 565 | B innerClassInstance = outerClassInstance.new B(); // Creating an instance of the inner class B 566 | C staticNestedClassInstance = new A.C(); // Creating an instance of the static nested class C 567 | outerClassInstance.someMethodInClassA(); // Calling the method that creates an instance of the local class D 568 | } 569 | } 570 | 571 | 572 | 50.1.2 573 | 574 | 575 | import java.util.Scanner; 576 | 577 | public class AreaMain { 578 | public static void main(String[] args) { 579 | Scanner scanner = new Scanner(System.in); 580 | 581 | // Prompt the user for the length 582 | System.out.print("Length: "); 583 | double length = scanner.nextDouble(); 584 | 585 | // Prompt the user for the width 586 | System.out.print("Width: "); 587 | double width = scanner.nextDouble(); 588 | 589 | // Create an instance of the local class Rectangle 590 | Rectangle rectangle = new Rectangle(length, width); 591 | 592 | // Calculate and print the area 593 | double area = rectangle.calculateArea(); 594 | System.out.println("Area: " + area); 595 | } 596 | 597 | // Local class Rectangle 598 | private static class Rectangle { 599 | private double length; 600 | private double width; 601 | 602 | // Constructor 603 | public Rectangle(double length, double width) { 604 | this.length = length; 605 | this.width = width; 606 | } 607 | 608 | // Calculate the area 609 | public double calculateArea() { 610 | return length * width; 611 | } 612 | } 613 | } 614 | 615 | 616 | 617 | 50.1.3 618 | 619 | import java.util.Scanner; 620 | import java.math.BigInteger; 621 | 622 | public class FactorialCalculator { 623 | 624 | public static void main(String[] args) { 625 | Scanner scanner = new Scanner(System.in); 626 | 627 | int inputNumber = scanner.nextInt(); 628 | 629 | // Method that defines the local class and calculates the factorial 630 | calculateAndPrintFactorial(inputNumber); 631 | 632 | scanner.close(); 633 | } 634 | 635 | private static void calculateAndPrintFactorial(int number) { 636 | // Local class inside the method 637 | class Factorial { 638 | private int number; 639 | 640 | public Factorial(int number) { 641 | this.number = number; 642 | } 643 | 644 | public BigInteger calculateFactorial() { 645 | BigInteger factorial = BigInteger.ONE; 646 | for (int i = 1; i <= number; i++) { 647 | factorial = factorial.multiply(BigInteger.valueOf(i)); 648 | } 649 | return factorial; 650 | } 651 | } 652 | 653 | // Creating an instance of the local class and using it to calculate the factorial 654 | Factorial factorial = new Factorial(number); 655 | System.out.println(factorial.calculateFactorial()); 656 | } 657 | } 658 | 659 | 660 | 50.2.1 661 | 662 | 663 | 664 | interface Printer { //this is a top-level interface 665 | public void printMe(); 666 | } 667 | 668 | class A { //this is a normal top-level class 669 | public static void main(String[] args) { 670 | class PrinterImpl implements Printer { // an example of a normal local class 671 | public void printMe() { 672 | System.out.println("I am in printMe method of the local class PrinterImpl instance"); 673 | } 674 | } 675 | 676 | Printer myPrinter1 = new PrinterImpl(); 677 | 678 | Printer myPrinter2 = new Printer() { // an example of an anonymous class 679 | public void printMe() { 680 | System.out.println("I am in printMe method of the anonymous class"); 681 | } 682 | }; 683 | 684 | myPrinter1.printMe(); 685 | myPrinter2.printMe(); 686 | } 687 | } 688 | 689 | 50.2.2 690 | 691 | 692 | 693 | interface Printer { 694 | void print(String message); 695 | } 696 | 697 | public class AnonymousExample { 698 | public static void main(String[] args) { 699 | // Example of anonymous class implementing an interface 700 | Printer printer = new Printer() { 701 | @Override 702 | public void print(String message) { 703 | System.out.println(message); 704 | } 705 | }; 706 | 707 | printer.print("printMe is called!"); 708 | 709 | // Example of anonymous class extending a class 710 | Prefixer prefixer = new Prefixer("Hello ") { 711 | @Override 712 | public String getPrefixedName(String name) { 713 | return prefix+prefix + name; 714 | } 715 | }; 716 | 717 | System.out.println(prefixer.getPrefixedName("James")); 718 | } 719 | } 720 | 721 | abstract class Prefixer { 722 | protected String prefix; 723 | 724 | public Prefixer(String prefix) { 725 | this.prefix = prefix; 726 | } 727 | 728 | public abstract String getPrefixedName(String name); 729 | } 730 | 731 | 50.2.3 732 | 733 | Statements 1 and 2 will result in compilation errors. 734 | 735 | 51.1.1 736 | Both default and static methods 737 | 738 | 51.1.2 739 | import java.util.Scanner; 740 | 741 | @FunctionalInterface 742 | interface CalculateOperation { 743 | double calculate(double a, double b); 744 | } 745 | 746 | public class CalculateMain { 747 | public static void main(String[] args) { 748 | Scanner scanner = new Scanner(System.in); 749 | 750 | // Get input from the user 751 | System.out.print("First number: "); 752 | double firstNumber = scanner.nextDouble(); 753 | System.out.print("Second number: "); 754 | double secondNumber = scanner.nextDouble(); 755 | 756 | // Implement the functional interface using lambda expressions 757 | CalculateOperation subtraction = (a, b) -> a - b; 758 | CalculateOperation division = (a, b) -> { 759 | if (b != 0) { 760 | return a / b; 761 | } else { 762 | throw new ArithmeticException("Division by zero!"); 763 | } 764 | }; 765 | 766 | // Use the lambda expressions 767 | double subtractionResult = subtraction.calculate(firstNumber, secondNumber); 768 | double divisionResult = division.calculate(firstNumber, secondNumber); 769 | 770 | // Print the results 771 | System.out.println("Subtraction Result: " + subtractionResult); 772 | System.out.println("Division Result: " + divisionResult); 773 | 774 | scanner.close(); 775 | } 776 | } 777 | 51.1.3 778 | 779 | import java.util.Scanner; 780 | 781 | // Functional interface with a single abstract method 782 | interface IntOperation { 783 | int operate(int x); 784 | } 785 | 786 | public class SquareNumber { 787 | public static void main(String[] args) { 788 | // Creating a Scanner object to take input from the user 789 | Scanner scanner = new Scanner(System.in); 790 | 791 | // Taking user input for a number 792 | 793 | int number = scanner.nextInt(); 794 | 795 | // Creating a lambda expression to square the input number 796 | IntOperation square = (x) -> x * x; 797 | 798 | // Applying the lambda expression to square the input number 799 | int squaredNumber = square.operate(number); 800 | 801 | // Printing the squared number to the console 802 | System.out.println(squaredNumber); 803 | 804 | // Closing the Scanner object 805 | scanner.close(); 806 | } 807 | } 808 | 809 | 810 | 52.1.1 811 | 812 | import java.util.Scanner; 813 | 814 | // Calculator interface 815 | interface Calculator { 816 | int calculate(int a, int b); 817 | } 818 | 819 | public class CalculatorExample { 820 | public static void main(String[] args) { 821 | // Create Scanner object for user input 822 | Scanner scanner = new Scanner(System.in); 823 | 824 | // Lambda expression for addition operation 825 | Calculator addition = (a, b) -> a + b; 826 | 827 | // Take input from user 828 | 829 | int input1 = scanner.nextInt(); 830 | 831 | int input2 = scanner.nextInt(); 832 | 833 | // Close the Scanner 834 | scanner.close(); 835 | 836 | // Calculate the result using the lambda expression 837 | int result = addition.calculate(input1, input2); 838 | 839 | // Output 840 | System.out.println("Addition: " + result); 841 | } 842 | } 843 | 844 | 845 | 52.1.2 846 | 847 | import java.util.ArrayList; 848 | 849 | public class LambdaExpression { 850 | public static void main(String[] args) { 851 | // Creating an ArrayList 852 | ArrayList numbers = new ArrayList<>(); 853 | 854 | // Adding elements to the ArrayList 855 | numbers.add(120); 856 | numbers.add(303); 857 | numbers.add(308); 858 | numbers.add(555); 859 | 860 | // Printing the original ArrayList 861 | 862 | for (Integer number : numbers) { 863 | System.out.println(number); 864 | } 865 | 866 | // Using lambda expression to print all odd elements 867 | System.out.println("All odd elements displayed:"); 868 | boolean oddFound = false; 869 | for (Integer number : numbers) { 870 | if (number % 2 != 0) { 871 | System.out.println(number); 872 | oddFound = true; 873 | } 874 | } 875 | if (!oddFound) { 876 | System.out.println("Empty"); 877 | } 878 | } 879 | } 880 | 52.1.3 881 | 882 | import java.util.Scanner; 883 | 884 | @FunctionalInterface 885 | interface StringTransformer { 886 | String transform(String str); 887 | } 888 | 889 | public class StringMain { 890 | public static void main(String[] args) { 891 | Scanner scanner = new Scanner(System.in); 892 | 893 | // Implementation using lambda expression to convert string to uppercase 894 | StringTransformer uppercaseTransformer = str -> str.toUpperCase(); 895 | 896 | // Take input from the user 897 | 898 | String input = scanner.nextLine(); 899 | 900 | // Transform the input string to uppercase 901 | String transformed = uppercaseTransformer.transform(input); 902 | 903 | // Output the transformed string 904 | 905 | System.out.println(transformed); 906 | 907 | scanner.close(); 908 | } 909 | } 910 | 911 | 912 | 53.1.1 913 | 914 | 915 | value4 declared in statement 4 is called a constant. 916 | 917 | 53.1.2 918 | 919 | option 3 and 5 are correct 920 | 921 | 53.2.1 922 | option 1 is correct 923 | 924 | 54.1.1 925 | 4th option 926 | 927 | 54.1.2 928 | import java.util.Scanner; 929 | 930 | public final class ImmutablePoint { 931 | private final double x; 932 | private final double y; 933 | 934 | public ImmutablePoint(double x, double y) { 935 | this.x = x; 936 | this.y = y; 937 | } 938 | 939 | public double getX() { 940 | return x; 941 | } 942 | 943 | public double getY() { 944 | return y; 945 | } 946 | 947 | public double calculateDistance(ImmutablePoint other) { 948 | return Math.sqrt(Math.pow(other.x - this.x, 2) + Math.pow(other.y - this.y, 2)); 949 | } 950 | 951 | public static void main(String[] args) { 952 | Scanner scanner = new Scanner(System.in); 953 | 954 | // Taking input for the first point 955 | System.out.print("x-coordinate for first point: "); 956 | double x1 = scanner.nextDouble(); 957 | System.out.print("y-coordinate for first point: "); 958 | double y1 = scanner.nextDouble(); 959 | ImmutablePoint firstPoint = new ImmutablePoint(x1, y1); 960 | 961 | // Taking input for the second point 962 | System.out.print("x-coordinate for second point: "); 963 | double x2 = scanner.nextDouble(); 964 | System.out.print("y-coordinate for second point: "); 965 | double y2 = scanner.nextDouble(); 966 | ImmutablePoint secondPoint = new ImmutablePoint(x2, y2); 967 | 968 | // Calculating and printing the distance 969 | System.out.println("Distance: " + firstPoint.calculateDistance(secondPoint)); 970 | 971 | scanner.close(); 972 | } 973 | } 974 | 54.2.1 975 | 2 and 5 are correct 976 | 55.1.1 977 | 2nd 978 | 979 | 55.2.1 980 | 2nd 981 | 982 | 983 | 56.1.1 984 | 3rd 985 | 986 | 56.1.2 987 | all are correct 988 | 989 | 56.2.1 990 | 4th 991 | 992 | 56.3.1 993 | public class TimingExample { 994 | public static void main(String[] args) { 995 | // Start the time measurement 996 | long startTime = System.currentTimeMillis(); 997 | 998 | // Calculate the sum of numbers from 0 to 999 999 | int sum = 0; 1000 | for (int i = 0; i < 1000; i++) { 1001 | sum += i; 1002 | } 1003 | 1004 | // End the time measurement 1005 | long endTime = System.currentTimeMillis(); 1006 | 1007 | // Calculate the time taken in milliseconds 1008 | long timeTaken = endTime - startTime; 1009 | 1010 | // Print the results 1011 | 1012 | System.out.println("Time taken in milliseconds = " + timeTaken); 1013 | } 1014 | } 1015 | 1016 | 57.1.1 1017 | 1st option 1018 | 1019 | 57.1.2 1020 | import java.util.Date; 1021 | 1022 | public class DateExample { 1023 | public static void main(String[] args) { 1024 | // Create a new Date object representing the current time 1025 | Date currentDate = new Date(); 1026 | 1027 | 1028 | // Get the current time in milliseconds 1029 | long currentTime = currentDate.getTime(); 1030 | 1031 | 1032 | 1033 | // Sleep for 1 second 1034 | System.out.println("Sleeping for 1 second..."); 1035 | try { 1036 | Thread.sleep(1000); 1037 | } catch (InterruptedException e) { 1038 | e.printStackTrace(); 1039 | } 1040 | System.out.println("This thread resumed after 1 or more seconds"); 1041 | 1042 | 1043 | 1044 | 1045 | 1046 | } 1047 | } 1048 | 1049 | 1050 | 1051 | 1052 | 1053 | 1054 | 1055 | 57.1.3 1056 | 1057 | import java.util.*; 1058 | import java.text.*; 1059 | 1060 | public class DateFormatInJapan { 1061 | public static String getJapaneseShortDate(Date date) { 1062 | Locale japanLocale = Locale.JAPAN; 1063 | DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, japanLocale); 1064 | return df.format(date); 1065 | } 1066 | 1067 | public static void main(String[] args) { 1068 | // Sample Test Case 1069 | int year = Integer.parseInt(args[0]); 1070 | int month = Integer.parseInt(args[1]) - 1; // Month in Calendar starts from 0 1071 | int day = Integer.parseInt(args[2]); 1072 | 1073 | Calendar cal = Calendar.getInstance(); 1074 | cal.set(year, month, day); 1075 | Date date = cal.getTime(); 1076 | 1077 | String formattedDate = getJapaneseShortDate(date); 1078 | System.out.println("Oct 2, 1869 in Japan is: " + formattedDate); 1079 | } 1080 | } 1081 | 57.1.4 1082 | 1083 | import java.text.ParseException; 1084 | import java.text.SimpleDateFormat; 1085 | import java.util.Date; 1086 | 1087 | public class SimpleDateFormatDemo { 1088 | public static void main(String[] args) { 1089 | // Define the date text 1090 | String dateText = "15-08-1947"; 1091 | 1092 | // Define the pattern for parsing 1093 | String pattern = "dd-MM-yyyy"; 1094 | 1095 | // Create a SimpleDateFormat object with the pattern 1096 | SimpleDateFormat sdf = new SimpleDateFormat(pattern); 1097 | 1098 | try { 1099 | // Parse the date text to a Date object 1100 | Date parsedDate = sdf.parse(dateText); 1101 | 1102 | // Print the parsed date 1103 | System.out.println("parsedDate : " + parsedDate); 1104 | } catch (ParseException e) { 1105 | System.out.println("Error occurred while parsing the date: " + e.getMessage()); 1106 | } 1107 | } 1108 | } 1109 | 1110 | 57.1.5 1111 | 5th option 1112 | 57.1.6 1113 | 1114 | import java.time.*; 1115 | import java.time.temporal.TemporalAdjusters; 1116 | 1117 | public class LocalDateDemo { 1118 | public static void main(String[] args) { 1119 | // Java's birthday was on 1995-05-23 1120 | LocalDate javaBirthday = LocalDate.of(1995, Month.MAY, 23); 1121 | 1122 | // The cake was cut on next Sunday: 1995-05-28 1123 | LocalDate nextSunday = javaBirthday.with(TemporalAdjusters.next(DayOfWeek.SUNDAY)); 1124 | 1125 | System.out.println("Java's birthday was on " + javaBirthday + ", and the cake was cut on next Sunday: " + nextSunday + "."); 1126 | } 1127 | } 1128 | 1129 | 57.1.7 1130 | 3rd 1131 | 1132 | 1133 | 58.1.1 1134 | 1st option 1135 | 1136 | 58.2.1 1137 | 3rd 1138 | 1139 | 59.1.1 1140 | 1st option 1141 | --------------------------------------------------------------------------------