0% found this document useful (0 votes)
35 views9 pages

Java Importent Q

The document discusses different types of type casting in Java including widening and narrowing type casting. It provides examples of each. It also defines some OOPs concepts like class, object, inheritance, polymorphism and interfaces in Java.

Uploaded by

nirojmarki15
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)
35 views9 pages

Java Importent Q

The document discusses different types of type casting in Java including widening and narrowing type casting. It provides examples of each. It also defines some OOPs concepts like class, object, inheritance, polymorphism and interfaces in Java.

Uploaded by

nirojmarki15
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/ 9

Q. Define type Casting With its types and example.

Typecasting, or type conversion, is a method of changing an entity from one data type to another.
It is used in computer programming to ensure variables are correctly processed by a function.
Types of Type Casting
(a) Widening Type Casting: - Converting a lower data type into a higher one is
called widening type casting. It is also known as implicit conversion or casting down. It is done
automatically. It is safe because there is no chance to lose data. It takes place when:
• Both data types must be compatible with each other.
• The target type must be larger than the source type.
• byte -> short -> char -> int -> long -> float -> double
For example,
public class WideningTypeCastingExample
{
public static void main(String[] args)
{
int x = 7;
long y = x;
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
}
OUTPUT: -
Before conversion, the value is: 7
After conversion, the long value is: 7
After conversion, the float value is: 7.0

(b) Narrowing Type Casting: - Converting a higher data type into a lower one is
called narrowing type casting. It is also known as explicit conversion or casting up. It is done
manually by the programmer. If we do not perform casting then the compiler reports a compile-
time error.
• double -> float -> long -> int -> char -> short -> byte
Let's see an example of narrowing type casting: -
public class NarrowingTypeCastingExample
{
public static void main(String args[])
{
double d = 166.66;
long l = (long)d;
int i = (int)l;
System.out.println("Before conversion: "+d);
System.out.println("After conversion into long type: "+l);
System.out.println("After conversion into int type: "+i);
}
}
OUTPUT: -
Before conversion: 166.66
After conversion into long type: 166
After conversion into int type: 166
Q. SHORT NOTES: -
HTTP PROTOCOL: -
o HTTP stands for HyperText Transfer Protocol. It is a protocol used to access the data on the World Wide
Web (www).
o The HTTP protocol can be used to transfer the data in the form of plain text, hypertext, audio, video, and so
on.
o This protocol is known as HyperText Transfer Protocol because of its efficiency that allows us to use in a
hypertext environment where there are rapid jumps from one document to another document. HTTP is used
to carry the data in the form of MIME-like format.
o HTTP is similar to SMTP as the data is transferred between client and server. The HTTP differs from the
SMTP in the way the messages are sent from the client to the server and from server to the client. SMTP
messages are stored and forwarded while HTTP messages are delivered immediately.
SERVLET: - Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page). Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was common as a server-side programming language.
However, there were many disadvantages to this technology. We have discussed these disadvantages below.
There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet, HttpServlet,
ServletRequest, ServletResponse, etc.
o Servlet is a technology which is used to create a web application.
o Servlet is an API that provides many interfaces and classes including documentation.
o Servlet is an interface that must be implemented for creating any Servlet.
o Servlet is a class that extends the capabilities of the servers and responds to the incoming requests. It can
respond to any requests.
o Servlet is a web component that is deployed on the server to create a dynamic web page.
METHOD OVERLOADDING: - If a class has multiple methods having same name but different in parameters,
it is known as Method Overloading. If we have to perform only one operation, having same name of the
methods increases the readability of the program. Suppose you have to perform addition of the given numbers
but there can be any number of arguments, if you write the method such as a (int,int) for two parameters,
and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to
understand the behavior of the method because its name differs.
OVERRIDING: - In any object-oriented programming language, Overriding is a feature that allows a
subclass or child class to provide a specific implementation of a method that is already provided by one of
its super-classes or parent classes. When a method in a subclass has the same name, same parameters or
signature, and same return type (or sub-type) as a method in its super-class, then the method in the
subclass is said to override the method in the super-class. Method overriding is one of the ways by which
java achieve Run time polymorphism. The version of a method that is executed will be determined by the
object that is used to invoke it. If an object of a parent class is used to invoke the method, then the version
in the parent class will be executed, but if an object of the subclass is used to invoke the method, then the
version in the child class will be executed. In other words, it is the type of the object being referred to (not
the type of the reference variable) that determines which version of an overridden method will be executed.
What is Interface? Different Form of interface in JAVA.
In Java, an interface is a reference type similar to a class that can contain only constants, the method
signatures, default methods, and static methods, and ts Nested types. In interfaces, method bodies exist
only for default methods and static methods. Writing an interface is similar to writing to a standard class.
Still, a class describes the attributes and internal behaviors objects, and an interface contains behaviors
that a class implements. On the other side unless the class that implements the interface is purely abstract
and all the interface methods need to be defined in that given usable class.
Types of Interfaces: -
Functional Interface:
Functional Interface is an interface that has only pure one abstract method.It can have any number of static
and default methods and also even public methods of java.lang.Object classes When an interface contains
only one abstract method, then it is known as a Functional Interface.
Examples of Functional Interfaces:
Runnable: It contains only run() method
ActionListener: It contains only actionPerformed()
ItemListener: It contains only itemStateChanged() method
Marker Interface:
An interface that does not contain any methods, fields, Abstract Methods, and any Constants is Called a
Marker interface. Also, if an interface is empty, then it is known as Marker Interface. The Serializable and
the Cloneable interfaces are examples of Marker interfaces.
Q. What is Constructor? Write example program of parametrized and default constructor.
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.
Example Default Constructor

class Bike1{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}
}
Output:
Bike is created
Example of parameterized constructor
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Gitam");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Output:
111 Gitam
222 Aryan
Q. What do you mean by object-oriented programming Explain different oops concept.
Object-Oriented Programming System (OOPs) is a programming concept that works on the
principles of abstraction, encapsulation, inheritance, and polymorphism. It allows users to create
objects they want and create methods to handle those objects. The basic concept of OOPs is to
create objects, re-use them throughout the program, and manipulate these objects to get results.
OOP meaning “Object Oriented Programming” is a popularly known and widely used concept in
modern programming languages like java.
OOPs Concepts in Java: -
1) Class: -The class is one of the Basic concepts of OOPs which is a group of similar entities. It is
only a logical component and not the physical entity. Let’s understand this one of the OOPs
Concepts with example, if you had a class called “Expensive Cars” it could have objects like
Mercedes, BMW, Toyota, etc. Its properties(data) can be price or speed of these cars. While the
methods may be performed with these cars are driving, reverse, braking etc.
2) Object: -An object can be defined as an instance of a class, and there can be multiple instances
of a class in a program. An Object is one of the Java OOPs concepts which contains both the data
and the function, which operates on the data. For example – chair, bike, marker, pen, table, car,
etc.
3) Inheritance: -Inheritance is one of the Basic Concepts of OOPs in which one object acquires
the properties and behaviors of the parent object. It’s creating a parent-child relationship between
two classes. It offers robust and natural mechanism for organizing and structure of any software.
4) Polymorphism: -Polymorphism refers to one of the OOPs concepts in Java which is the ability
of a variable, object or function to take on multiple forms. For example, in English, the
verb run has a different meaning if you use it with a laptop, a foot race, and business. Here, we
understand the meaning of run based on the other words used along with it. The same also
applied to Polymorphism.
5) Abstraction: -Abstraction is one of the OOP Concepts in Java which is an act of representing
essential features without including background details. It is a technique of creating a new data
type that is suited for a specific application. Lets understand this one of the OOPs Concepts with
example, while driving a car, you do not have to be concerned with its internal working. Here you
just need to concern about parts like steering wheel, Gears, accelerator, etc.
6) Encapsulation: -Encapsulation is one of the best Java OOPs concepts of wrapping the data and
code. In this OOPs concept, the variables of a class are always hidden from other classes. It can
only be accessed using the methods of their current class. For example – in school, a student
cannot exist without a class.
7) Association: -Association is a relationship between two objects. It is one of the OOP Concepts
in Java which defines the diversity between objects. In this OOP concept, all objects have their
separate lifecycle, and there is no owner. For example, many students can associate with one
teacher while one student can also associate with multiple teachers.
8) Aggregation: -In this technique, all objects have their separate lifecycle. However, there is
ownership such that child object can’t belong to another parent object. For example consider
class/objects department and teacher. Here, a single teacher can’t belong to multiple
departments, but even if we delete the department, the teacher object will never be destroyed.
9) Composition: -Composition is a specialized form of Aggregation. It is also called “death”
relationship. Child objects do not have their lifecycle so when parent object deletes all child object
will also delete automatically. For that, let’s take an example of House and rooms. Any house can
have several rooms. One room can’t become part of two different houses. So, if you delete the
house room will also be deleted.
Q. What do you mean by inheritance? Explain different types of inheritance with syntax and
example program.
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors
of a parent object. It is an important part of OOPs (Object Oriented programming system). The idea
behind inheritance in Java is that you can create new classes that are built upon existing classes.
When you inherit from an existing class, you can reuse methods and fields of the parent class.
Moreover, you can add new methods and fields in your current class also. Inheritance represents
the IS-A relationship which is also known as a parent-child relationship.
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
Single level Inheritance: - When a class inherits another class, it is known as a single
inheritance. In the example given below, Dog class inherits the Animal class, so there is the single
inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Multilevel Inheritance: - When there is a chain of inheritance, it is known as multilevel
inheritance. As you can see in the example given below, BabyDog class inherits the Dog class
which again inherits the Animal class, so there is a multilevel inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output: -
weeping...
barking...
eating...
Hierarchical Inheritance: - When two or more classes inherits a single class, it is known
as hierarchical inheritance. In the example given below, Dog and Cat classes inherits the Animal
class, so there is hierarchical inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output: -
meowing...
eating...

SERVLET PROGRAM: -
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class HelloWorld extends HttpServlet {

private String message;

public void init() throws ServletException {


// Do required initialization
message = "Hello World";
}

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Set response content type


response.setContentType("text/html");

// Actual logic goes here.


PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}

public void destroy() {


// do nothing.
}
}
Q. What is exception handling.
He 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 this tutorial, we will learn about Java exceptions, it's types, and the difference between checked
and unchecked exceptions.
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.
What do you mean by package? Explain different types of packages with example program.
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Types in packages: -
Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some of the
commonly used built-in packages are:
1) java.lang: Contains language support classes(e.g classed which defines primitive data types,
math operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List, Dictionary
and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user interfaces (like
button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.
User-defined packages
These are the packages that are defined by the user. First we create a directory myPackage (name
should be same as the name of the package). Then create the MyClass inside the directory with
the first statement being the package names.
// Name of the package must be same as the directory
// under which this file is saved
package myPackage;
public class MyClass
{
public void getNames(String s)
{
System.out.println(s);
}
}
Now we can use the MyClass class in our program.
/* import 'MyClass' class from 'names' myPackage */
import myPackage.MyClass;
public class PrintName
{
public static void main(String args[])
{
String name = "GeeksforGeeks";
MyClass obj = new MyClass();
obj.getNames(name);
}
}
Q. What is thread? Explain life cycle of Thread, With diagram.

All programmers are familiar with writing sequential programs. You’ve probably written a program
that displays "Hello World!" or sorts a list of names or computes a list of prime numbers. These are
sequential programs. That is, each has a beginning, an execution sequence, and an end. At any
given time during the runtime of the program, there is a single point of execution. A thread is
similar to the sequential programs described previously. A single thread also has a beginning, a
sequence, and an end. At any given time during the runtime of the thread, there is a single point
of execution. However, a thread itself is not a program; a thread cannot run on its own. Rather, it
runs within a program. The following figure shows this relationship.

Life cycle of a Thread (Thread States): - In Java, a thread always exists in any one of the
following states. These states are:

New
Active
Blocked / Waiting
Timed Waiting
Terminated
Explanation of Different Thread States
New: Whenever a new thread is created, it is always in the new state. For a thread in the new
state, the code has not been run yet and thus has not begun its execution.
Active: When a thread invokes the start() method, it moves from the new state to the active state.
The active state contains two states within it: one is runnable, and the other is running.
Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then,
either the thread is in the blocked state or is in the waiting state.
For example, a thread (let's say its name is A) may want to print some data from the printer.
However, at the same time, the other thread (let's say its name is B) is using the printer to print
some data. Therefore, thread A has to wait for thread B to use the printer. Thus, thread A is in
the blocked state. A thread in the blocked state is unable to perform any execution and thus
never consume any cycle of the Central Processing Unit (CPU). Hence, we can say that thread A
remains idle until the thread scheduler reactivates thread A, which is in the waiting or blocked
state.
Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its name is A)
has entered the critical section of a code and is not willing to leave that critical section. In such a
scenario, another thread (its name is B) has to wait forever, which leads to starvation. To avoid
such scenario, a timed waiting state is given to thread B. Thus, thread lies in the waiting state for
a specific span of time, and not forever. A real example of timed waiting is when we invoke the
sleep() method on a specific thread. The sleep() method puts the thread in the timed wait state.
After the time runs out, the thread wakes up and start its execution from when it has left earlier.
Terminated: A thread reaches the termination state because of the following reasons:
When a thread has finished its job, then it exists or terminates normally.
Abnormal termination: It occurs when some unusual events such as an unhandled exception or
segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the thread is
dead, and there is no way one can respawn (active after kill) the dead thread.
Q. What is an applet? And its types and explain the applet life cycle with diagram.

An applet is a Java program that can be embedded into a web page. It runs inside the web browser
and works on the client-side. An applet is embedded in an HTML page using the APPLET or OBJECT
tag and hosted on a web server. The entire life cycle of an applet is managed by the Applet Container.
All applets are sub-classes (either directly or indirectly) of java. applet. Applet class. Applets are
not stand-alone programs. They run either within a web browser or an applet viewer.

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.

o Applet program: -

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

public class HelloWorldApplet extends Applet {


public void paint (Graphics g) {
g.drawString ("Hello World", 25, 50);
}
}
Invoking an Applet
<html>
<title>The Hello, World Applet</title>
<hr>
<applet code = "HelloWorldApplet.class" width = "320" height = "120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
<hr>
</html>

You might also like