CS8392-UnivKey (NOVl18)

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 32

CS8392-Object Oriented Programming Department of CSE Nov/Dec 18

PART-A
1 Define Objects and Classes in Java
Each class is a collection of data and the function that manipulate the data.The data
components of the class are called data fields and the function components of the class are
called member functions or methods. The class that contains main function is called main
class.
Object is an instance of a class. The objects represent real world entity. The
objects are used to provide a practical basis for the real world. Objects are used
to understand the real world. The object can be declared by specifying the name
of the class.
2 Define Access Specifier.
Java Access Specifiers (also known as Visibility Specifiers) regulate access to classes, fields and
methods in java. These specifiers determine whether a field or method in c lass, can be used or
invoked by another method in another class or sub-class. Access Specifiers can be used to restrict
access.There are 4 types of java access modifiers: Private, Default, 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. In single inheritance, a class is derived from one direct superclass. In Java, multiple inheritance
is not supported; a class can only have one direct superclass.
5 Define Runtime Exceptions.
Unchecked are the exceptions that are not checked at compiled time. In C++, all exceptions are
unchecked, so it is not forced by the compiler to either handle or specify the exception. It is up to the
programmers to be civilized, and specify or catch the exceptions.
In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else
under throwable is checked.
6 What is the use of assert keyword?
An assert statement is used to declare an expected boolean condition in a program. If the program is
running with assertions enabled, then the condition is checked at runtime. If the condition is false,
the Java runtime system throws an AssertionError .
7 What is Multithreading?
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?
Code that uses generics has many benefits over non-generic code: Stronger type checks at compile
time. A Java compiler applies strong type checking to generic code and issues errors if the code
violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be
difficult to find.
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 –(5*13=65 marks)

St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 1 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
11 a
Explain the Characteristics of OOPs
(i)

Encapsulation – Encapsulation is capturing data and keeping it safely and securely from
outside interfaces.
Inheritance- This is the process by which a class can be derived from a base class with all
features of base class and some of its own. This increases code reusability.
Polymorphism- This is the ability to exist in various forms. For example an operator can be
overloaded so as to add two integer numbers and two floats.
Abstraction- The ability to represent data at a very conceptual level without any details.
Some key features of the Object Oriented programming are:
- Emphasis on data rather than procedure
- Programs are divided into entities known as objects
- Data Structures are designed such that they characterize objects
- Functions that operate on data of an object are tied together in data structures
- Data is hidden and cannot be accessed by external functions
- Objects communicate with each other through functions
- New data and functions can be easily added whenever necessary
- Follows bottom up design in program design

11 a Explain the features and characteristics of Java.


(ii) The primary objective of Java programming language creation was to make it portable, simple
and secure programming language. Apart from this, there are also some excellent features
which play an important role in the popularity of this language. The features of Java are also
known as java buzzwords.
A list of most important features of Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun, Java language is a simple programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.

Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects that
incorporates both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software development
and maintenance by providing some rules.

St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 2 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run anywhere
language. A platform is the hardware or software environment in which a program runs.
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o Classloader: Classloader in Java is a part of the Java Runtime Environment(JRE) which
is used to load Java classes into the Java Virtual Machine dynamically. It adds security
by separating the package for the classes of the local file system from those that are
imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate access
right to objects.
o Security Manager: It determines what resources a class can access such as reading and
writing to the local disk.
Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.

Robust
Robust simply means strong. Java is robust because:
o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o There is automatic garbage collection in java which runs on the Java Virtual Machine to
get rid of objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these
points make Java robust.

Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4
bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32
and 64-bit architectures in Java.

Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation.

High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode
is "close" to native code. It is still a little bit slower than a compiled language (e.g., C++). Java
is an interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc.

Distributed
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 3 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
Java is distributed because it facilitates users to create distributed applications in Java. RMI
and EJB are used for creating distributed applications. This feature of Java makes us able to
access files by calling the methods from any machine on the internet.

Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications, etc.
Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.
Java supports dynamic compilation and automatic memory management (garbage collection).

11 b What is a method?How method is defined?Give example


i In the Java programming language, a method is a section of the program that contains a set of
instructions or code. In a Java program, similar to a cake recipe, a method has a set of
instructions. When the method is called, the set of instructions within the method is executed.

Here, the name of the method is addNumbers. When the method addNumbers is called, the
code within the method is executed, and the variable z is printed.
Parameters of a Method
When following the method to make cake, the ingredients like sugar and butter are combined
and processed to make the final product. Similarly, Java methods have parameters (like
ingredients) or data that are inputted or passed into the method. The method uses these
parameter values to do the necessary data manipulation and processing. The method then
usually returns the final value after all the necessary data processing is successfully
performed.

In this example, m and n are parameters. The Java method subtractNumbers finds the
difference between m and n and saves the result in a new variable p. The values of the
parameters m and n are used to generate the new variable p that is printed out on the
computer screen.
The parameters of a method are declared within parentheses following the method name. If
there is more than one parameter, they are separated by commas. Both the data type and the
variable name (int m, int n) are specified for the parameters.

11b State the purpose of finalize() method in java? With an example explain how finalize()
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 4 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
(ii) method can be used in java program.
finalize() method is a protected and non-static method of java.lang.Object class. This method
will be available in all objects you create in java. This method is used to perform some final
operations or clean up operations on an object before it is removed from the memory. you can
override the finalize() method to keep those operations you want to perform before an object
is destroyed. Here is the general form of finalize() method.

protected void finalize() throws Throwable


{
//Keep some resource closing operations here
}
EXAMPLE

public class ObjectDemo extends GregorianCalendar {

public static void main(String[] args) {


try {
// create a new ObjectDemo object
ObjectDemo cal = new ObjectDemo();

// print current time


System.out.println("" + cal.getTime());

// finalize cal
System.out.println("Finalizing...");
cal.finalize();
System.out.println("Finalized.");

} catch (Throwable ex) {


ex.printStackTrace();
}
}
}
OUTPUT
Finalizing...
Finalized.
12 a Define Inheritance.With diagrammatic illustration and java programs illustrate the
different types of inheritance with an example.
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. Types of Inheritance
There are Various types of inheritance in Java:
1. Single Inheritance:
In Single Inheritance one class extends another class (one class only).

St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 5 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18

In above diagram, Class B extends only Class A. Class A is a super class and Class B is a
Sub-class.
2. Multiple Inheritance:
In Multiple Inheritance, one class extending more than one class. Java does not support
multiple inheritance.

As per above diagram, Class C extends Class A and Class B both.


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

As per shown in diagram Class C is subclass of B and B is a of subclass Class A.


4. Hierarchical Inheritance:
In Hierarchical Inheritance, one class is inherited by many sub classes.

St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 6 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18

As per above example, Class B, C, and D inherit the same class A.


5. Hybrid Inheritance:
Hybrid inheritance is a combination of Single and Multiple inheritance.

As per above example, all the public and protected members of Class A are inherited into
Class D, first via Class B and secondly via Class C.
Java Inheritance Example

class Doctor {
void Doctor_Details() {
System.out.println("Doctor Details...");
}
}

class Surgeon extends Doctor {


St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 7 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
void Surgeon_Details() {
System.out.println("Surgen Detail...");
}
}

public class Hospital {


public static void main(String args[]) {
Surgeon s = new Surgeon();
s.Doctor_Details();
s.Surgeon_Details();
}
}
Super Keyword
The super keyword is similar to "this" keyword.
The keyword super can be used to access any data member or methods of the parent class.
Super keyword can be used at variable, method and constructor level.
Syntax:
super.<method-name>();
12 Write a Java program to create a student examination database system that prints the mark sheet of
b students.Input student 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’
import java.util.Scanner;
public class CaseGrade {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
String name ;
int grade;
String exellent = "Exellent :";
String veryGgood ="Very Good :";
String good="Good :";
String pass ="Pass :";
String fail = "Fail :";

int max = 0;
int min = 100;
int sum = 0;
int avg ;
int counter =0;

boolean repeat ;
while (repeat =true)
{
System.out.println("Enter Name : ");
name = input.next();
System.out.println("Enter Grade : ");
grade = input.nextInt();

if (grade == -1 )
{
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 8 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
avg = sum / counter;
System.out.println(" result = :");
System.out.println(exellent +"\n"+ veryGgood +"\n"+ good +"\n"+
pass +"\n"+fail);
System.out.println("maximum = "+ max +"\t");
System.out.println("minimum = "+ min +"\t");
System.out.println("\tAverage = " +avg);
System.exit(0);
}

switch (grade/10)
{
case 100:
case 9 :
exellent += "\n"+ name + "\t" +grade+"\n";

break;
case 8 :
veryGgood += "\n" + name + "\t" +grade +"\n";

break ;

case 7 :
good += "\n" + name + "\t" +grade +"\n";

break;
case 6:
case 5:
pass += "\n" + name + "\t" +grade +"\n";
break;

default:
fail +="\n" + name + "\t" +grade +"\n";
break;

sum = sum + grade;


counter = counter + 1;

if (grade > max)


{
max = grade;
}
if (grade < min)
{
min = grade;
}

}
}
}
13a Explain the different types of Exceptions and the exception hierarchy in java with
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 9 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
appropriate examples.
Java being an object oriented programming language, whenever an error occurs while
executing a statement, creates an exception object and then the normal flow of the program
halts and JRE tries to find someone that can handle the raised exception. The exception object
contains a lot of debugging information such as method hierarchy, line number where the
exception occurred, type of exception etc. When the exception occurs in a method, the process
of creating the exception object and handing it over to runtime environment is
called “throwing the exception”. Once runtime receives the exception object, it tries to find
the handler for the exception. Exception Handler is the block of code that can process the
exception object. The logic to find the exception handler is simple – starting the search in the
method where error occurred, if no appropriate handler found, then move to the caller
method and so on. So if methods call stack is A->B->C and exception is raised in method C,
then the search for appropriate handler will move from C->B->A. If appropriate exception
handler is found, exception object is passed to the handler to process it. The handler is said to
be “catching the exception”. If there are no appropriate exception handler found then
program terminates printing information about the exception.Note that Java Exception
handling is a framework that is used to handle runtime errors only, compile time errors are
not handled by exception handling in java.
Java Exception Handling Keywords
Java provides specific keywords for exception handling purposes, we will look after them first
and then we will write a simple program showing how to use them for exception handling.
1. throw – We know that if any exception occurs, an exception object is getting created and
then Java runtime starts processing to handle them. Sometime we might want to
generate exception explicitly in our code, for example in a user authentication program
we should throw exception to client if the password is null. throw keyword is used to
throw exception to the runtime to handle it.

2. throws – When we are throwing any exception in a method and not handling it, then we
need to use throws keyword in method signature to let caller program know the
exceptions that might be thrown by the method. The caller method might handle these
exceptions or propagate it to it’s caller method using throws keyword. We can provide
multiple exceptions in the throws clause and it can be used with main() method also.

3. try-catch – We use try-catch block for exception handling in our code. try is the start of
the block and catch is at the end of try block to handle the exceptions. We can have
multiple catch blocks with a try and try-catch block can be nested also. catch block
requires a parameter that should be of type Exception.

4. finally – finally block is optional and can be used only with try-catch block. Since
exception halts the process of execution, we might have some resources open that will
not get closed, so we can use finally block. finally block gets executed always, whether
exception occurred or not.

Exception Hierarchy

St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 10 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18

Example:
class JavaException {
public static void main(String args[]) {
int d = 0;
int n = 20;
try {
int fraction = n / d;
System.out.println("This line will not be Executed");
} catch (ArithmeticException e) {
System.out.println("In the catch Block due to Exception = " + e);
}
System.out.println("End Of Main");
}
}
13 What are input and output streams?Explain them with illustrations.
b Stream
A stream can be defined as a sequence of data. There are two kinds of Streams −
 InPutStream − The InputStream is used to read data from a source.
 OutPutStream − The OutputStream is used for writing data to a destination.

Java provides strong but flexible support for I/O related to files and networks but this
tutorial covers very basic functionality related to streams and I/O. We will see the most
commonly used examples one by one −
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are
many classes related to byte streams but the most frequently used classes
are, FileInputStream and FileOutputStream. Following is an example which makes use of
these two classes to copy an input file into an output file −
Example

import java.io.*;

public class CopyFile {

public static void main(String args[]) throws IOException {

St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 11 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18

FileInputStream in = null;

FileOutputStream out = null;

try {

in = new FileInputStream("input.txt");

out = new FileOutputStream("output.txt");

int c;

while ((c = in.read()) != -1) {

out.write(c);

}finally {

if (in != null) {

in.close();

if (out != null) {

out.close();

}
Now let's have a file input.txt with the following content –
This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating
output.txt file with the same content as we have in input.txt. So let's put the above code in
CopyFile.java file and do the following –

$javac CopyFile.java

$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas

St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 12 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
Java Character streams are used to perform input and output for 16-bit unicode. Though
there are many classes related to character streams but the most frequently used classes
are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.
We can re-write the above example, which makes the use of these two classes to copy an
input file (having unicode characters) into an output file −
Example

import java.io.*;

public class CopyFile {

public static void main(String args[]) throws IOException {

FileReader in = null;

FileWriter out = null;

try {

in = new FileReader("input.txt");

out = new FileWriter("output.txt");

int c;

while ((c = in.read()) != -1) {

out.write(c);

}finally {

if (in != null) {

in.close();

if (out != null) {

out.close();

St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 13 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18

}
Now let's have a file input.txt with the following content –
This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating
output.txt file with the same content as we have in input.txt. So let's put the above code in
CopyFile.java file and do the following –

$javac CopyFile.java

$java CopyFile
Standard Streams
All the programming languages provide support for standard I/O where the user's program
can take input from a keyboard and then produce an output on the computer screen. If you
are aware of C or C++ programming languages, then you must be aware of three standard
devices STDIN, STDOUT and STDERR. Similarly, Java provides the following three standard
streams −
 Standard Input − This is used to feed the data to user's program and usually a
keyboard is used as standard input stream and represented as System.in.
 Standard Output − This is used to output the data produced by the user's program
and usually a computer screen is used for standard output stream and represented
as System.out.
 Standard Error − This is used to output the error data produced by the user's program
and usually a computer screen is used for standard error stream and represented
as System.err.
Following is a simple program, which creates InputStreamReader to read standard input
stream until the user types a "q" −
Example

import java.io.*;

public class ReadConsole {

public static void main(String args[]) throws IOException {

InputStreamReader cin = null;

try {

cin = new InputStreamReader(System.in);

System.out.println("Enter characters, 'q' to quit.");

char c;

St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 14 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18

do {

c = (char) cin.read();

System.out.print(c);

} while(c != 'q');

}finally {

if (cin != null) {

cin.close();

}
Let's keep the above code in ReadConsole.java file and try to compile and execute it as shown
in the following program. This program continues to read and output the same character
until we press 'q' –

$javac ReadConsole.java

$java ReadConsole

Enter characters, 'q' to quit.

q
Reading and Writing Files
As described earlier, a stream can be defined as a sequence of data. The InputStream is used
to read data from a source and the OutputStream is used for writing data to a destination.
Here is a hierarchy of classes to deal with Input and Output streams.

St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 15 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18

The two important streams are FileInputStream and FileOutputStream, which would be
discussed in this tutorial.
FileInputStream
This stream is used for reading data from the files. Objects can be created using the
keyword new and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the
file −
InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read the file. First
we create a file object using File() method as follows −
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
Once you have InputStream object in hand, then there is a list of helper methods which can be
used to read to stream or to do other operations on the stream.
Sr.No. Method & Description

1 public void close() throws IOException{}


This method closes the file output stream. Releases any system resources
associated with the file. Throws an IOException.

2 protected void finalize()throws IOException {}


This method cleans up the connection to the file. Ensures that the close
method of this file output stream is called when there are no more
references to this stream. Throws an IOException.

3 public int read(int r)throws IOException{}


This method reads the specified byte of data from the InputStream.
Returns an int. Returns the next byte of data and -1 will be returned if it's
the end of the file.

St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 16 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
4 public int read(byte[] r) throws IOException{}
This method reads r.length bytes from the input stream into an array.
Returns the total number of bytes read. If it is the end of the file, -1 will
be returned.

5 public int available() throws IOException{}


Gives the number of bytes that can be read from this file input stream.
Returns an int.
There are other important input streams available, for more detail you can refer to the
following links −
 ByteArrayInputStream
 DataInputStream
FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream would create a file,
if it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write
the file −
OutputStream f = new FileOutputStream("C:/java/hello")
Following constructor takes a file object to create an output stream object to write the file.
First, we create a file object using File() method as follows −
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
Once you have OutputStream object in hand, then there is a list of helper methods, which can
be used to write to stream or to do other operations on the stream.
Sr.No. Method & Description

1 public void close() throws IOException{}


This method closes the file output stream. Releases any system resources
associated with the file. Throws an IOException.

2 protected void finalize()throws IOException {}


This method cleans up the connection to the file. Ensures that the close
method of this file output stream is called when there are no more
references to this stream. Throws an IOException.

3 public void write(int w)throws IOException{}


This methods writes the specified byte to the output stream.

4 public void write(byte[] w)


Writes w.length bytes from the mentioned byte array to the
OutputStream.
There are other important output streams available, for more detail you can refer to the
following links −
 ByteArrayOutputStream
 DataOutputStream

Example
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 17 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
Following is the example to demonstrate InputStream and OutputStream –

import java.io.*;

public class fileStreamTest {

public static void main(String args[]) {

try {

byte bWrite [] = {11,21,3,40,5};

OutputStream os = new FileOutputStream("test.txt");

for(int x = 0; x < bWrite.length ; x++) {

os.write( bWrite[x] ); // writes the bytes

os.close();

InputStream is = new FileInputStream("test.txt");

int size = is.available();

for(int i = 0; i < size; i++) {

System.out.print((char)is.read() + " ");

is.close();

} catch (IOException e) {

System.out.print("Exception");

}
The above code would create file test.txt and would write given numbers in binary format.
Same would be the output on the stdout screen.

St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 18 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
File Navigation and I/O
There are several other classes that we would be going through to get to know the basics of
File Navigation and I/O.
 File Class
 FileReader Class
 FileWriter Class
Directories in Java
A directory is a File which can contain a list of other files and directories. You use File object
to create directories, to list down files available in a directory. For complete detail, check a list
of all the methods which you can call on File object and what are related to directories.
Creating Directories
There are two useful File utility methods, which can be used to create directories −
 The mkdir( ) method creates a directory, returning true on success and false on failure.
Failure indicates that the path specified in the File object already exists, or that the
directory cannot be created because the entire path does not exist yet.
 The mkdirs() method creates both a directory and all the parents of the directory.
Following example creates "/tmp/user/java/bin" directory −
Example

import java.io.File;

public class CreateDir {

public static void main(String args[]) {

String dirname = "/tmp/user/java/bin";

File d = new File(dirname);

// Create directory now.

d.mkdirs();

}
Compile and execute the above code to create "/tmp/user/java/bin".
Note − Java automatically takes care of path separators on UNIX and Windows as per
conventions. If you use a forward slash (/) on a Windows version of Java, the path will still
resolve correctly.
Listing Directories
You can use list( ) method provided by File object to list down all the files and directories
available in a directory as follows –

Example

St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 19 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18

import java.io.File;

public class ReadDir {

public static void main(String[] args) {

File file = null;

String[] paths;

try {

// create new file object

file = new File("/tmp");

// array of files and directory

paths = file.list();

// for each name in the path array

for(String path:paths) {

// prints filename and directory name

System.out.println(path);

} catch (Exception e) {

// if any error occurs

e.printStackTrace();

}
This will produce the following result based on the directories and files available in
your /tmp directory −
Output

St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 20 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18

test1.txt

test2.txt

ReadDir.java

ReadDir.class
14 a Explain in detail the different states of a thread?
Lifecycle and States of a Thread in Java
A thread in Java at any point of time exists in any one of the following states. A thread lies
only in one of the shown states at any instant:
1. New
2. Runnable
3. Blocked
4. Waiting
5. Timed Waiting
6. Terminated
The diagram shown below represent various states of a thread at any instant of time.

Image source: Core Java Vol 1, 9th Edition, Horstmann, Cay S. & Cornell, Gary_2013
Life Cycle of a thread
1. New Thread: When a new thread is created, it is in the new state. The thread has not yet
started to run when thread is in this state. When a thread lies in the new state, it’s code is
yet to be run and hasn’t started to execute.
2. Runnable State: A thread that is ready to run is moved to runnable state. In this state, a
thread might actually be running or it might be ready run at any instant of time. It is the
responsibility of the thread scheduler to give the thread, time to run.
A multi-threaded program allocates a fixed amount of time to each individual thread.
Each and every thread runs for a short while and then pauses and relinquishes the CPU
to another thread, so that other threads can get a chance to run. When this happens, all
such threads that are ready to run, waiting for the CPU and the currently running thread
lies in runnable state.
3. Blocked/Waiting state:When a thread is temporarily inactive, then it’s in one of the

St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 21 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
following states:
 Blocked
 Waiting
For example, when a thread is waiting for I/O to complete, it lies in the blocked state. It’s
the responsibility of the thread scheduler to reactivate and schedule a blocked/waiting
thread. A thread in this state cannot continue its execution any further until it is moved
to runnable state. Any thread in these states do not consume any CPU cycle.
A thread is in the blocked state when it tries to access a protected section of code that is
currently locked by some other thread. When the protected section is unlocked, the
schedule picks one of the thread which is blocked for that section and moves it to the
runnable state. Whereas, a thread is in the waiting state when it waits for another thread
on a condition. When this condition is fulfilled, the scheduler is notified and the waiting
thread is moved to runnable state.
If a currently running thread is moved to blocked/waiting state, another thread in the
runnable state is scheduled by the thread scheduler to run. It is the responsibility of
thread scheduler to determine which thread to run.
4. Timed Waiting: A thread lies in timed waiting state when it calls a method with a time
out parameter. A thread lies in this state until the timeout is completed or until a
notification is received. For example, when a thread calls sleep or a conditional wait, it is
moved to timed waiting state.
5. Terminated State: A thread terminates because of either of the following reasons:
 Because it exists normally. This happens when the code of thread has entirely
executed by the program.
 Because there occurred some unusual erroneous event, like segmentation fault or an
unhandled exception.
A thread that lies in terminated state does no longer consumes any cycles of CPU.

14 Demonstrate Inter thread Communication and suspending,resuming and stopping threads.


b
Understanding the process of inter-thread communication

The point to point explanation of the above diagram is as follows:

1. Threads enter to acquire lock.


2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it
releases the lock and exits.
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 22 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable
state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of the
object.

1. class Customer{
2. int amount=10000;
3.
4. synchronized void withdraw(int amount){
5. System.out.println("going to withdraw...");
6.
7. if(this.amount<amount){
8. System.out.println("Less balance; waiting for deposit...");
9. try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed..."); }
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
} }

class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}
start();
new Thread(){
public void run(){c.deposit(10000);}
}start();

}}
Output: going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed

St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 23 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
15 State and explain the basic of AWT Event handling in detail.
a Event and Listener (Java Event Handling)
Changing the state of an object is known as an event. For example, click on button,
dragging mouse etc. The java.awt.event package provides many event classes and
Listener interfaces for event handling.
Java Event classes and Listener interfaces
Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener
Steps to perform Event Handling
Following steps are required to perform event handling:
1. Register the component with the Listener
Registration Methods
For registering the component with the Listener, many classes provide the
registration methods. For example:
o Button - public void addActionListener(ActionListener a){}
o MenuItem - public void addActionListener(ActionListener a){}
o TextField - public void addActionListener(ActionListener a){}, public void
addTextListener(TextListener a){}
o TextArea - public void addTextListener(TextListener a){}
o Checkbox - public void addItemListener(ItemListener a){}
o Choice - public void addItemListener(ItemListener a){}
o List - public void addActionListener(ActionListener a){}, public void
addItemListener(ItemListener a){}
15 Describe in detail about the different layout in Java GUI.Which layout is the default one?
b Java LayoutManagers

The LayoutManagers are used to arrange components in a particular manner. LayoutManager


is an interface that is implemented by all the classes of layout managers. There are following
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 24 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18

classes that represents the layout managers:

1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.

Java BorderLayout

The BorderLayout is used to arrange the components in five regions: north, south, east, west
and center. Each region (area) may contain one component only. It is the default layout of
frame or window. The BorderLayout provides five constants for each region:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:


o BorderLayout(): creates a border layout but with no gaps between the components.
o JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal
and vertical gaps between the components.
o Example of BorderLayout class:

St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 25 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18

1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class Border {
5. JFrame f;
6. Border(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("NORTH");;
10. JButton b2=new JButton("SOUTH");;
11. JButton b3=new JButton("EAST");;
12. JButton b4=new JButton("WEST");;
13. JButton b5=new JButton("CENTER");;
14.
15. f.add(b1,BorderLayout.NORTH);
16. f.add(b2,BorderLayout.SOUTH);
17. f.add(b3,BorderLayout.EAST);
18. f.add(b4,BorderLayout.WEST);
19. f.add(b5,BorderLayout.CENTER);
20.
21. f.setSize(300,300);
22. f.setVisible(true);
23. }
24. public static void main(String[] args) {
25. new Border();
26. }
27. }
download this example

Part C – (1*15=15)
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 26 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18

16 Create a Bank database application program to illustrate the use of multithreads.


a Bank Class
import java.util.ArrayList;

public class Bank {


private ArrayList<Account> accounts;

public Bank(int accountsCount) {


accounts = new ArrayList<Account>();
for (int i = 0; i < accountsCount; i++) {
accounts.add(new Account(i));
}
}

public Account getRandomAccount() {


return accounts.get((int) (Math.random() * accounts.size()));
}

public void printSummary() {


for (Account a : accounts)
System.out.println(a.toString());
}
}
Account class
public class Account {
private int balance = 1000;
private int number;

public Account(int number) {


this.number = number;
}

public synchronized int getBalance() {


return balance;
}

public synchronized void withdraw(Client client, int bal) {


try {

if (balance >= bal) {


System.out.println(client.getName() + " "
+ "is trying to withdraw from account " + number);
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
balance = balance - bal;
System.out.println(client.getName() + " "
+ "has completed withdrawal from account " + number);

St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 27 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
} else {
System.out
.println(client.getName()
+""
+ "doesn't have enough money for withdraw from account "
+ number);
}
System.out.println(client.getName() + " withdrawal value: "
+ balance + " from account " + number);
} catch (Exception e) {
e.printStackTrace();
}
}

public synchronized void deposit(Client client, int bal) {


try {
if (bal > 0) {
System.out.println(client.getName() + " "
+ "trying to deposit on account " + number);
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
balance = balance + bal;
System.out.println(client.getName() + " "
+ "has completed the deposit on account " + number);
} else {
System.out.println(client.getName() + " "
+ " doesn't have enough money for deposit on account "
+ number);
}
System.out.println(client.getName() + " deposited " + balance
+ " on account " + number);
} catch (Exception e) {
e.printStackTrace();
}
}

@Override
public String toString() {
return "Account " + number + " balance: " + balance;
}
}
Client Class
public class Client {
private String name;

public Client(String name) {


this.name = name;
}

St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 28 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
public String getName() {
return name;
}

public void setName(String name) {


this.name = name;
}

@Override
public String toString() {
return name;
}
}
Main Class
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Main extends Thread implements Runnable {

private static final int CLIENT_COUNT = 5;


private static final int CLIENT_ITERATIONS = 5;
private static final int ACCOUNTS_COUNT = 2;

private static final int RAND_MIN = 10;


private static final int RAND_MAX = 10;
private static final int RAND_MIN_AMOUNT = 10;
private static final int RAND_MAX_AMOUNT = 200;

private static Bank bank = new Bank(ACCOUNTS_COUNT);


private Client client;

public Main(Client c) {
client = c;
}

private int randAmount() {


return (new Random()).nextInt((RAND_MAX_AMOUNT - RAND_MIN_AMOUNT) +
1)
+ RAND_MIN_AMOUNT;
}

private int randSleepTime() {


return (new Random()).nextInt((RAND_MAX - RAND_MIN) + 1) + RAND_MIN;
}

public static void main(String[] args) {


for (int i = 0; i < CLIENT_COUNT; i++) {
Main ts1 = new Main(new Client("Person " + i));
ts1.start();
}
}

St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 29 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18

private void clientWork() {


try {
Thread.sleep(randSleepTime());
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}

@Override
public void run() {
for (int i = 0; i < CLIENT_ITERATIONS; i++) {
Account acc = bank.getRandomAccount();
clientWork();
acc.withdraw(client, randAmount());
clientWork();
acc.deposit(client, randAmount());
}
System.out.println("#Account balance: " + Account.getBalance());
}
}

16 Code a java program to implement the following:Create four checkboxes.The initial state
b of the first box should be in the checked state.The status of each check box should be
displayed.when we change the state of a check box,status should be display is updated.
import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

private Frame mainFrame;


private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;

public AwtControlDemo(){
prepareGUI();
}

public static void main(String[] args){


AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showCheckBoxDemo();
}

private void prepareGUI(){


mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}

St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 30 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);

controlPanel = new Panel();


controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}

private void showCheckBoxDemo(){

headerLabel.setText("Control in action: CheckBox");

Checkbox chkApple = new Checkbox("Apple");


Checkbox chkMango = new Checkbox("Mango");
Checkbox chkPeer = new Checkbox("Peer");
Checkbox chkgrape= new Checkbox("Grape");

chkApple.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Apple Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});

chkMango.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Mango Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});

chkPeer.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Peer Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
chkgrape.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Grape Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});

St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 31 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
controlPanel.add(chkApple);
controlPanel.add(chkMango);
controlPanel.add(chkPeer);
controlPanel.add(chkgrape);

mainFrame.setVisible(true);
}
}

St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 32 of 32

You might also like