0% found this document useful (0 votes)
27 views

Jaa Pyqs

Uploaded by

Roban Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Jaa Pyqs

Uploaded by

Roban Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

18 9 july 2022

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:

Portability , Reduced Compatibility issues, Cost Saving , Wider Audience , Consistency

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.

public class JoinExample1 extends Thread {

public void run() {

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


try {

Thread.sleep(500);

}catch(Exception e){System.out.println(e);}

System.out.println(i);

}
}

public static void main(String args[]) {


JoinExample1 t1 = new JoinExample1();

JoinExample1 t2 = new JoinExample1();

JoinExample1 t3 = new JoinExample1();


t1.start();

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.

Life cycle of applet includes:

Init(), start(), paint(), stop(), destroy().

3: We can perform polymorphism in java by method overloading and method overriding.

Method Overloading:

class CompileTime {
static int perimeter(int a) {

return 4 * a;
}

static int perimeter(int l, int b) {


return 2 * (l + b);

class Polymorphism {

public static void main(String[] args) {


System.out.println("Side of square : 4\nPerimeter of square will be : " + Compiletime.perimeter(4) + "\n");

System.out.println("Sides of rectangle are : 10, 13\nPerimeter of rectangle will be :


Compiletime.perimeter(10, 13));

}
Method overriding:

class Animal{

void place(){
System.out.println("Animals live on earth.");

}
}

class Dog extends Animal{


void place(){

System.out.println("Dog lives in kennel.");

}
}
class Horse extends Animal{
void place(){

System.out.println("Horse lives in stable.");


}
}

class Polymorphism{

public static void main(String[] args) {

Animal A = new Animal();


A.place();

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;

public class Demo {

public void show()


{

System.out.println("Hi Everyone");

public void view()


{

System.out.println("Hello");
}

// Name of the package


import data.*;
class ncj {

public static void main(String arg[])


{ Demo d = new Demo();
d.show();

d.view();

5: class GFG {
static int binaryToDecimal(int n)
{

int num = n;
int dec_value = 0;

int base = 1;

int temp = num;

while (temp > 0) {


int last_digit = temp % 10;

temp = temp / 10;

dec_value += last_digit * base;


base = base * 2;

}
return dec_value;

}
public static void main(String[] args)
{

int num = 10101001;


System.out.println(binaryToDecimal(num));

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));

System.out.print("Enter the Limit for fabonacci: ");


int n = Integer.parseInt(br.readLine());
System.out.println("Fibonacci series:");
while (n>0)
{
System.out.print(c+" ");
a=b;
b=c;
c=a+b;
n=n-1;
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}

B: class Reverse extends Thread


{
public void run()
{
try
{
System.out.println("\nReverse is: ");
for (int i=10; i >= 1 ;i-- )
{
System.out.print(i+" ");
}

}
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;

void printArea(double x,double y){


}

class rectangle extends shape{

void printArea(double l , double b){

System.out.println("Area= "+ l*b);

class triangle extends shape{

void printArea(double b, double h){

System.out.println("Area= "+ 0.5*b*h);


}

class circle extends shape{

void printArea(double r , double y){

System.out.println("Area= "+ 3.14*r*r);

}
public class code {

public static void main(String[] args) {


Rectangle r=new Rectangle();

r.printArea(2,5);
triangle t = new triangle();

t.printArea(2, 5);

circle c=new circle();

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.

Multiple catch statement:

import java.util.Scanner;
public class Test
{

public static void main(String args[])


{

Scanner scn = new Scanner(System.in);

try

{
int n = Integer.parseInt(scn.nextLine());

if (99%n == 0)
System.out.println(n + " is a factor of 99");

catch (ArithmeticException ex)


{

System.out.println("Arithmetic " + ex);


}

catch (NumberFormatException ex)


{

System.out.println("Number Format Exception " + ex);


}

}
}
Custom Exception

class MyException extends Exception {


}
public class setText {

public static void main(String args[])

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();

// Now calling the methods from both the interfaces


d.show(); // Default method from API
d.display(); // Overridden method from Interface1
d.print(); // Overridden method from Interface2
}
}

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)
{

Child child = new Child();


child.hello();

class Child extends Base {


public void hello()

System.out.println("Hello from child class");

}
}
class Base {

public final void hello()


{
System.out.println("Hello from base class");

9: public class Author {


// The private instance variables
private String name;
private String email;
private char gender; // 'm' or 'f'

/** Constructs a Author instance with the given inputs */


public Author(String name, String email, char gender) {
this.name = name;
this.email = email;
this.gender = gender;
}

// 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;
}

/** Returns a self-descriptive String */


public String toString() {
return name + " (" + gender + ") at " + email;
}
}

public class Book {


// The private instance variables
private String name;
private Author author;
private double price;
private int qty;

/** Constructs a Book instance with the given author */


public Book(String name, Author author, double price, int qty) {
this.name = name;
this.author = author;
this.price = price;
this.qty = qty;
}

// Getters and Setters


/** Returns the name of this book */
public String getName() {
return name;
}
/** Return the Author instance of this book */
public Author getAuthor() {
return author; // return member author, which is an instance of the class Author
}
/** Returns the price */
public double getPrice() {
return price;
}
/** Sets the price */
public void setPrice(double price) {
this.price = price;
}
/** Returns the quantity */
public int getQty() {
return qty;
}
/** Sets the quantity */
public void setQty(int qty) {
this.qty = qty;
}

/** Returns a self-descriptive String */


public String toString() {
return "'" + name + "' by " + author; // author.toString()
}
}

public class TestBook {


public static void main(String[] args) {
// We need an Author instance to create a Book instance
Author ahTeck = new Author("Tan Ah Teck", "ahTeck@somewhere.com", 'm');
System.out.println(ahTeck); // Author's toString()
//Tan Ah Teck (m) at ahTeck@somewhere.com

// Test Book's constructor and toString()


Book dummyBook = new Book("Java for dummies", ahTeck, 9.99, 99);
System.out.println(dummyBook); // Book's toString()
//'Java for dummies' by Tan Ah Teck (m) at ahTeck@somewhere.com

// Test Setters and Getters


dummyBook.setPrice(8.88);
dummyBook.setQty(88);
System.out.println("name is: " + dummyBook.getName());
//name is: Java for dummies
System.out.println("price is: " + dummyBook.getPrice());
//price is: 8.88
System.out.println("qty is: " + dummyBook.getQty());
//qty is: 88
System.out.println("author is: " + dummyBook.getAuthor()); // invoke Author's toString()
//author is: Tan Ah Teck (m) at ahTeck@somewhere.com
System.out.println("author's name is: " + dummyBook.getAuthor().getName());
//author's name is: Tan Ah Teck
System.out.println("author's email is: " + dummyBook.getAuthor().getEmail());
//author's email is: ahTeck@somewhere.com
System.out.println("author's gender is: " + dummyBook.getAuthor().getGender());
//author's gender is: m

// Using an anonymous Author instance to create a Book instance


Book moreDummyBook = new Book("Java for more dummies",
new Author("Peter Lee", "peter@nowhere.com", 'm'), // an anonymous Author's instance
19.99, 8);
System.out.println(moreDummyBook); // Book's toString()
//'Java for more dummies' by Peter Lee (m) at peter@nowhere.com
}
}

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[]) {

String str1 = "To";


String str2 = "gether";
str1 = str1.concat(str2);
System.out.println(str1);
}
}

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.*;

public class GeeksForGeeks {


public static void printPattern(int n)
{
int i, j;
int num = 1;
for (i = 1; i <= n; i++) {
for (j = 1; j <= n - i; j++) {
System.out.print(" ");
}
for (j = 1; j <= 2 * i - 1; j++) {
System.out.print("*");
}
System.out.println();
}
for (i = n-1; i >= 1; i--) {
for (j = 1; j <= n - i; j++) {
System.out.print(" ");
}
for (j = 1; j <= 2 * i - 1; j++) {
System.out.print("*");
}
System.out.println();
}
}
public static void main(String args[])
{
int n = 6;
printPattern(n);
}
}
7:
import java.io.*;
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.

Multiple inheritance done

9: Done

OR

import java.util.Random;

class RandomNumberThread extends Thread {


public void run() {
Random random = new Random();
for (int i = 0; i < 10; i++) {
int randomInteger = random.nextInt(100);
System.out.println("Random Integer generated : " + randomInteger);
if((randomInteger%2) == 0) {
SquareThread sThread = new SquareThread(randomInteger);
sThread.start();
}
else {
CubeThread cThread = new CubeThread(randomInteger);
cThread.start();
}
try {
Thread.sleep(1000);
}
catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
}
class SquareThread extends Thread {
int number;

SquareThread(int randomNumbern) {
number = randomNumbern;
}

public void run() {


System.out.println("Square of " + number + " = " + (number * number));
}
}

class CubeThread extends Thread {


int number;

CubeThread(int randomNumber) {
number = randomNumber;
}

public void run() {


System.out.println("Cube of " + number + " = " + number * number * number);
}
}

public class MultiThreadingTest {


public static void main(String args[]) {
RandomNumberThread rnThread = new RandomNumberThread();
rnThread.start();
}
}
20 28 june 2023

1 A: DONE
B:

C: Private Access Modifier

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 protected access modifier is specified using the keyword protected.


The methods or data members declared as protected are accessible within the same package or subclasses in
different packages.

Public Access modifier


The public access modifier is specified using the keyword public.

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

Java Grid Layout


The Java GridLayout class is used to arrange the components in a rectangular grid. One component is
displayed in each rectangle.

Java Flow Layout


The Java FlowLayout class is used to arrange the components in a line, one after another (in a flow). It is the
default layout of the applet or panel.
Fields of FlowLayout class
public static final int LEFT
public static final int RIGHT
public static final int CENTER
public static final int LEADING
public static final int TRAILING

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.

public class Main {

public static void main(String[ ] args) {

try {

int[] myNumbers = {1, 2, 3};


System.out.println(myNumbers[10]);

} catch (Exception e) {

System.out.println("Something went wrong.");

Nested Try statements:


class NestedTry {
public static void main(String args[])
{
try {
int a[] = { 1, 2, 3, 4, 5 };
System.out.println(a[5]);
try {
int x = a[2] / 0;
}
catch (ArithmeticException e2) {
System.out.println("division by zero is not possible");
}
}
catch (ArrayIndexOutOfBoundsException e1) {
System.out.println("ArrayIndexOutOfBoundsException");
System.out.println("Element at such index does not exists");
}
}
}

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.

Threads can be created by using two mechanisms :

Thread creation by extending the Thread class

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.

Thread creation by implementing the Runnable Interface


We create a new class which implements java.lang.Runnable interface and override run() method. Then we
instantiate a Thread object and call start() method on this object.

Life Cycle of thread

 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.

set priority of a thread in java.

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.

Here are some reasons why thread synchronization is important in Java:


Data Consistency: When multiple threads access and modify shared data concurrently, it's essential to ens ure
that the data remains consistent and correct. Without proper synchronization, one thread may read the data
while another thread is in the process of modifying it, leading to unpredictable behavior and data corruption.

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;

public Account(String name, String accountNumber, double balance) {


this.name = name;
this.accountNumber = accountNumber;
this.balance = balance;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getAccountNumber() {


return accountNumber;
}

public void setAccountNumber(String accountNumber) {


this.accountNumber = accountNumber;
}

public double getBalance() {


return balance;
}

public void setBalance(double balance) {


this.balance = balance;
}

public void deposit(double amount) {


balance += amount;
}

public void withdraw(double amount) {


balance -= amount;
}

public String getAccountInfo() {


return "Name: " + name + ", Account Number: " + accountNumber + ", Balance: "
+ balance;
}
}

//Bank.java
import java.util.ArrayList;

public class Bank {


private ArrayList < Account > accounts;

public Bank() {
accounts = new ArrayList < Account > ();
}

public void addAccount(Account account) {


accounts.add(account);
}

public void removeAccount(Account account) {


accounts.remove(account);
}

public void depositMoney(Account account, double amount) {


account.deposit(amount);
}

public void withdrawMoney(Account account, double amount) {


account.withdraw(amount);
}

public ArrayList < Account > getAccounts() {


return accounts;
}
}

//Main.java
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
Bank bank = new Bank();

Account account1 = new Account("Peter Irmgard", "C0011", 5000);


Account account2 = new Account("Katja Ruedi", "C0121", 4500);
Account account3 = new Account("Marcella Gebhard", "C0222", 20000);

bank.addAccount(account1);
bank.addAccount(account2);
bank.addAccount(account3);

ArrayList < Account > accounts = bank.getAccounts();

for (Account account: accounts) {


System.out.println(account.getAccountInfo());
}

System.out.println("\nAfter depositing 1000 into account1:");


bank.depositMoney(account1, 1000);
System.out.println(account1.getAccountInfo());
System.out.println("No transaction in account2:");
System.out.println(account2.getAccountInfo());
System.out.println("After withdrawing 5000 from account3:");
bank.withdrawMoney(account3, 5000);
System.out.println(account3.getAccountInfo());
}
}

6:
import java.applet.*;
importjava.awt.*;

/* <applet code= Appletprogram.class height=400 width=400>


<Param name=”string1” value=”hello”>

<Param name=”Sstring2” value=”world”>

</applet>
public class AppletProgram extends Applet {

String str1;

public void init() {

str1 = getParameter("string1").concat(getParameter("string2"));

public void paint(Graphics g) {

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]);
}

9 import java.awt.*; // Using AWT container and component classes


import java.awt.event.*; // Using AWT event classes and listener interfaces

// An AWT GUI program inherits (customized) from the top-level container


// java.awt.Frame
public class AWTAccumulator extends Frame {
//private Label lblInput; // Declare input Label (to use anonymous)
//private Label lblOutput; // Declare output Label (to use anonymous)
private TextField tfInput; // Declare input TextField
private TextField tfOutput; // Declare output TextField
private int sum = 0; // Accumulated sum, init to 0

// Constructor to setup the GUI components and event handlers


public AWTAccumulator() {
setLayout(new GridLayout(2, 2));
// "super" Frame (Container) sets layout to GridLayout of 2 rows 2 columns.

add(new Label("Enter an Integer: ")); // "super" Frame adds an anonymous Label

tfInput = new TextField(10); // Construct TextField


add(tfInput); // "super" Frame adds TextField

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

tfOutput = new TextField(10); // allocate TextField


tfOutput.setEditable(false); // read-only
add(tfOutput); // "super" Frame adds TextField

setTitle("AWT Accumulator"); // "super" Frame sets title


setSize(350, 120); // "super" Frame sets initial window size
setVisible(true); // "super" Frame shows
}

// The entry main() method


public static void main(String[] args) {
// Invoke the constructor to setup the GUI, by allocating an anonymous instance
new AWTAccumulator();
}

// Define an inner class to handle the input TextField.


// An ActionEvent listener must implement ActionListener interface.
private class TFInputListener implements ActionListener {
// ActionEvent handler - Called back upon hitting "enter" key on TextField
@Override
public void actionPerformed(ActionEvent evt) {
// Get the String entered into the TextField tfInput, convert to int
int numberIn = Integer.parseInt(tfInput.getText());
sum += numberIn; // Accumulate numbers entered into sum
tfInput.setText(""); // Clear input TextField
tfOutput.setText(sum + ""); // Display sum on the output TextField
// convert int to String
}
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy