0% found this document useful (0 votes)
29 views30 pages

IP IMPORTANT QUESTIONS

The document discusses various Java programming concepts including thread models, applets, inner classes, applet lifecycle, constructors, and multilevel inheritance. It explains the states of threads, the lifecycle of applets with associated methods, types of constructors, and the advantages of inner classes. Additionally, it provides code examples for creating threads, displaying images in applets, and drawing a smiley face using an applet.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views30 pages

IP IMPORTANT QUESTIONS

The document discusses various Java programming concepts including thread models, applets, inner classes, applet lifecycle, constructors, and multilevel inheritance. It explains the states of threads, the lifecycle of applets with associated methods, types of constructors, and the advantages of inner classes. Additionally, it provides code examples for creating threads, displaying images in applets, and drawing a smiley face using an applet.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

IP IMPORTANT QUESTIONS

1.Explain java thread models with eg? Or what are stages of thread and
types? * 13M
 New (Ready to run) A thread is in New when it gets CPU time.
 Running. A thread is in a Running state when it is under execution.
 Suspended. A thread is in the Suspended state when it is temporarily inactive or
under execution.
 Blocked.
 Terminated.

A Thread is a very light-weighted process, or we can say the smallest part of


the process that allows a program to operate more efficiently by running
multiple tasks simultaneously.

In order to perform complicated tasks in the background, we used


the Thread concept in Java. All the tasks are executed without affecting
the main program. In a program or process, all the threads have their own
separate path for execution, so each thread of a process is independent.
 When multiple threads are executed in parallel at the same time,
this process is known as Multithreading.

In a simple way, a Thread is a:

 Feature through which we can perform multiple activities within a


single process.
 Lightweight process.
 Series of executed statements.
 Nested sequence of method calls

Thread Class
A Thread class has several methods and constructors which allow us to
perform various operations on a thread. The Thread class extends
the Object class. The Object class
There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

implements the Runnable interface. The thread class has the following
constructors that are used to perform various operations.

o Thread()
o Thread(Runnable, String name)
o Thread(Runnable target)
o Thread(ThreadGroup group, Runnable target, String name)
o Thread(ThreadGroup group, Runnable target)
o Thread(ThreadGroup group, String name)
o Thread(ThreadGroup group, Runnable target, String name,
long stackSize)

Runnable Interface(run() method)


The Runnable interface is required to be implemented by that class whose
instances are intended to be executed by a thread. The runnable interface
gives us the run() method to perform an action for the thread.

start() method
The method is used for starting a thread that we have newly created. It
starts a new thread with a new callstack. After executing the start() method,
the thread changes the state from New to Runnable. It executes the run()
method when the thread gets the correct time to execute it.

ThreadExample.java

// Implementing runnable interface by extending Thread class


public class ThreadExample1 extends Thread {
// run() method to perform action for thread.
public void run()
{
int a= 10;
int b=12;
int result = a+b;
System.out.println("Thread started running..");
System.out.println("Sum of two numbers is: "+ result);
}
public static void main( String args[] )
{
// Creating instance of the class extend Thread class
ThreadExample1 t1 = new ThreadExample1();
//calling start method to execute the run() method of the Thread clas
s
t1.start();
}
}

Output:

2.what do you mean applet? eg for display an image on screen 6M

- Java applets are used to provide interactive features to web applications and can be
executed by browsers for many platforms. They are small, portable Java programs
embedded in HTML pages and can run automatically when the pages are viewed.
Malware authors have used Java applets as a vehicle for attack.
- A Flash applet is a small application that runs inside the Flash web-browser plugin.
- Applet is mostly used in games and animation. For this purpose image is
required to be displayed. The java.awt.Graphics class provide a method
drawImage() to display the image.

- There are two types of applets:

local applet
remote applets

Syntax of drawImage() method:


1. public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.

to get the object of Image:


syntax:
public Image getImage(URL u, String image){}

Other required methods of Applet class to display


image:
1. public URL getDocumentBase(): is used to return the URL of the
document in which applet is embedded.
2. public URL getCodeBase(): is used to return the base URL.

Example

import java.awt.*;
import java.applet.*;

public class DisplayImage extends Applet {


Image picture;

public void init() {


picture = getImage(getDocumentBase(),"sonoo.jpg");
}

public void paint(Graphics g) {


g.drawImage(picture, 30,30, this);
}

myapplet.html :

<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>

3.Explain the concepts of inner class and its types? Or nested class 13M

Java inner class or nested class is a class that is declared inside the class
or interface.

We use inner classes to logically group classes and interfaces in one place to
be more readable and maintainable.

Additionally, it can access all the members of the outer class, including
private data members and methods.
Syntax of Inner class
1. class Java_Outer_class{
2. //code
3. class Java_Inner_class{
4. //code
5. }
6. }

Advantage of Java inner classes


There are three advantages of inner classes in Java. They are as follows:

1. Nested classes represent a particular type of relationship that is it can


access all the members (data members and methods) of the
outer class, including private.
2. Nested classes are used to develop more readable and
maintainable code because it logically group classes and interfaces
in one place only.
3. Code Optimization: It requires less code to write.

Need of Java Inner class


Sometimes users need to program a class in such a way so that no other
class can access it. Therefore, it would be better if you include it within other
classes.

If all the class objects are a part of the outer object then it is easier to nest
that class inside the outer class. That way all the outer class can access all
the objects of the inner class.

Types of Nested classes


There are two types of nested classes non-static and static nested classes.
The non-static nested classes are also known as inner classes.

o Non-static nested class (inner class)


1. Member inner class
2. Anonymous inner class
3. Local inner class
o Static nested class

Type Description

Member Inner A class created within class and outside method.


Class

Anonymous A class created for implementing an interface or


Inner Class extending class. The java compiler decides its
name.

Local Inner A class was created within the method.


Class

Static Nested A static class was created within the class.


Class

Nested An interface created within class or interface.


Interface

Important Points on Inner Classes in Java


The following are some important things to remember when working with
Inner classes in Java:

 An inner class can be declared as public, private, or protected.


 An inner class can extend any class and implement any interface.
 It should be noted that if an inner class has been marked as static, it
cannot access non-static members of the outer class. It can access
static members of the outer class.
 You cannot create an instance of an inner or nested class without an
instance of the outer class.
 Inner classes can be used to write more modular and reusable code

EXAMPLE:

class CPU {
double price;
// nested class
class Processor{

// members of nested class


double cores;
String manufacturer;

double getCache(){
return 4.3;
}
}

// nested protected class


protected class RAM{

// members of protected nested class


double memory;
String manufacturer;

double getClockSpeed(){
return 5.5;
}
}
}

public class Main {


public static void main(String[] args) {

// create object of Outer class CPU


CPU cpu = new CPU();

// create an object of inner class Processor using outer class


CPU.Processor processor = cpu.new Processor();
// create an object of inner class RAM using outer class CPU
CPU.RAM ram = cpu.new RAM();
System.out.println("Processor Cache = " + processor.getCache());
System.out.println("Ram Clock speed = " + ram.getClockSpeed());
}
}
Run Code

Output:

Processor Cache = 4.3


Ram Clock speed = 5.5

4.Describe detail about applet lifecycle and associated methods of applet?

The applet life cycle can be defined as the process of how the object is
created, started, stopped, and destroyed during the entire execution of its
application. It basically has five core methods namely init(), start(), stop(),
paint() and destroy().These methods are invoked by the browser to execute.

Along with the browser, the applet also works on the client side, thus having
less processing time.

Methods of Applet Life Cycle


There are five methods of an applet life cycle, and they are:

o init(): The init() method is the first method to run that initializes the applet. It
can be invoked only once at the time of initialization. The web browser
creates the initialized objects, i.e., the web browser (after checking the
security settings) runs the init() method within the applet.
o start(): The start() method contains the actual code of the applet and starts
the applet. It is invoked immediately after the init() method is invoked. Every
time the browser is loaded or refreshed, the start() method is invoked. It is
also invoked whenever the applet is maximized, restored, or moving from one
tab to another in the browser. It is in an inactive state until the init() method
is invoked.
o stop(): The stop() method stops the execution of the applet. The stop ()
method is invoked whenever the applet is stopped, minimized, or moving
from one tab to another in the browser, the stop() method is invoked. When
we go back to that page, the start() method is invoked again.
o destroy(): The destroy() method destroys the applet after its work is done. It
is invoked when the applet window is closed or when the tab containing the
webpage is closed. It removes the applet object from memory and is
executed only once. We cannot start the applet once it is destroyed.
o paint(): The paint() method belongs to the Graphics class in Java. It is used
to draw shapes like circle, square, trapezium, etc., in the applet. It is
executed after the start() method and when the browser or applet windows
are resized.

Sequence of method execution when an applet is executed:

1. init()
2. start()
3. paint()

Sequence of method execution when an applet is executed:

1. stop()
2. destroy()
Applet Life Cycle Working
o The Java plug-in software is responsible for managing the life cycle of an
applet.
o An applet is a Java application executed in any web browser and works on the
client-side. It doesn't have the main() method because it runs in the browser.
It is thus created to be placed on an HTML page.
o The init(), start(), stop() and destroy() methods belongs to
the applet.Applet class.
o The paint() method belongs to the awt.Component class.
o In Java, if we want to make a class an Applet class, we need to extend
the Applet
o Whenever we create an applet, we are creating the instance of the existing
Applet class. And thus, we can use all the methods of that class.

Flow of Applet Life Cycle:


These methods are invoked by the browser automatically. There is no need
to call them explicitly.
Syntax of entire Applet Life Cycle in Java
class TestAppletLifeCycle extends Applet {
public void init() {
// initialized objects
}
public void start() {
// code to start the applet
}
public void paint(Graphics graphics) {
// draw the shapes
}
public void stop() {
// code to stop the applet
}
public void destroy() {
// code to destroy the applet
}
}

5.Write a java program to draw smiley using applet 3M

import java.applet.*;
import java.awt.*;
/*<applet code ="Smiley" width=600 height=600>
</applet>*/

public class Smiley extends Applet {


public void paint(Graphics g)
{

// Oval for face outline


g.drawOval(80, 70, 150, 150);

// Ovals for eyes


// with black color filled
g.setColor(Color.BLACK);
g.fillOval(120, 120, 15, 15);
g.fillOval(170, 120, 15, 15);

// Arc for the smile


g.drawArc(130, 180, 50, 20, 180, 180);
}
}

Output:
7. Explain types of constructor with eg? 8M

Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called
when an instance of the class is created. At the time of calling constructor,
memory for the object is allocated in the memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one
constructor is called.

It calls a default constructor if there is no constructor available in the class.


In such case, Java compiler provides a default constructor by default.

Rules for creating Java constructor


There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
Types of Java constructors
There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Default Constructor
A constructor is called "Default Constructor" when it doesn't have any
parameter.

Syntax of default constructor:

<class_name>(){}

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class.

//Java Program to create and call a default constructor


class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}

Output:

Bike is created

Parameterized Constructor
A constructor which has a specific number of parameters is called a
parameterized constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct


objects. However, you can provide the same values also.

Example of parameterized constructor


In this example, we have created the constructor of Student class that have
two parameters. We can have any number of parameters in the constructor.

//Java Program to demonstrate the use of the parameterized constructo


r.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan

8.Explain multilevel inheritance with eg?

INHERITANCE:

 Inheritance is one of the useful feature of OOPs. It allows a


class to use the properties and methods of another class.
 The purpose of inheritance in java, is to provide the
reusability of code so that a class has to write only the unique
features and rest of the common properties and functionalities
can be inherited from the another class.
 A class can only inherit the fields and methods of another
class, if it extends the class. For example in the following
snippet, class A extends class B. Now class A can access the
fields and methods of class B.

class A extends B
{
}
The concept of parent and child class in Inheritance:

Child Class: The class that extends the features of another class is
known as child class, sub class or derived class. In the above code,
class A is the child class.
Parent Class: The class that shares the fields and methods with the
child class is known as parent class, super class or Base class. In the
above code, Class B is the parent class.

Advantages of Inheritance
 Inheritance removes redundancy from the code.
 Inheritance allows us to reuse of code, it improves
reusability in your java application.
 Reduces code size: By removing redundant code, it
reduces the number of lines of the code.
 Improves logical structure: It allows programmer to
visualize the relationship between different classes.

Syntax:
To inherit a class we use extends keyword. Here, class XYZ is a child
class and class ABC is a parent class. The class XYZ is inheriting the
properties and methods of ABC class.

class XYZ extends ABC


{
}
Terminologies used in Inheritance

Super class and base class are synonyms of Parent class.

 Sub class and derived class are synonyms of Child class.


 Properties and fields are synonyms of Data members.
 Functionality is a synonym of method.

Inheritance Example
In this example, we have a base class Teacher and a sub
class PhysicsTeacher. Child class inherits the following fields and
methods from parent class:

 Properties: designation and collegeName properties


 Method: does()
MULTILEVEL INHERITANCE
When a class extends a class, which extends anther class then this is
called multilevel inheritance. For example class C extends class B
and class B extends class A then this type of inheritance is known as
multilevel inheritance.
Lets see this in a diagram:

It’s pretty clear with the diagram that in Multilevel inheritance there is
a concept of grand parent class. If we take the example of this
diagram, then class C inherits class B and class B inherits class A which
means B is a parent class of C and A is a parent class of B. So in this
case class C is implicitly inheriting the properties and methods of class
A along with class B that’s what is called multilevel inheritance.

Multilevel Inheritance Example


In this example we have three classes – Car, Maruti and Maruti800. We
have done a setup – class Maruti extends Car and
class Maruti800 extends Maruti. With the help of this Multilevel hierarchy
setup our Maruti800 class is able to use the methods of both the
classes (Car and Maruti).

class Car{
public Car()
{
System.out.println("Class Car");
}
public void vehicleType()
{
System.out.println("Vehicle Type: Car");
}
}
class Maruti extends Car{
public Maruti()
{
System.out.println("Class Maruti");
}
public void brand()
{
System.out.println("Brand: Maruti");
}
public void speed()
{
System.out.println("Max: 90Kmph");
}
}
public class Maruti800 extends Maruti{

public Maruti800()
{
System.out.println("Maruti Model: 800");
}
public void speed()
{
System.out.println("Max: 80Kmph");
}
public static void main(String args[])
{
Maruti800 obj=new Maruti800();
obj.vehicleType();
obj.brand();
obj.speed();
}
}
Output:

Class Car
Class Maruti
Maruti Model: 800
Vehicle Type: Car
Brand: Maruti
Max: 80Kmph

9.Explain exception handling in java with eg? 8M


Exception Handling in Java
The Exception Handling in Java is one of the powerful mechanism to
handle the runtime errors so that the normal flow of the application can be
maintained.

In Java, an exception is an event that disrupts the normal flow of the


program. It is an object which is thrown at runtime

Exception Handling is a mechanism to handle runtime errors such as


ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow


of the application. An exception normally disrupts the normal flow of the
application; that is why we need to handle exceptions. Let's consider a
scenario:

1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10.statement 10;

Suppose there are 10 statements in a Java program and an exception occurs


at statement 5; the rest of the code will not be executed, i.e., statements 6
to 10 will not be executed. However, when we perform exception handling,
the rest of the statements will be executed. That is why we use exception
handling in Java.

Hierarchy of Java Exception classes


The java.lang.Throwable class is the root class of Java Exception hierarchy
inherited by two subclasses: Exception and Error. The hierarchy of Java
Exception classes is given below:
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. An error
is considered as the unchecked exception. However, according to Oracle,
there are three types of exceptions namely:

1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception

The classes that directly inherit the Throwable class except


RuntimeException and Error are known as checked exceptions. For example,
IOException, SQLException, etc. Checked exceptions are checked at compile-
time.

2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked


exceptions. For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not
checked at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable. Some example of errors are OutOfMemoryError,


VirtualMachineError, AssertionError etc.

Java exception keywords :


 try
 catch
 finally
 throw
 throws

JavaExceptionExample.java

public class JavaExceptionExample{


public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero


rest of the code...

10.Explain the use of buffered reader object to read characters from the
console using a pgm? 8M
The BufferedReader class of Java is used to read the stream of characters
from the specified source (character-input stream). The constructor of this
class accepts an InputStream object as a parameter.
This class provides a method named read() and readLine() which reads
and returns the character and next line from the source (respectively) and
returns them.
 Instantiate an InputStreamReader class bypassing your
InputStream object as a parameter.
 Then, create a BufferedReader, bypassing the above obtained
InputStreamReader object as a parameter.
 Now, read data from the current reader as String using the
readLine() or read() method.
Example
The following Java program demonstrates how to read integer data from the
user using the BufferedReader class.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Employee{
String name;
int id;
int age;
Employee(String name, int age, int id){
this.name = name;
this.age = age;
this.id = id;
}
public void displayDetails(){
System.out.println("Name: "+this.name);
System.out.println("Age: "+this.age);
System.out.println("Id: "+this.id);
}
}
public class ReadData {
public static void main(String args[]) throws IOException {
BufferedReader reader =new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter your name: ");
String name = reader.readLine();
System.out.println("Enter your age: ");
int age = Integer.parseInt(reader.readLine());
System.out.println("Enter your Id: ");
int id = Integer.parseInt(reader.readLine());
Employee std = new Employee(name, age, id);
std.displayDetails();
}
}
Output
Enter your name:
Krishna
Enter your age:
25
Enter your Id:
1233
Name: Krishna
Age: 25
Id: 1233

11.How interface is declared and implemented in java with eg? * 13M

Interface in Java
 An interface in Java is a blueprint of a class. It has static constants
and abstract methods

 The interface in Java is a mechanism to achieve abstraction. There


can be only abstract methods in the Java interface, not method
body. It is used to achieve abstraction and multiple inheritance in
Java.

In other words, you can say that interfaces can have abstract methods and
variables. It cannot have a method body.

 Java Interface also represents the IS-A relationship.It cannot be


instantiated just like the abstract class. Since, we can have default
and static methods in an interface. Since we can have private
methods in an interface.

To declare an interface
An interface is declared by using the interface keyword. It provides total
abstraction; means all the methods in an interface are declared with the
empty body, and all the fields are public, static and final by default. A class
that implements an interface must implement all the methods declared in
the interface.
Syntax:

interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}

Default Method in Interface


example:

TestInterfaceDefault.java

1. interface Drawable{
2. void draw();
3. default void msg(){System.out.println("default method");}
4. }
5. class Rectangle implements Drawable{
6. public void draw(){System.out.println("drawing rectangle");}
7. }
8. class TestInterfaceDefault{
9. public static void main(String args[]){
10.Drawable d=new Rectangle();
11. d.draw();
12.d.msg();
13. }}

Output:

drawing rectangle
default method

Static Method in Interface


example:
TestInterfaceStatic.java

interface Drawable{

1. void draw();
2. static int cube(int x){return x*x*x;}
3. }
4. class Rectangle implements Drawable{
5. public void draw(){System.out.println("drawing rectangle");}
6. }
7.
8. class TestInterfaceStatic{
9. public static void main(String args[]){
10. Drawable d=new Rectangle();
11.d.draw();
12. System.out.println(Drawable.cube(3));
13.}}

Output:

drawing rectangle
27

Marker or tagged interface:

An interface which has no member is known as a marker or tagged interface,


for example, Serializable, Cloneable, Remote, etc. They are used to provide
some essential information to the JVM so that JVM may perform some useful
operation.

1. //How Serializable interface is written?


2. public interface Serializable{
3. }

Implements interface:

To declare a class that implements an interface, you include an implements clause in the class
declaration. Your class can implement more than one interface, so the implements keyword is
followed by a comma-separated list of the interfaces implemented by the class.
Example:

import java.io.*;

// A simple interface
interface In1 {

// public, static and final


final int a = 10;

// public and abstract


void display();
}

// A class that implements the interface.


class TestClass implements In1 {

// Implementing the capabilities of


// interface.
public void display(){
System.out.println("Geek");
}

// Driver Code
public static void main(String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(a);
}
}

Output
Geek
10
UNIT – 2

12.Write enhanced features of html 5.0 with dgm 13M

You might also like