Jaa Pyqs
Jaa Pyqs
1 A: Mutithreading in java feature allows concurrent execution of two or more parts of a program for
maximum utilization of CPU. Each part of such program is called as thread. So threads are light weight
processes within process. It can be created by either extending thread class or implementing the runnable
interface.
B:
C: False, Java is platform independent because it is designed to be executable on different platforms without
requiring major modification in the code. Programs written in java can be implemented on any platform
without significant changes or adaptations because of JVM(Java Virtual Machine). It has advantages like:
D:
E: The join method of thread class waits for a thread to die. It is used when you want one thread to wait for
completion of the other. This process is like a relay race where the second runner waits until the first runner
completes the race.
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
try {
t1.join();
}catch(Exception e){System.out.println(e);}
t2.start();
t3.start();
}
}
F : A static method in Java is a method that is part of a class rather than an instance of that class.
Every instance of a class has access to the method.
Static methods have access to class variables (static variables) without using the class’s object (instance).
Only static data may be accessed by a static method. It is unable to access data that is not static (instance
variables).
In both static and non-static methods, static methods can be accessed directly.
2: An applet is a special type of program that is embedded in webpage to generate dynamic content It works
inside a browser
Creating an applet typically involves writing Java code to implement the applet's functionality. You'll need a
basic understanding of Java programming and familiarity with GUI components for creating user interfaces.
Applets require the Java Development Kit (JDK) to compile and run. Once your applet code is written, you can
embed it into an HTML document using the <applet> tag, specifying attributes like the applet's width, height,
and codebase. Finally, the HTML file containing the applet can be viewed in a web browser to run the applet.
Method Overloading:
class CompileTime {
static int perimeter(int a) {
return 4 * a;
}
class Polymorphism {
}
Method overriding:
class Animal{
void place(){
System.out.println("Animals live on earth.");
}
}
}
}
class Horse extends Animal{
void place(){
class Polymorphism{
A = new Dog();
A.place();
A = new Horse();
A.place();
}
4: In order to create a package in java follow the certain steps as described below: We Should Choose A Name
For The Package We Are Going To Create And Include. The package command In The first line in the java
program source code.
To access the already created package just add the import statement with the package name in the program
you want to use the package.
package data;
System.out.println("Hi Everyone");
System.out.println("Hello");
}
d.view();
5: class GFG {
static int binaryToDecimal(int n)
{
int num = n;
int dec_value = 0;
int base = 1;
}
return dec_value;
}
public static void main(String[] args)
{
6: a: import java.io.*;
class Fibonacci extends Thread
{
public void run()
{
try
{
int a=0, b=1, c=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
Main thread:
class MainThread
{
public static void main(String[] args)
{
try
{
Fibonacci fib = new Fibonacci();
fib.start();
fib.sleep(4000);
Reverse rev = new Reverse();
rev.start();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
7: import java.util.*;
abstract class shape{
int a,b;
}
public class code {
r.printArea(2,5);
triangle t = new triangle();
t.printArea(2, 5);
c.printArea(4, 0);
8: In Java, Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at
run time, that disrupts the normal flow of the program’s instructions. Exceptions can be caught and handled by the
program. When an exception occurs within a method, it creates an object. This object is called the exception
object. It contains information about the exception, such as the name and description of the exception and the
state of the program when the exception occurred.
import java.util.Scanner;
public class Test
{
try
{
int n = Integer.parseInt(scn.nextLine());
if (99%n == 0)
System.out.println(n + " is a factor of 99");
}
}
Custom Exception
try {
throw new MyException();
}
catch (MyException ex) {
System.out.println("Caught");
System.out.println(ex.getMessage());
}
OR
A: Java doesn’t support Multiple Inheritance. Java uses interfaces to implement multiple inheritances in order
to prevent these conflicts.A Java interface is a group of abstract methods that specify the behavior that
implementing classes must follow. It serves as a class blueprint by outlining each class's methods. Interfaces
offer a degree of abstraction for specifying behaviors but cannot be instantiated like classes. In Java, a class can
successfully implement several interfaces to achieve multiple inheritance.
interface API {
// Default method
default void show()
{
// Print statement
System.out.println("Default API");
}
}
// Interface 2
// Extending the above interface
interface Interface1 extends API {
// Abstract method
void display();
}
// Interface 3
// Extending the above interface
interface Interface2 extends API {
// Abstract method
void print();
}
// Main class
// Implementation class code
class TestClass implements Interface1, Interface2 {
// Overriding the abstract method from Interface1
public void display()
{
System.out.println("Display from Interface1");
}
// Overriding the abstract method from Interface2
public void print()
{
System.out.println("Print from Interface2");
}
// Main driver method
public static void main(String args[])
{
// Creating object of this class
// in main() method
TestClass d = new TestClass();
B: The final way of preventing overriding is by using the final keyword in your method. The final keyword puts
a stop to being an inheritance. Hence, if a method is made final it will be considered final implementation and
no other class can override the behavior.
import java.io.*;
class GFG {
public static void main(String[] args)
{
}
}
class Base {
// The public getters and setters for the private instance variables.
// No setter for name and gender as they are not designed to be changed.
/** Returns the name */
public String getName() {
return name;
}
/** Returns the gender */
public char getGender() {
return gender;
}
/** Returns the email */
public String getEmail() {
return email;
}
/** Sets the email */
public void setEmail(String email) {
this.email = email;
}
OR
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
/*
<applet code="MyCalculator" width=300 height=300>
</applet>
*/
public class MyCalculator extends Applet implements ActionListener {
int num1,num2,result;
TextField T1;
Button NumButtons[]=new Button[10];
Button Add,Sub,Mul,Div,clear,EQ;
char Operation;
Panel nPanel,CPanel,SPanel;
public void init() {
nPanel=new Panel();
T1=new TextField(30);
nPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
nPanel.add(T1);
CPanel=new Panel();
CPanel.setBackground(Color.white);
CPanel.setLayout(new GridLayout(5,5,3,3));
for(int i=0;i<10;i++) {
NumButtons[i]=new Button(""+i);
}
Add=new Button("+");
Sub=new Button("-");
Mul=new Button("*");
Div=new Button("/");
clear=new Button("clear");
EQ=new Button("=");
T1.addActionListener(this);
for(int i=0;i<10;i++) {
CPanel.add(NumButtons[i]);
}
CPanel.add(Add);
CPanel.add(Sub);
CPanel.add(Mul);
CPanel.add(Div);
CPanel.add(EQ);
SPanel=new Panel();
SPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
SPanel.setBackground(Color.yellow);
SPanel.add(clear);
for(int i=0;i<10;i++) {
NumButtons[i].addActionListener(this);
}
Add.addActionListener(this);
Sub.addActionListener(this);
Mul.addActionListener(this);
Div.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
this.setLayout(new BorderLayout());
add(nPanel,BorderLayout.NORTH);
add(CPanel,BorderLayout.CENTER);
add(SPanel,BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent ae) {
String str=ae.getActionCommand ();
char ch=str.charAt(0);
if(Character.isDigit(ch))
T1.setText(T1.getText()+str);
else
if(str.equals("+")){
num1=Integer.parseInt (T1.getText());
Operation='+';
T1.setText ("");
}
if(str.equals("-")){
num1=Integer.parseInt(T1.getText());
Operation='-';
T1.setText("");
}
if(str.equals("*")){
num1=Integer.parseInt(T1.getText());
Operation='*';
T1.setText("");
}
if(str.equals("/")){
num1=Integer.parseInt(T1.getText());
Operation='/';
T1.setText("");
}
if(str.equals("%")){
num1=Integer.parseInt(T1.getText());
Operation='%';
T1.setText("");
}
if(str.equals("=")) {
num2=Integer.parseInt(T1.getText());
switch(Operation)
{
case '+':result=num1+num2;
break;
case '-':result=num1-num2;
break;
case '*':result=num1*num2;
break;
case '/':try {
result=num1/num2;
}
catch(ArithmeticException e) {
result=num2;
JOptionPane.showMessageDialog(this,"Divided by ze
ro");
}
break;
}
T1.setText(""+result);
}
if(str.equals("clear")) {
T1.setText("");
}
}
}
19 12 jan 2023
1 A:DONE
B: DONE
C: class GFG {
public static void main(String args[]) {
D: import java.io.*;
import java.util.*;
class GFG {
static int factorial(int n)
{
if (n == 0 || n == 1)
return 1;
return n * factorial(n - 1);
}
public static void main(String[] args)
{
int ans = factorial(5);
System.out.println("Factorial of 5 is :" + ans);
}
}
E: Done
F: It is majorly used in the following contexts as mentioned below:
Use of super with Variables
Use of super with Methods
Use of super with Constructors
class Person {
Person()
{
System.out.println("Person class Constructor");
}
}
class Student extends Person {
Student()
{
super();
System.out.println("Student class Constructor");
}
}
class Test {
public static void main(String[] args)
{
Student s = new Student();
}
}
2:
3 DONE
4 DONE
5:
5: import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code="FactorialApplet" width=500 height=250>
</applet>*/
public class FactorialApplet extends Applet implements ActionListener {
Label L1,L2;
TextField T1,T2;
Button B1;
public void init() {
L1=new Label("Enter any Number : ");
add(L1);
T1=new TextField(10);
add(T1);
L2=new Label("Factorial of Num : ");
add(L2);
T2=new TextField(10);
add(T2);
B1=new Button("Compute");
add(B1);
B1.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==B1)
{
int value=Integer.parseInt(T1.getText());
int fact=factorial(value);
T2.setText(String.valueOf(fact));
}
}
int factorial(int n) {
if(n==0)
return 1;
else
return n*factorial(n-1);
}
}
6:
import java.util.*;
class GFG {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the name");
String name = input.next();
try {
System.out.println("Enter the age");
Integer age = input.nextInt();
if (age <= 18) {
MyException me = new MyException();
throw me;
}
else
{
System.out.println("name:" + name);
System.out.println("age:" + age);
}
}
catch (MyException e)
{
System.out.println(e);
}
}
}
class MyException extends RuntimeException {
public String toString()
{
return "Age must be greater than 18";
}
}
8:A: There are multiple types of operators in Java all are mentioned below:
Arithmetic Operators
Unary Operators
Assignment Operator
Relational Operators
Logical Operators
Ternary Operator
Bitwise Operators
Shift Operators
instance of operator
B: In Java, ‘this’ is a reference variable that refers to the current object, or can be said “this” in Java is a
keyword that refers to the current object instance. It can be used to call current class methods and fields, to
pass an instance of the current class as a parameter, and to differentiate between the local and instance
variables. Using “this” reference can improve code readability and reduce naming conflicts.
public class Person {
String name;
int age;
Person(String name, int age)
{
this.name = name;
this.age = age;
}
public String get_name() { return name; }
public void change_name(String name)
{
this.name = name;
}
public void printDetails()
{
System.out.println("Name: " + this.name);
System.out.println("Age: " + this.age);
System.out.println();
}
public static void main(String[] args)
{
Person first = new Person("ABC", 18);
Person second = new Person("XYZ", 22);
first.printDetails();
second.printDetails();
first.change_name("PQR");
System.out.println("Name has been changed to: "
+ first.get_name());
}
}
OR
In Java, Inheritance means creating new classes based on existing ones. A class that inherits from another class
can reuse the methods and fields of that class.
1. Single Inheritance
In single inheritance, subclasses inherit the features of one superclass. In the image below, class A serves as a
base class for the derived class B.
2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the derived class also
acts as the base class for other classes. In the below image, class A serves as a base class for the derived class
B, which in turn serves as a base class for the derived class C.
3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In th e
below image, class A serves as a base class for the derived classes B, C, and D. Multiple Inheritance (Through
Interfaces)
4 Multiple Inheritance
In Multiple inheritances, one class can have more than one superclass and inherit features from all parent
classes. Please note that Java does not support multiple inheritances with classes. In Java, we can achieve
multiple inheritances only through Interfaces. In the image below, Class C is derived from interfaces A and B.
5. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. Since Java doesn’t support multiple inheritances
with classes, hybrid inheritance involving multiple inheritance is also not possible with classes. In Java, we can
achieve hybrid inheritance only through Interfaces if we want to involve multiple inheritance to implement
Hybrid inheritance.
9: Done
OR
import java.util.Random;
SquareThread(int randomNumbern) {
number = randomNumbern;
}
CubeThread(int randomNumber) {
number = randomNumber;
}
1 A: DONE
B:
The private access modifier is specified using the keyword private. The methods or data members declared as
private are accessible only within the class in which they are declared.
Protected Access Modifier
The public access modifier has the widest scope among all other access modifiers.
Classes, methods, or data members that are declared as public are accessible from everywhere in the
program. There is no restriction on the scope of public data members.
D: Java abstract class is a class that can not be initiated by itself, it needs to be subclassed by another class to
use its properties. An abstract class is declared using the “abstract” keyword in its class definition
The abstract Method is used for creating blueprints for classes or interfaces. Here methods are defined but
these methods don’t provide the implementation. Abstract Methods can only be implemented using
subclasses or classes that implement the interfaces.
These methods are sometimes referred to as subclasses responsibility because they have no implementation
specified in the super-class. Thus, a subclass must override them to provide a method definition.
E: paint( ) : The paint( ) method is called each time an AWT-based applet’s output must be redrawn. This
situation can occur for several reasons. For example, the window in which the applet is running may be
overwritten by another window and then uncovered. Or the applet window may be minimized and then
restored.
The getParameterTypes () method of Method class returns an array of type class objects representing the
formal parameter types, in the order in which they are declared. If the underlying executable takes no
parameter, then an array of length 0 is returned.
F:
2: Byte Code can be defined as an intermediate code generated by the compiler after the compilation of
source code(JAVA Program). This intermediate code makes Java a platform-independent language. Compiler
converts the source code or the Java program into the Byte Code(or machine code), and secondly, the
Interpreter executes the byte code on the system. The Interpreter can also be called JVM(Java Virtual
Machine). The byte code is the common piece between the compiler(which creates it) and the Interpreter
(which runs it).
Creation of a Java Program-When we talk about creating a program or typing a code that solves any
kind of problem that we may have, it means physically writing the program on any text editor. You may
or may not edit the program after you have written it once. When you create a program you don't just
make it and let it be the way it is you can modify it and save it on the device. But you need to save it
with the java extension otherwise it would just appear as a normal text file.
Compiling a Java Program-Now once the program is created and does not have any errors or mistakes
we can go ahead and compile the program when you compile a program it means the compiler
compiles the program and if there are no errors after compiling the program we can further run it and
get the desired output. We compile the Java program in a command prompt or another console.
Loading the Program into the Memory by Java Virtual Machine- A lot of memory is required by JVM
when you want to load the .class file extension before the execution. Loading is the process of placing a
program in memory for it to run. The .class files are needed by the program to execute the file.
Java Virtual Machine verification for bytecode- Jvm has a bytecode verifier that is due to maintenance
of the security of the program. The bytecode verifies the code only and only after the classes have
been loaded in the memory to maintain the security of the program. It makes sure that the bytecodes
are valid and accessible. It also saves the computer from various viruses and unsecure websites.
Java Program Execution-The above steps are executed by JVM when it interprets the bytecode. Earlier
JVM's were slow and only interpreted one bytecode at a time. Nowadays the modern JVM's are much
faster as they use JIT(just-in-time) compilation units. These JVMs can execute various tasks at the same
time. We also call them HotSpot compilers as they are used by JVM to find out the hot spots in our
bytecode.
3. Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run
time, rather than compile time.
class A
{
void m1()
{
System.out.println("Inside A's m1 method");
}
}
class B extends A
{
void m1()
{
System.out.println("Inside B's m1 method");
}
}
class C extends A
{
void m1()
{
System.out.println("Inside C's m1 method");
}
}
class Dispatch
{
public static void main(String args[])
{
A a = new A();
B b = new B();
C c = new C();
A ref;
ref = a;
ref.m1();
ref = b;
ref.m1();
ref = c;
ref.m1();
}
}
4: Java BorderLayout:
The BorderLayout is used to arrange the components in five regions: north, south, east, west, and center. Each region
(area) may contain one component only. It is the default layout of a frame or window. The BorderLayout provides five
constants for each region:
public static final int NORTH
public static final int SOUTH
public static final int EAST
public static final int WEST
public static final int CENTER
5:
import java.util.*;
class device {
String vendorname;
int ramsize;
double OSversion;
void input() {
Scanner sc=new Scanner(System.in);
System.out.println("Enter VendorName:");
vendorname=sc.nextLine();
System.out.println("Enter RAM size:");
ramsize=sc.nextInt();
System.out.println("Enter OSversion");
OSversion=sc.nextDouble();
}
}
interface loader {
void loados();
}
class mobile extends device implements loader {
public void loados() {
super.input();
System.out.println("VendorName:"+vendorname+"\nRAM size:"+ramsize+"\nOSversion:"+OSversion);
}
}
class Phone {
public static void main(String args[]) {
mobile obj=new mobile(); obj.loados();
}
}
6:
1. import java.util.Scanner;
2. // create class PrintEvenOddExample2 to print even and odd numbers using 2 threads
3. public class PrintEvenOddExample2 {
4. public static void main(String[] args) {
5. int MAX;
6. // create an instance of Scanner class
7. Scanner sc = new Scanner(System.in);
8. System.out.println("Enter MAX value:");
9. MAX = sc.nextInt();
10. // close scanner class instance
11. sc.close();
12. // create instances of EvenOddRunnable classes
13. EvenOddRunnable runnable1 = new EvenOddRunnable(1, MAX );
14. EvenOddRunnable runnable2 = new EvenOddRunnable(0, MAX);
15. // create thread1 and thread2
16. Thread thread1 = new Thread(runnable1,"Odd");
17. Thread thread2 = new Thread(runnable2,"Even");
18. // use start() method to start thread1 and thread2
19. thread1.start();
20. thread2.start();
21. }
22. }
7:
import java.awt.*;
import java.awt.event.*;
class MyLoginWindow extends Frame
{
TextField name,pass;
Button b1,b2;
MyLoginWindow()
{
setLayout(new FlowLayout());
this.setLayout(null);
Label n=new Label("Name:",Label.CENTER);
Label p=new Label("password:",Label.CENTER);
name=new TextField(20);
pass=new TextField(20);
pass.setEchoChar('#');
b1=new Button("submit");
b2=new Button("cancel");
this.add(n);
this.add(name);
this.add(p);
this.add(pass);
this.add(b1);
this.add(b2);
n.setBounds(70,90,90,60);
p.setBounds(70,130,90,60);
name.setBounds(200,100,90,20);
pass.setBounds(200,140,90,20);
b1.setBounds(100,260,70,40);
b2.setBounds(180,260,70,40);
}
public static void main(String args[])
{
MyLoginWindow ml=new MyLoginWindow();
ml.setVisible(true);
ml.setSize(400,400);
ml.setTitle("my login window");
}
}
8: Build In exceptions:
Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to
explain certain error situations. Below is the list of important built-in exceptions in Java.
ArithmeticException: It is thrown when an exceptional condition has occurred in an arithmetic
operation.
ArrayIndexOutOfBoundsException: It is thrown to indicate that an array has been accessed with an
illegal index. The index is either negative or greater than or equal to the size of the array.
ClassNotFoundException: This Exception is raised when we try to access a class whose definition is
not found
FileNotFoundException: This Exception is raised when a file is not accessible or does not open.
IOException: It is thrown when an input-output operation failed or interrupted
User-Defined Exceptions
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, the
user can also create exceptions which are called ‘user-defined Exceptions’.
The following steps are followed for the creation of a user-defined Exception.
The user should create an exception class as a subclass of the Exception class. Since all the exceptions are
subclasses of the Exception class, the user should also make his class a subclass of it
The try statement allows you to define a block of code to be tested for errors while it is being executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
try {
} catch (Exception e) {
OR
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for
maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight
processes within a process.
We create a class that extends the java.lang.Thread class. This class overrides the run() method available in
the Thread class. A thread begins its life inside run() method. We create an object of our new class and call
start() method to start the execution of a thread. Start() invokes the run() method on the Thread object.
New Thread: When a new thread is created, it is in the new state. The thread has not yet started to
run when the thread is in this state. When a thread lies in the new state, its code is yet to be run
and hasn’t started to execute.
Runnable State: A thread that is ready to run is moved to a runnable state. In this state, a thread
might actually be running or it might be ready to run at any instant of time. It is the responsibility of
the thread scheduler to give the thread, time to run.
A multi-threaded program allocates a fixed amount of time to each individual thread. Each and every
thread runs for a short while and then pauses and relinquishes the CPU to another thread so that other
threads can get a chance to run. When this happens, all such threads that are ready to run, waiting for the
CPU and the currently running thread lie in a runnable state.
Blocked: The thread will be in blocked state when it is trying to acquire a lock but currently the lock
is acquired by the other thread. The thread will move from the blocked state to runnable state
when it acquires the lock.
Waiting state: The thread will be in waiting state when it calls wait() method or join() method. It will
move to the runnable state when other thread will notify or that thread will be terminated.
Timed Waiting: A thread lies in a timed waiting state when it calls a method with a time-out
parameter. A thread lies in this state until the timeout is completed or until a notification is
received. For example, when a thread calls sleep or a conditional wait, it is moved to a timed
waiting state.
Terminated State: A thread terminates because of either of the following reasons:
Because it exits normally. This happens when the code of the thread has been entirely executed by the
program.
Because there occurred some unusual erroneous event, like a segmentation fault or an unhandled
exception.
public final int getPriority(): java.lang.Thread.getPriority() method returns priority of given thread.
public final void setPriority(int newPriority): java.lang.Thread.setPriority() method changes the priority of
thread to the value newPriority. This method throws IllegalArgumentException if value of parameter
newPriority goes beyond minimum(1) and maximum(10) limit.
9.
DONE
OR
1. import java.applet.*;
2. import java.awt.*;
3. import java.util.*;
4. public class Clock extends Applet implements Runnable
5. {
6. Thread t;
7. //Initialize the applet
8. public void init()
9. {
10. setBackground(Color.white);
11. }
12. //Function to start the thread
13. public void start()
14. {
15. t = new Thread(this);
16. t.start();
17. }
18. //Function to execute the thread
19. public void run()
20. {
21. while(true)
22. {
23. try
24. {
25. repaint();
26. //Delay by 1 sec
27. Thread.sleep(1000);
28. }
29. catch(Exception e)
30. {
31. }
32. }
33. }
34. //Function to draw the clock
35. public void paint(Graphics g)
36. {
37. Calendar time = Calendar.getInstance();
38. int hour = time.get(Calendar.HOUR_OF_DAY) % 12;
39. int minute = time.get(Calendar.MINUTE);
40. int second = time.get(Calendar.SECOND);
41. double angle;
42. int x,y;
43. //Draw a circle with center(250,250) & radius=150
44. g.drawOval(100,100,300,300);
45. //Label the clock
46. String s="12";
47. int i=0;
48. while(i<12)
49. {
50. angle = Math.toRadians(30*(i-3));
51. x = 250+(int)(Math.cos(angle)*135);
52. y = 250+(int)(Math.sin(angle)*135);
53. g.drawString(s,x,y);
54. i++;
55. s=String.valueOf(i);
56. }
57. //Draw the hours hand
58. g.setColor(Color.green);
59. angle = Math.toRadians((30*hour)-90);
60. x = 250+(int)(Math.cos(angle)*100);
61. y = 250+(int)(Math.sin(angle)*100);
62. g.drawLine(250,250,x,y);
63. //Draw the minutes hand
64. g.setColor(Color.red);
65. angle = Math.toRadians((6*minute)-90);
66. x = 250+(int)(Math.cos(angle)*115);
67. y = 250+(int)(Math.sin(angle)*115);
68. g.drawLine(250,250,x,y);
69. //Draw the seconds hand
70. g.setColor(Color.blue);
71. angle = Math.toRadians((6*second)-90);
72. x = 250+(int)(Math.cos(angle)*130);
73. y = 250+(int)(Math.sin(angle)*130);
74. g.drawLine(250,250,x,y);
75. }
76. }
77. /*
78. <applet code = Clock.class width=500 height=500>
79. </applet>
80. */
21 11 dec 2023
1 A DONE
B:
C:
D: If the main method is not declared as static in Java, the JVM won't be able to invoke it directly without
an instance of the class containing the main method. Consequently, the Java program won't execute as
expected and will likely throw a runtime error. 4
E:
No, we cannot override private methods because the scope of private methods is limited to the class and
we cannot access them outside of the class which they are define in.
Just like static and final methods, private methods in Java use static binding that is done at compile time.
That's the reason we will get compile time error, when we try to override private methods.
F:
The answer is No. Because if a class is defined final it cannot be overridden . But if you create an abstract
class then it should be overridden by the subclass . Hence an abstract class cannot be final.
2: done
3 done
4: The synchronized keyword in Java is a way to ensure that only one thread can access a shared resource at a
time. This is important because when multiple threads access and modify a shared resource simultaneously, it
can lead to inconsistent data and unexpected results, a situation commonly known as a race condition.
Thread synchronization is crucial in Java (and in many other programming languages) because Java supports
multithreading, where multiple threads can execute concurrently within a single Java program. When multiple
threads are accessing and modifying shared resources or data concurrently, it can lead to issues such as data
inconsistency, race conditions, and deadlock.
Race Conditions: Race conditions occur when the outcome of a program depends on the timing or interleaving
of multiple threads. Synchronization mechanisms like locks, semaphores, and monitors help prevent race
conditions by ensuring that only one thread can access a shared resource at a time.
5:
//Account.java
public class Account {
private String name;
private String accountNumber;
private double balance;
//Bank.java
import java.util.ArrayList;
public Bank() {
accounts = new ArrayList < Account > ();
}
//Main.java
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
Bank bank = new Bank();
bank.addAccount(account1);
bank.addAccount(account2);
bank.addAccount(account3);
6:
import java.applet.*;
importjava.awt.*;
</applet>
public class AppletProgram extends Applet {
String str1;
str1 = getParameter("string1").concat(getParameter("string2"));
showStatus(str1);
}
}
7: done
8 done
OR
A: import java.util.*;
class GFG {
static void print2largest(Integer arr[], int arr_size)
{
Arrays.sort(arr, Collections.reverseOrder());
for (int i = 1; i < arr_size; i++) {
if (arr[i] != arr[0]) {
System.out.printf("The second largest "
+ "element is %d\n",
arr[i]);
return;
}
}
System.out.printf("There is no second "
+ "largest element\n");
}
public static void main(String[] args)
{
Integer arr[] = { 12, 35, 1, 10, 34, 1 };
int n = arr.length;
print2largest(arr, n);
}
}
B:
import java.io.*;
class GFG {
static void decToOctal(int n)
{
int[] octalNum = new int[100];
int i = 0;
while (n != 0) {
octalNum[i] = n % 8;
n = n / 8;
i++;
}
for (int j = i - 1; j >= 0; j--)
System.out.print(octalNum[j]);
}
tfInput.addActionListener(new TFInputListener());
// "tfInput" is the source object that fires an ActionEvent upon entered.
// The source add an anonymous instance of TFInputListener as an ActionEvent
// listener, which provides an ActionEvent handler called actionPerformed().
// Hitting "enter" on tfInput invokes actionPerformed().
add(new Label("The Accumulated Sum is: ")); // "super" Frame adds an anonymous Label