OOP using JAVA(NEP)
Important Questions
1. Explain features of Java.
Ans:
Object Oriented: In java, everything is an object which has some data and behaviour. Java can be
easily extended as it is based on Object Model. Following are some basic concept of OOP's.
Inheritance, Polymorphism, Abstraction, Encapsulation.
Robust :Java makes an effort to eliminate error prone codes by emphasizing mainly on compile time
error checking and runtime checking.
Platform Independent: Unlike other programming languages such as C, C++ etc which are compiled
into platform specific machines. Java is guaranteed to be write-once, run-anywhere language.
Multi Threading: Java multithreading feature makes it possible to write program that can do many
tasks simultaneously.
Architectural Neutral: Compiler generates bytecodes, which have nothing to do with a particular
computer architecture, hence a Java program is easy to 1nterpret on any machine.
Portable: Java Byte code can be carried to any platform. No implementation dependent features.
2. List out the differences between Java and C.
Java C
Java is an object-oriented programming C is a structural and procedure-oriented
language programming language.
It is an interpreted language. It is a compiled language.
It is platform-independent. It is platform dependent.
It does not support the concepts of pointers It supports the concept of the pointer.
because of security.
Preprocessors are not supported in Java. Preprocessors are supported in C
3. Explain architecture of JVM with a neat diagram.
Ans: Java Virtual Machine (JVM) is a engine that provides runtime environment to drive the Java Code
or applications. It converts Java bytecode into machines language. JVM is a part of Java Runtime
Environment (JRE). First, Java code is compiled into bytecode. This bytecode gets interpreted on
different machines
JVM architecture in Java contains classloader, memory area, execution engine etc.
1)ClassLoader: The class loader is a subsystem used for loading class files. It performs three major
functions viz. Loading, Linking, and Initialization.
2)Method Area: JVM Method Area stores class structures like metadata, the constant runtime pool, and
the code for methods.
3)Heap: All the Objects, their related instance variables, and arrays are stored in the heap. This memory
is common and shared across multiple threads.
4)JVM language Stacks: Java language Stacks store local variables, and it’s partial results. Each thread
has its own JVM stack, created simultaneously as the thread is created. A new frame is created
whenever a method is invoked, and it is deleted when method invocation process is complete.
5)PC Registers: PC register store the address of the Java virtual machine instruction which is currently
executing. In Java, each thread has its separate PC register.
6)Native Method Stacks: Native method stacks hold the instruction of native code depends on the
native library. It is written in another language instead of Java.
7)Execution Engine: It is a type of software used to test hardware, software, or complete systems. The
test execution engine never carries any information about the tested product.
8)Native Method interface: The Native Method Interface is a programming framework. It allows Java
code which is running in a JVM to call by libraries and native applications.
9)Native Method Libraries : Native Libraries is a collection of the Native Libraries(C, C++) which are
needed by the Execution Engine.
4. Explain command line arguments with an example.
Ans: Command Line Argument in Java is the information that is passed to the program when it is
executed. The information passed is stored in the string array passed to the main() method and it is
stored as a string.
Example
Step 1)
class Demo{
public static void main(String args[]){
System.out.println("Argument one = "+args[0]);
System.out.println("Argument two = "+args[1]);
}
}
Step 2) Save & Compile the code
Step 3) Run the code as java Demo apple orange.
Output:
Argument one= apple
Argument two= orange
5. Write a note on Java data types.
Ans: Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:
Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and
double.
Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
Java Primitive Data Types
In Java language, primitive data types are the building blocks of data manipulation. These are the most
basic data types available in Java language.
There are 8 types of primitive data types:
boolean data type
byte data type
char data type
short data type
int data type
long data type
float data type
double data type
6. Explain type casting.
Ans: Implicit Casting:
This type of type conversion is also called Widening Type Conversion/ Implicit Conversion/ Casting
Down. In this case, as the lower data types with smaller sizes are converted into higher ones with a
larger size, there is no chance of data loss.
Example
public class Main {
public static void main(String[] args) {
int intType = 20;
// Float is of higher data type than int
float floatType = intType;
System.out.println("intType: "+intType);
System.out.println("floatType: "+floatType);
}
}
Output:
intType: 20
floatType: 20.0
Explicit casting:
Type casting is also called Narrowing Type Casting/ Explicit Conversion/ Casting Up. In this case, as
the higher data types with a larger size are converted into lower ones with a smaller size, there is a
chance of data loss. This is the reason that this type of conversion does not happen automatically.
Example:
public class Main {
public static void main(String[] args) {
int intType = 20;
// Short is of lower data type than int
short shortType = (short)intType;
System.out.println("intType: "+intType);
System.out.println("shortType: "+shortType);
}
}
Output:
intType: 20
shortType: 20
7. Explain looping statements in java.
Ans: Loops in Java
Looping in Java is defined as performing some lines of code in an ordered fashion until a condition is
false. The condition is important because we do not want the loop to be running forever. As soon as
this condition is false, the loop stops.
In Java there are three primary types of loops:-
1. for loop
2. Enhanced for loop/ for each loop
3. while loop
4. do-while loop
1. For loop in Java
Java for loop consists of 3 primary factors which define the loop itself. These are the initialization
statement, a testing condition, an increment or decrement part for incrementing/decrementing the
control variable.
The basic syntax of java for loop goes like this:
for(initializing statement;testing condition;increment/decrement)
{
//code to be iterated
}
Example:
import java.io. * ;
public class ForLoop {
public static void main(String[] args) {
int i;
for (i = 0; i <= 10; i++) {
System.out.println("Studying for loops at DataFlair");
System.out.println("Value of i = " + i);
}
}
}
2. Enhanced for loop in Java/ for each loop
This is similar to a for loop except that it has some enhanced features.
It can be used to iterate over the elements of a collection without knowing the index of each element.
You also need not know the size of the collection.
The syntax for Java enhanced for loop is:
for(<datatype> <variable_name>:<collection_name>)
{
//Statements;
}
Example:
import java.io. * ;
public class EnhancedFor {
public static void main(String[] args) {
String array[] = {
"DataFlair",
"Java",
"Python"
};
for (String a: array) {
System.out.println(a);
}
}
}
3. While loop in Java
While loops are very important as we cannot know the extent of a loop everytime we define one. For
example if we are asked to take a dynamic collection and asked to iterate through every element, for
loops would be impossible to use because we do not know the size of the collection. Then we would
have to use an enhanced for loop or a while loop.
A while loop iterates through a set of statements till its boolean condition returns false. As long as the
condition given evaluates to true, the loop iterates.
The basic syntax of Java while loop is:
while(boolean condition)
{
//statements;
}
Example:
import java.io. * ;
public class WhileLoop {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println("Learning Java at DataFlair");
System.out.println("The value of i is = " + i);
i++;
}
System.out.println("The value of i became " + i + " that is why it broke out of the loop");
}
}
4. do while loop in Java
Java do while loop executes the statement first and then checks for the condition.Other than that it is
similar to the while loop. The difference lies in the fact that if the condition is true at the starting of the
loop the statements would still be executed, however in case of while loop it would not be executed at
all.
This is an exit-controlled loop because of the fact that it checks the condition after the statements inside
it are executed.
Example:
import java.io. * ;
public class DoWhileLoop {
public static void main(String[] args) {
int i = 0;
do {
i++;
System.out.println("Learning Java at DataFlair");
System.out.println("The value of i is " + i);
}
while ( i != 5 );
}
}
8. Differentiate between AWT and Swing.
Ans:
AWT Swing
The Components used in AWT are mainly The Components used in Swing are not
dependent on the operating system. dependent on the operating system. It is
completely scripted in Java.
The AWT is heavyweight since it uses the The Swing is mostly lightweight since it
resources of the operating system. doesn't need any Operating system object for
processing. The Swing Components are built
on the top of AWT.
Java AWT needs a higher amount of memory Java Swing needs less memory space as
for the execution. compared to Java AWT.
Java AWT is slower than swing in terms of Java Swing is faster than the AWT.
performance.
The Java AWT provides a smaller number of Java Swing provides a greater number of
components in comparison to Swing. components than AWT, such as list, scroll
panes, tables, color choosers, etc.
9. Explain break and continue statements with an example.
Ans: Break Statement:
The break statement can also be used to jump out of a loop.
This example stops the loop when i is equal to 4:
Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
}
Output:
0
1
2
3
Continue Statement:
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues
with the next iteration in the loop.
This example skips the value of 4:
Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
}
Output:
0
1
2
3
5
6
7
8
9
10. What is package? Explain user defined package.
Ans: A package as the name suggests is a pack(group) of classes, interfaces and other packages. In java
we use packages to organize our classes and interfaces. We have two types of packages in Java: built-in
packages and the packages we can create (also known as user defined package).
In java we have several built-in packages, for example when we need user input, we import a package
like this:
import java.util.Scanner
Here:
→ java is a top level package
→ util is a sub package
→ and Scanner is a class which is present in the sub package util.
Types of packages in Java
As mentioned in the beginning of this guide that we have two types of packages in java.
1) User defined package: The package we create is called user-defined package.
2) Built-in package: The already defined package like java.io.*, java.lang.* etc are known as built-in
packages.
User-defined package
We have created a class Calculator inside a package name letmecalculate. To create a class inside a
package, declare the package name in the first statement in your program. A class can have only one
package declaration.
Calculator.java file created inside a package letmecalculate
package letmecalculate;
public class Calculator {
public int add(int a, int b){
return a+b;
}
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(10, 20));
}
}
Now lets see how to use this package in another program.
import letmecalculate.Calculator;
public class Demo{
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(100, 200));
}
}
11. Explain different access specifiers/visibility modifiers in java.
Ans: The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or
class. We can change the access level of fields, constructors, methods, and class by applying the access
modifier on it.
There are four types of Java access modifiers:
Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
Default: The access level of a default modifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default.
Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the package.
Public: The access level of a public modifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.
1) Private
The private access modifier is accessible only within the class.
Example:
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
2) Default
If you don't use any modifier, it is treated as default by default.
Example:
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
3) Protected
The protected access modifier is accessible within package and outside the package but through
inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can't be
applied on the class.
Example:
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
Example:
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
12. Explain final variable, final method and class with an example.
Ans: 1) final variable
final variables are nothing but constants. We cannot change the value of a final variable once it is
initialized. Lets have a look at the below code:
class Demo{
final int MAX_VALUE=99;
void myMethod(){
MAX_VALUE=101;
}
public static void main(String args[]){
Demo obj=new Demo();
obj.myMethod();
}
}
2) final method
A final method cannot be overridden. Which means even though a sub class can call the final method
of parent class without any issues but it cannot override it.
Example:
class XYZ{
final void demo(){
System.out.println("XYZ Class Method");
}
}
class ABC extends XYZ{
void demo(){
System.out.println("ABC Class Method");
}
public static void main(String args[]){
ABC obj= new ABC();
obj.demo();
}
}
3) final class
We cannot extend a final class. Consider the following example:
final class XYZ{
}
class ABC extends XYZ{
void demo(){
System.out.println("My Method");
}
public static void main(String args[]){
ABC obj= new ABC();
obj.demo();
}
}
13. Write a note on String class.
Ans: String is a sequence of characters, for e.g. “Hello” is a string of 5 characters. In java, string is an
immutable object which means it is constant and can cannot be changed once it is created.
Java String Methods
Here are the list of the methods available in the Java String class.
1. char charAt(int index): It returns the character at the specified index. Specified index value should be
between 0 to length() -1 both inclusive. It throws IndexOutOfBoundsException if index<0||>= length of
String.
2. boolean equals(Object obj): Compares the string with the specified string and returns true if both
matches else false.
3. boolean equalsIgnoreCase(String string): It works same as equals method but it doesn’t consider the
case while comparing strings. It does a case insensitive comparison.
4. int compareTo(String string): This method compares the two strings based on the Unicode value of
each character in the strings.
5. int compareToIgnoreCase(String string): Same as CompareTo method however it ignores the case
during comparison.
6. int hashCode(): It returns the hash code of the string.
7. int indexOf(int ch): Returns the index of first occurrence of the specified character ch in the string.
14. Explain Abstract classes with an example.
Ans: A class that is declared using “abstract” keyword is known as abstract class. It can have abstract
methods(methods without body) as well as concrete methods (regular methods with body). A normal
class(non-abstract class) cannot have abstract methods.
Abstract class Example
//abstract parent class
abstract class Animal{
//abstract method
public abstract void sound();
}
//Dog class extends Animal class
public class Dog extends Animal{
public void sound(){
System.out.println("Woof");
}
public static void main(String args[]){
Animal obj = new Dog();
obj.sound();
}
}
Output:
Woof
15. What are interfaces? How interfaces can be used for implementing multiple inheritance.
Ans: Interface
An interface is a fully abstract class i.e., it includes a set of abstract methods that specifies what a class
must do and not how to do it. Hence, if a class implements an interface, it inherits all the abstract
methods of the interface and provides an implementation for each of them.
Interfaces are non-instantiable and provide a representation of what a class should implement i.e.,
interfaces do not contain detailed instructions for their behaviors.
Example:
// CNG Car interface
interface CNG_Car{
// Abstract methods
void drive();
void cng_kit();
}
// Petrol Car interface
interface Petrol_Car{
// Abstract methods
void drive();
void petrol_kit();
}
// Multiple Inheritance using Interface
class Hybrid_Car implements Petrol_Car, CNG_Car {
public void drive(){
System.out.println("Driving a Hybrid Car");
}
// Overridden method of CNG_Car Interface
public void cng_kit(){
System.out.println("Using the CNG kit for Hybrid Car");
}
// Overridden method of Petrol_Car Interface
public void petrol_kit(){
System.out.println("Using the Petrol kit for Hybrid Car");
}
}
// Driver Code
class Main {
public static void main(String args[]) {
// Creating a new object of the Hybrid Car class
Hybrid_Car obj = new Hybrid_Car();
// Calling the methods of the Hybrid_Car class
obj.drive();
obj.cng_kit();
obj.petrol_kit();
}
}
Output:
Driving a Hybrid Car
Using the CNG kit for Hybrid Car
Using the Petrol kit for Hybrid Car
16. Explain any 6 GUI components with an example.
Ans: AWT Button
In Java, AWT contains a Button Class. It is used for creating a labelled button which can perform an
action.
AWT Button Classs Declaration:
public class Button extends Component implements Accessible
Example:
Lets take an example to create a button and it to the frame by providing coordinates.
import java.awt.*;
public class ButtonDemo1
{
public static void main(String[] args)
{
Frame f1=new Frame("studytonight ==> Button Demo");
Button b1=new Button("Press Here");
b1.setBounds(80,200,80,50);
f1.add(b1);
f1.setSize(500,500);
f1.setLayout(null);
f1.setVisible(true);
}
}
AWT Label
In Java, AWT contains a Label Class. It is used for placing text in a container. Only Single line text is
allowed and the text can not be changed directly.
Label Declaration:
public class Label extends Component implements Accessible
Example:
In this example, we are creating two labels to display text to the frame.
import java.awt.*;
class LabelDemo1
{
public static void main(String args[])
{
Frame l_Frame= new Frame("studytonight ==> Label Demo");
Label lab1,lab2;
lab1=new Label("Welcome to studytonight.com");
lab1.setBounds(50,50,200,30);
lab2=new Label("This Tutorial is of Java");
lab2.setBounds(50,100,200,30);
l_Frame.add(lab1);
l_Frame.add(lab2);
l_Frame.setSize(500,500);
l_Frame.setLayout(null);
l_Frame.setVisible(true);
}
}
AWT TextField
In Java, AWT contains aTextField Class. It is used for displaying single line text.
TextField Declaration:
public class TextField extends TextComponent
Example:
We are creating two textfields to display single line text string. This text is editable in nature, see the
below example.
import java.awt.*;
class TextFieldDemo1{
public static void main(String args[]){
Frame TextF_f= new Frame("studytonight ==>TextField");
TextField text1,text2;
text1=new TextField("Welcome to studytonight");
text1.setBounds(60,100, 230,40);
text2=new TextField("This tutorial is of Java");
text2.setBounds(60,150, 230,40);
TextF_f.add(text1);
TextF_f.add(text2);
TextF_f.setSize(500,500);
TextF_f.setLayout(null);
TextF_f.setVisible(true);
}
}
AWT Checkbox
In Java, AWT contains a Checkbox Class. It is used when we want to select only one option i.e true or
false. When the checkbox is checked then its state is "on" (true) else it is "off"(false).
Checkbox Syntax
public class Checkbox extends Component implements ItemSelectable, Accessible
Example:
In this example, we are creating checkbox that are used to get user input. If checkbox is checked it
returns true else returns false.
import java.awt.*;
public class CheckboxDemo1
{
CheckboxDemo1(){
Frame checkB_f= new Frame("studytonight ==>Checkbox Example");
Checkbox ckbox1 = new Checkbox("Yes", true);
ckbox1.setBounds(100,100, 60,60);
Checkbox ckbox2 = new Checkbox("No");
ckbox2.setBounds(100,150, 60,60);
checkB_f.add(ckbox1);
checkB_f.add(ckbox2);
checkB_f.setSize(400,400);
checkB_f.setLayout(null);
checkB_f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxDemo1();
}
}
AWT List
In Java, AWT contains a List Class. It is used to represent a list of items together. One or more than
one item can be selected from the list.
List Declaration:
public class List extends Component implements ItemSelectable, Accessible
Example:
In this example, we are creating a list that is used to list out the items.
import java.awt.*;
public class ListDemo
{
ListDemo()
{
Frame list_f= new Frame();
List obj=new List(6);
obj.setBounds(80,80, 100,100);
obj.add("Red");
obj.add("Blue");
obj.add("Black");
obj.add("Pink");
obj.add("White");
obj.add("Green");
list_f.add(obj);
list_f.setSize(400,400);
list_f.setLayout(null);
list_f.setVisible(true);
}
public static void main(String args[])
{
new ListDemo();
}
}
17. Explain creating and extending thread with an example.
Ans: There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.Thread
class extends Object class and implements Runnable interface.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
Thread Example by extending Thread class
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Thread Example by implementing Runnable interface
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
t1.start();
}
}
18. What is constructor? Explain types of constructor with an example.
Ans: 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.
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
Java 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. It will be invoked at the time
of object creation.
//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();
}
}
Java Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized constructor.
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 constructor.
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();
}
}
19. Explain exception handling with an example.
Ans: Exception handling is one of the most important feature of java programming that allows us to
handle the runtime errors caused by exceptions.
An Exception is an unwanted event that interrupts the normal flow of the program. When an exception
occurs program execution gets terminated. In such cases we get a system generated error message.
Errors indicate that something went wrong which is not in the scope of a programmer to handle. You
cannot handle an error. Also, the error doesn’t occur due to bad data entered by user rather it indicates a
system failure, disk crash or resource unavailability.
Exceptions are events that occurs during runtime due to bad data entered by user or an error in
programming logic. A programmer can handle such conditions and take necessary corrective actions.
There are two types of exceptions in Java:
1) Checked exceptions
2) Unchecked exceptions
1) Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler
checks them during compilation to see whether the programmer has handled them or not. If these
exceptions are not handled/declared in the program, you will get compilation error. For example,
SQLException, IOException, ClassNotFoundException etc.
Checked Exception Example
import java.io.*;
class Example {
public static void main(String args[]) throws IOException
{
FileInputStream fis = null;
fis = new FileInputStream("B:/myfile.txt");
int k;
while(( k = fis.read() ) != -1)
{
System.out.print((char)k);
}
fis.close();
}
}
2) Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked at
compile-time so compiler does not check whether the programmer has handled them or not but it’s the
responsibility of the programmer to handle these exceptions and provide a safe exit.
Unchecked Exception Example
class Example {
public static void main(String args[])
{
int num1=10;
int num2=0;
/*Since I'm dividing an integer with 0
* it should throw ArithmeticException
*/
int res=num1/num2;
System.out.println(res);
}
}
20. Explain applet life cycle with neat diagram.
Ans: an applet is a special type of program embedded in the web page to generate dynamic content.
Applet is a class in Java.
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.
There are five methods of an applet life cycle, and they are:
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.
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.
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.
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.
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.
21. Explain life cycle of a thread.
Ans: Life Cycle of Thread in Java is basically state transitions of a thread that starts from its birth and
ends on its death.
When an instance of a thread is created and is executed by calling start() method of Thread class, the
thread goes into runnable state.
When sleep() or wait() method is called by Thread class, the thread enters into non-runnable state.
From non-runnable state, thread comes back to runnable state and continues execution of statements.
When the thread comes out of run() method, it dies. These state transitions of a thread are called Thread
life cycle in Java.
1. New (Newborn State): When we create a thread object using Thread class, thread is born and is
known to be in Newborn state. That is, when a thread is born, it enters into new state but the start()
method has not been called yet on the instance.
2. Runnable state: Runnable state means a thread is ready for execution. When the start() method is
called on a new thread, thread enters into a runnable state.
3. Running state: Running means Processor (CPU) has allocated time slot to thread for its execution.
When thread scheduler selects a thread from the runnable state for execution, it goes into running state.
a) When sleep() method is invoked on a thread to sleep for specified time period, the thread is out of
queue during this time period. The thread again reenters into the runnable state as soon as this time
period is elapsed.
b) When a thread is suspended using suspend() method for some time in order to satisfy some
conditions. A suspended thread can be revived by using resume() method.
c) When wait() method is called on a thread to wait for some time. The thread in wait state can be run
again using notify() or notifyAll() method.
4. Blocked state: A thread is considered to be in the blocked state when it is suspended, sleeping, or
waiting for some time in order to satisfy some condition.
5. Dead state: A thread dies or moves into dead state automatically when its run() method completes
the execution of statements. That is, a thread is terminated or dead when a thread comes out of run()
method. A thread can also be dead when the stop() method is called.
22. What is Inheritance? Explain types of inheritance.
Ans: Inheritance is a mechanism in which one class acquires the property of another class. For
example, a child inherits the traits of his/her parents. With inheritance, we can reuse the fields and
methods of the existing class. Hence, inheritance facilitates Reusability and is an important concept of
OOPs.
Types of Inheritance
Single Inheritance:
In Single Inheritance one class extends another class (one class only).
Class B extends only Class A. Class A is a super class and Class B is a Sub-class.
Example:
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:
In Multilevel Inheritance, one class can inherit from a derived class. Hence, the derived class becomes
the base class for the new class.
Class C is subclass of B and B is a of subclass Class A.
Example:
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();
}}
Hierarchical Inheritance:
In Hierarchical Inheritance, one class is inherited by many sub classes.
Class B, C, and D inherit the same class A.
Example:
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
}}
Multiple Inheritance:
Multiple Inheritance is one of the inheritance in Java types where one class extending more than one
class. Java does not support multiple inheritance.
Class C extends Class A and Class B both.
23. Explain method overloading and method overriding.
Ans: Method Overloading is a feature that allows a class to have multiple methods with the same
name but with different number, sequence or type of parameters. In short multiple methods with same
name but with different signatures.
This is one of the most popular OOP feature in java
Three ways to overload a method
In order to overload a method, the parameter list of the methods must differ in either of these:
1. Number of parameters.
For example: This is a valid case of overloading
add(int, int)
add(int, int, int)
2. Data type of parameters.
For example:
add(int, int)
add(int, float)
3. Sequence of Data type of parameters.
For example:
add(int, float)
add(float, int)
Method Overloading Example:
class DisplayOverloading
{
//adding two integer numbers
int add(int a, int b)
{
int sum = a+b;
return sum;
}
//adding three integer numbers
int add(int a, int b, int c)
{
int sum = a+b+c;
return sum;
}
}
class JavaExample
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
System.out.println(obj.add(10, 20));
System.out.println(obj.add(10, 20, 30));
}
}
Output:
30
60
Method Overriding
Declaring a method in sub class which is already present in parent class is known as method
overriding. Overriding is done so that a child class can give its own implementation to a method which
is already provided by the parent class. In this case the method in parent class is called overridden
method and the method in child class is called overriding method.
Example:
class Human{
//Overridden method
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}
}
Output:
Boy is eating
24. Explain any 5 math class methods.
Ans: Java Math class provides several methods to work on math calculations like min(), max(), avg(),
sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.
Example
public class JavaMathExample1
{
public static void main(String[] args)
{
double x = 28;
double y = 4;
// return the maximum of two numbers
System.out.println("Maximum number of x and y is: " +Math.max(x, y));
// return the square root of y
System.out.println("Square root of y is: " + Math.sqrt(y));
//returns 28 power of 4 i.e. 28*28*28*28
System.out.println("Power of x and y is: " + Math.pow(x, y));
// return the logarithm of given value
System.out.println("Logarithm of x is: " + Math.log(x));
System.out.println("Logarithm of y is: " + Math.log(y));
// return the logarithm of given value when base is 10
System.out.println("log10 of x is: " + Math.log10(x));
System.out.println("log10 of y is: " + Math.log10(y));
// return the log of x + 1
System.out.println("log1p of x is: " +Math.log1p(x));
// return a power of 2
System.out.println("exp of a is: " +Math.exp(x));
// return (a power of 2)-1
System.out.println("expm1 of a is: " +Math.expm1(x));
}
}
25. Explain object creation in java.
Ans: We know that everything is an object in Java. A class is a model or user-defined blueprint for
creating objects. It encapsulates the relevant data members and methods (behaviors) that an object of
that class will have.
A simple example of a Java class is as:
public class Car {
// Declaration of variables
String make;
String model;
int year;
// Declaration of methods
void start() {
System.out.println("Engine started.");
}
void stop() {
System.out.println("Engine stopped.");
}
}
In this example, we have created a class named “Car” that contains three instance variables (make,
model, and year) and two instance methods (start() and stop()).
Creating an object means allocating memory to store the data of variables temporarily. That is, we
create an object of a class to store data temporarily.
we can create an object of a class using the new keyword in three steps. They are as follows.
1.Declaration of a reference variable.
2.Creation of an object.
3.inking the object and the reference variable.
College myCollege = new College();
where,
College ➝Name of the class.
myCollege ➝Object reference variable which stores the address of the object in the stack memory.
new ➝keyword that stores the object in the heap memory.
College() ➝Constructor of the class.
= ➝ The equal sign (=) is an assignment operator. It simply says to take the object created by a new
keyword and assign it to the object reference variable.
26. Explain arrays in java with an example.
Ans:
Array is a collection of elements of same type. For example an int array contains integer elements and
a String array contains String elements.
This is how an array looks like:
int number[] = new int[10]
Here number is the array name. The type of the array is integer, which means it can store integer
values. The size of the array is 10.
Array works on an index-based system. In the above array, number[0] represents the first element of
the array, number[1] represents the second element of the array and so on. The index of array starts
from 0 and ends at array_size-1.
Declaration, Instantiation and Initialization of Array in Java
This is how we declare, instantiate and initialize an array.
int number[]; //array declaration
number[] = new int[10]; //array instantiation
number[0] = 10; //array Initialization
number[1] = 20; //array Initialization
Example:
The following example demonstrates, how we declared an int array, initialized it with integers and print
the elements of the array using for loop.
public class JavaExample{
public static void main(String args[]){
//array declaration, instantiation and initialization
int number[] = {11, 22, 33, 44, 55};
//print array elements
//length property return the size of the array
for(int i=0;i<number.length;i++)
System.out.println("number["+i+"]: "+number[i]);
}
}
Types of array in Java
1.Single Dimensional Array
2. Multidimensional Array
1. Single dimensional array
public class JavaExample{
public static void main(String args[]){
//array declaration
String names[] = new String[5];
//array initialization
names[0]="Chaitanya";
names[1]="Ajeet";
names[2]="Rahul";
names[3]="Shivam";
names[4]="Rohit";
//print array elements
for(int i=0;i<names.length;i++)
System.out.println("names["+i+"]: "+names[i]);
}
}
Output:
names[0]: Chaitanya
names[1]: Ajeet
names[2]: Rahul
names[3]: Shivam
names[4]: Rohit
2. Multidimensional array
Multidimensional array declaration:
This is how you can declare a multidimensional array: All the four syntax are valid multidimensional
array declaration.
int[][] arr;
int [][]arr;
int arr[][];
int []arr[];
Instantiate Multidimensional Array in Java
Number of elements in multidimensional array = number of rows*number of columns.
The following array can store upto 2*3 = 6 elements.
int[][] arr=new int[2][3]; //2 rows and 3 columns
Initialize Multidimensional Array in Java
arr[0][0]=11;
arr[0][1]=22;
arr[0][2]=33;
arr[1][0]=44;
arr[1][1]=55;
arr[1][2]=66;
Example:
public class JavaExample{
public static void main(String args[]){
//two rows and three columns
int arr[][]={{11,22,33},{44,55,66}};
//outer loop 0 till number of rows
for(int i=0;i<2;i++){
//inner loop from 0 till number of columns
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
//new line after each row
System.out.println();
}
}
}
Output:
11 22 33
44 55 66
27. Explain switch case with an example.
Ans: Switch case statement is used when we have number of options (or choices) and we may need to
perform a different task for each choice.
The syntax of Switch case statement looks like this –
switch (variable or an integer expression)
{
case constant:
//Java code
;
case constant:
//Java code
;
default:
//Java code
;
}
public class SwitchCaseExample {
public static void main(String args[]){
int i=2;
switch(i)
{
case 1:
System.out.println("Case1 ");
break;
case 2:
System.out.println("Case2 ");
break;
case 3:
System.out.println("Case3 ");
break;
case 4:
System.out.println("Case4 ");
break;
default:
System.out.println("Default ");
}
}
}
Output:
Case2
28. Differentiate between String class and String Buffer class.
Ans:
String Class String Buffer Class
The String class is immutable The StringBuffer class is mutable.
String is slow and consumes more memory StringBuffer is fast and consumes less
when we concatenate too many strings memory when we concatenate t strings.
because every time it creates new instance.
String class overrides the equals() method of StringBuffer class doesn't override the equals()
Object class. So you can compare the contents method of Object class.
of two strings by equals() method.
String class is slower while performing StringBuffer class is faster while performing
concatenation operation. concatenation operation.
String class uses String constant pool. StringBuffer uses Heap memory