Nov Dec 18
Nov Dec 18
Nov Dec 18
Part A
1. Define Objects and Classes in Java
A class can be defined as a template/blueprint that describes the behavior/state
that the object of its type support.ie. A class is a blueprint from which individual
objects are created
An Object can be defined as an instance of a class. An object contains an address
and takes up some space in memory. Objects can communicate without knowing
the details of each other's data or code
2. Define access specifier/modifier?
Access specifiers/modifiers in Java helps to restrict the scope of a class,
constructor, variable, method or data member. There are four types of access
modifiers available in java:
Default – No keyword required , Private , Protected and Public
3. What is object cloning?
It is the process of duplicating an object so that two identical objects will exist in
the memory at the same time.
4. What is class hierarchy? Give example
The class hierarchy defines the inheritance relationship between the classes. The
root of the class hierarchy is the class Object. Every class in Java directly or
indirectly extends (inherits from) this class
5. Define Runtime Exception
RuntimeException is the superclass of those exceptions that can be thrown
during the normal operation of the Java Virtual Machine
6. What is the use of assert keyword?
The assert keyword is used in assert statement which is a feature of the Java
programming language since Java 1.4. Assertion enables developers to test
assumptions in their programs as a way to defect and fix bugs
7. What is Multi-threading?
Multithreading is a conceptual programming concept where a program(process)
is divided into two or more subprograms(process), which can be implemented at
the same time in parallel. A multithreaded program contains two or more parts
that can run concurrently. Each part of such a program is called a thread, and
each thread defines a separate path of execution.
8. What is the need for generic code?
Generic programming is a style of computer programming in which algorithms
are written in terms of to-be-specified-later types that are then instantiated when
needed for specific types provided as parameters
9. What is meant by window adapter classes?
The class WindowAdapter is an abstract (adapter) class for receiving window
events. All methods of this class are empty. This class is convenience class for
creating listener objects
10. Enumerate the features of AWT in Java.
A collection of graphical user interface (GUI) components that were
implemented using native-platform versions of the components. These
components provide that subset of functionality which is common to all native
platforms. Largely supplanted by the Project Swing component set.
Part B
11. a. i. Explain the characteristics of OOPs
Encapsulation
Abstraction
Inheritance
Polymorphism
Abstraction of Data
Classes use the concept of abstraction. A class encapsulates the relevant data and
functions that operate on data by hiding the complex implementation details from the
user. The user needs to focus on what a class does rather than how it does.
Encapsulation
Encapsulation, is one of the core reason for the existence of an object. Since the
beginning we have been talking about objects, its data, functions, privacy etc., now it's
time to know how is all this kept bounded. The answer is encapsulation. Much as it
may sound like a capsule, it is pretty much the same. Here we try to encapsulate the
data and functions together which belongs to the same class.
Inheritance
As explained in the previous tutorial, inheritance is about defining a set of core
properties and functions in one place and then re-using them by inheriting the class in
which they are defined.
Python supports Simple, Multiple and MultiLevel Inheritance. We will be covering
these in details in inheritance tutorial.
Polymorphism
Polymorphism, or Poly + Morph, means "many formsb. Precisely, Polymorphism
is the property of any function or operator that can behave differently depending upon
the input that they are fed with.
1) Simple
Java is easy to learn and its syntax is quite simple, clean and easy to
understand.The confusing and ambiguous concepts of C++ are either left out in Java or
they have been re-implemented in a cleaner way.
Eg : Pointers and Operator Overloading are not there in java but were an important part
of C++.
2) Object Oriented
In java everything is Object which has some data and behaviour. Java can be
easily extended as it is based on Object Model.
3) Robust
Java makes an effort to eliminate error prone codes by emphasizing mainly on compile
time error checking and runtime checking. But the main areas which Java improved
were Memory Management and mishandled Exceptions by introducing
automatic Garbage Collector and Exception Handling.
4) 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.
On compilation Java program is compiled into bytecode. This bytecode is platform
independent and can be run on any machine, plus this bytecode format also provide
security. Any machine with Java Runtime Environment can run Java Programs.
5) Secure
When it comes to security, Java is always the first choice. With java secure features it
enable us to develop virus free, temper free system. Java program always runs in Java
runtime environment with almost null interaction with system OS, hence it is more
secure.
6) Multi Threading
Java multithreading feature makes it possible to write program that can do many tasks
simultaneously. Benefit of multithreading is that it utilizes same memory and other
resources to execute multiple threads at the same time, like While typing, grammatical
errors are checked along.
7) Architectural Neutral
Compiler generates bytecodes, which have nothing to do with a particular computer
architecture, hence a Java program is easy to intrepret on any machine.
8) Portable
Java Byte code can be carried to any platform. No implementation dependent features.
Everything related to storage is predefined, example: size of primitive data types
9) High Performance
Java is an interpreted language, so it will never be as fast as a compiled language like C
or C++. But, Java enables high performance with the use of just-in-time compiler.
Methods in Java
Method describe behavior of an object. A method is a collection of statements
that are group together to perform an operation.
Syntax :
return-type methodName(parameter-list)
{
//body of method
}
Example
public String getName(String st)
{
String name="StudyTonight";
name=name+st;
return name;
}
Modifier : Modifier are access type of method. We will discuss it in detail later.
Return Type : A method may return value. Data type of value return by a method is
declare in method heading.
Parameter is variable defined by a method that receives value when the method
is called. Parameter are always local to the method they dont have scope outside the
method. While argument is a value that is passed to a method when it is called
Example
public class Test
{
public void callByValue(int x)
{
x=100;
}
public static void main(String[] args)
{
int x=50;
Test t = new Test();
t.callByValue(x); //function call
System.out.println(x);
}
}
ii. State the purpose of finalize() method in java? With example how finalize()
method can be used in java program
Sometime an object will need to perform some specific task before it is destroyed
such as closing an open connection or releasing any resources held. To handle such
situation finalize() method is used. finalize() method is called by garbage collection
thread before collecting object. Its the last chance for any object to perform cleanup
utility.
gc() method is used to call garbage collector explicitly. However gc() method does
not guarantee that JVM will perform the garbage collection. It only request the JVM for
garbage collection. This method is present in System and Runtime class
public class Test
{
12. a. Define inheritance. With diagrammatic illustration and java program illustrate
the different types of inheritance with an example
Inheritance (IS-A)
Inheritance is one of the key features of Object Oriented Programming.
Inheritance provided mechanism that allowed a class to inherit property of another
class. When a Class extends another class it inherits all non-private members including
fields and methods. Inheritance in Java can be best understood in terms of Parent and
Child relationship, also known as Super class(Parent) and Sub class(child) in Java
language.
Inheritance defines is-a relationship between a Super class and its Sub
class. extends and implements keywords are used to describe inheritance in Java.
class Vehicle.
{
......
}
class Car extends Vehicle
{
....... //extends the property of vehicle class.
}
Vehicle is super class of Car.
Car is sub class of Vehicle.
Car IS-A Vehicle
Purpose of Inheritance
It promotes the code reusabilty i.e the same methods and variables which are
defined in a parent/super/base class can be used in the child/sub/derived class.
It promotes polymorphism by allowing method overriding.
class Parent
{
public void p1()
{
System.out.println("Parent method");
}
}
public class Child extends Parent {
public void c1()
{
System.out.println("Child method");
}
public static void main(String[] args)
{
Child cobj = new Child();
cobj.c1(); //method of Child class
cobj.p1(); //method of Parent class
}
}
Types of Inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Heirarchical Inheritance
b. Write a java program to create a student examination database system that prints
the mark sheets. Input sudent name marks in 6 subjects. This mark should be
between 0 and 100
If the average of marks is>= 80 then prints Grade ‘A’
If the average of marks is< 80 and >=60 then prints Grade ‘B’
If the average of marks is< 60 and >=40 then prints Grade ‘C’
Else prints Grade ‘D’
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Marksheet1
{
class Program
{
static void Main(string[] args)
{
int r, m1, m2, m3, m4,m5,m6,t;
float p;
string n;
Console.WriteLine("Enter Roll Number :");
r = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter Student Name :");
n = Console.ReadLine();
Console.WriteLine("Mark of Subject1 : ");
m1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Mark of Subject2 : ");
m2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Mark of Subject3 : ");
m3 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Mark of Subject4 : ");
m1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Mark of Subject5 : ");
m2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Mark of Subject6 : ");
m3 = Convert.ToInt32(Console.ReadLine());
t = m1 + m2 + m3+m4+m5+m6;
p = t / 6.0f;
Console.WriteLine("Total : " + t);
Console.WriteLine("Percentage : " + p);
if (p >= 40 && p < 60)
{
Console.WriteLine("Grade is C");
}
if (p >= 60 && p <= 80)
{
Console.WriteLine("Grade is B");
}
if (p >= 80)
{
Console.WriteLine("Grade is A");
}
if (p <40)
{
Console.WriteLine("Grade is D");
}
Console.ReadLine();
}
}
}
13. a. Explain the different types of Exceptions and the exception hierarchy in java
with appropriate examples.
Exception Handling is the mechanism to handle runtime malfunctions. We need
to handle such exceptions to prevent abrupt termination of program. The term
exception means exceptional condition, it is a problem that may arise during the
execution of program. A bunch of things can lead to exceptions, including programmer
error, hardware failures, files that need to be opened cannot be found, resource
exhaustion etc
Exception class is for exceptional conditions that program should catch. This class is
extended to create user specific exception classes.
RuntimeException is a subclass of Exception. Exceptions under this class are
automatically defined for programs.
Exceptions of type Error are used by the Java run-time system to indicate errors
having to do with the run-time environment, itself. Stack overflow is an example of
such an error.
Exception are categorized into 3 category.
Checked Exception
The exception that can be predicted by the programmer at the compile time.
Example : File that need to be opened is not found. These type of exceptions must be
checked at compile time.
Unchecked Exception
Unchecked exceptions are the class that extends RuntimeException. Unchecked
exception are ignored at compile time.
Example : ArithmeticException, NullPointerException, Array Index out of Bound
exception. Unchecked exceptions are checked at runtime.
Error
Errors are typically ignored in code because you can rarely do anything about an
error.
Example :if stack overflow occurs, an error will arise. This type of error cannot be
handled in the code.
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...");
}
}
In Java, 3 streams are created for us automatically. All these streams are attached with
the console.
OutputStream vs InputStream
The explanation of OutputStream and InputStream classes are given below:
OutputStream
Java application uses an output stream to write data to a destination; it may be a
file, an array, peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source; it may be a file,
an array, peripheral device or socket.
Let's understand the working of Java OutputStream and InputStream by the figure
given below.
Program to take String input from Keyboard in Java
import java.io.*;
class MyInput
{
public static void main(String[] args)
{
String text;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
text = br.readLine(); //Reading String
System.out.println(text);
}
}
Program to read from a file using BufferedReader class
import java. Io *;
class ReadTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
BufferedReader br = new BufferedReader(new FileReader(fl)) ;
String str;
while ((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close();
fl.close();
}
catch (IOException e)
{ e.printStackTrace(); }
}
}
14. a. Explain in detail the different states of a thread?
A thread is a lightweight sub-process, the smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared
memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.
A thread can be in one of the five states. According to sun, there is only 4 states
in thread life cycle in java new, runnable, non-runnable and terminated. There is no
running state.
The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1. New : A thread begins its life cycle in the new state. It remains in this state until the
start() method is called on it.
2. Runnable : After invocation of start() method on new thread, the thread becomes
runnable.
3. Running : A thread is in running state if the thread scheduler has selected it.
4. Waiting : A thread is in waiting state if it waits for another thread to perform a task.
In this stage the thread is still alive.
5. Terminated : A thread enter the terminated state when it complete its task.
NewThread(String threadname)
{
name = threadname;
thr = new Thread(this, name);
System.out.println("New thread : " + thr);
suspendFlag = false;
thr.start(); // start the thread
}
class SuspendResumeThread
{
public static void main(String args[])
{
try
{
Thread.sleep(1000);
obj1.mysuspend();
System.out.println("Suspending thread One...");
Thread.sleep(1000);
obj1.myresume();
System.out.println("Resuming thread One...");
obj2.mysuspend();
System.out.println("Suspending thread Two...");
Thread.sleep(1000);
obj2.myresume();
System.out.println("Resuming thread Two...");
}
catch(InterruptedException e)
{
System.out.println("Main thread Interrupted..!!");
}
}
}
15. a. State and explain the basic of AWT Event handling in detail
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based
applications in java.
Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system. AWT is heavyweight i.e. its components are
using the resources of OS.
The java.awt package provides classes for AWT api such
as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc
To create simple awt example, you need a frame. There are two ways to create a frame
in AWT.
o By extending Frame class (inheritance)
o By creating the object of Frame class (association)
import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[]){
First f=new First();
}
}
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance
1 BorderLayout
The borderlayout arranges the components to fit in the five regions: east, west,
north, south, and center.
2 CardLayout
The CardLayout object treats each component in the container as a card. Only
one card is visible at a time.
3 FlowLayout
The FlowLayout is the default layout. It layout the components in a directional
flow.
4 GridLayout
The GridLayout manages the components in the form of a rectangular grid.
5 GridBagLayout
This is the most flexible layout manager class. The object of GridBagLayout
aligns the component vertically, horizontally, or along their baseline without
requiring the components of the same size.
6 GroupLayout
The GroupLayout hierarchically groups the components in order to position
them in a Container.
7 SpringLayout
A SpringLayout positions the children of its associated container according to a
set of constraints.