0% found this document useful (0 votes)
17 views

Unit 4 - OOPNotes

Uploaded by

110123104026
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Unit 4 - OOPNotes

Uploaded by

110123104026
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 49

UNIT IV I/O, GENERICS, STRING HANDLING

I/O Basics – Reading and Writing Console I/O – Reading and Writing Files. Generics: Generic Programming – Generic classes – Generic
Methods – Bounded Types – Restrictions and Limitations. Strings: Basic String class, methods and String Buffer Class.

1. I/O BASICS

1. What is InputStream? Present an outline of the methods defined by InputStream.

(NOV/DEC 2021)(13)
2. How character streams are defined?(2) (NOV/DEC 2021)(13)
3. What are the uses of streams. What are the two types of streams ?(NOV/DEC
2020)
4. Explain in detail about reading and writing console in java with sample example program?

Java I/O (Input and Output) is used to process the input and produce the output based on the input. Java uses the concept of stream to
make I/O operation fast. The java.io package contains all the classes required for input and output operations.

1.1 I/O Basics

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.
Byte Streams

Java byte streams are used to perform input and output of 8-bit bytes FileInputStream , FileOutputStream.

Character Streams

Java Character streams are used to perform input and output for 16-bit unicode. FileReader , FileWriter 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 to
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 to
standard error stream and represented as System.err.

Classification of Stream Classes

Byte Stream Classes

ByteStream classes have been designed to provide functional features for creating and manipulating streams and files for reading and
writing bytes. Since the streams are unidirectional, they can transmit bytes in only one direction and therefore, Java provides two kinds of
byte stream classes: InputStream class and OutputStream class.
Input Stream Classes

Input stream classes that are used to read 8-bit bytes include a super class known as InputStream and number of subclasses for supporting
various input- related functions.

1.2 Reading and writing console I/O

Hierarchy of Input Stream Classes

The super class InputStream is an abstract class, so we cannot create object for the class. InputStream class defines the methods to
perform the following functions:-

• Reading Bytes
• Closing Streams
• Marking position in Streams
• Skipping ahead in streams
• Finding the number of bytes in stream.

The following are the InputStream methods:


The DataInput interface contains the following methods

OutputStream Class

The super class InputStream is an abstract class, so we cannot create object for the class. InputStream class defines the methods to
perform the following functions:

• Writing Bytes

• Closing Streams

• Flushing Streams
Hierarchy of Output Stream Classes

OutputStream Method
Character Stream Vs Byte Stream in Java I/O Stream

A stream is a method to sequentially access a file. I/O Stream means an input source or output destination representing different types
of sources e.g. disk files.The java.io package provides classes that allow you to convert between Unicode character streams and byte streams
of non-Unicode text.

Stream: A sequence of data.

Input Stream: reads data from source.

Output Stream: writes data to destination.

Character Stream

In Java, characters are stored using Unicode conventions. Character stream automatically allows us to read/write data character by character.
For example FileReader and FileWriter are character streams used to read from source andwrite to destination.

Java BufferedInputStream Class

Java BufferedInputStream class is used to read information from stream. It internally uses buffer mechanism to make the performance
fast.

The important points about BufferedInputStream are:

1. When the bytes from the stream are skipped or read, the internal buffer automatically refilled from the contained input
stream, many bytes at a time.

2. When a BufferedInputStream is created, an internal buffer array is created. Example of Java BufferedInputStream

import java.io.*; public class BufferedInputStreamExample{ public static

void main(String args[]){

try{

FileInputStream fin=new FileInputStream("D:\\testout.txt"); BufferedInputStream bin=new

BufferedInputStream(fin);

int i;
while((i=bin.read())!=-1){

System.out.print((char)i);

bin.close(); fin.close();

}catch(Exception e){System.out.println(e);}

Java BufferedOutputStream Class

Java BufferedOutputStream class is used for buffering an output stream. It internally uses buffer to store data. It adds more efficiency than to
write data directly into a stream. So, it makes the performance fast.

For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see the syntax for adding the buffer in an OutputStream:

OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\IO Package\\testout.txt"));

Example of Java BufferedOutputStream

In this example, we are writing the textual information in the BufferedOutputStream object which is connected to the FileOutputStream object.
The flush() flushes the data of one stream and send it into another. It is required if you have connected the one stream with another.

import java.io.*; public class BufferedOutputStreamExample{ public static void

main(String args[])throws Exception{

FileOutputStream fout=new FileOutputStream("D:\\testout.txt");

BufferedOutputStream bout=new BufferedOutputStream(fout); String s="Welcome to cse

department"; byte b[]=s.getBytes(); bout.write(b); bout.flush(); bout.close();

fout.close();
System.out.println("success");

Output:

Success

testout.txt

Welcome to cse department

Java DataInputStream Class

Java DataInputStream class allows an application to read primitive data from the input stream in a machineindependent way.

Java application generally uses the data output stream to write data that can later be read by a data input

stream.

Example of DataInputStream class

In this example, we are reading the data from the file testout.txt file. import java.io.*; public class

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

InputStream input = new FileInputStream("D:\\testout.txt"); DataInputStream inst = new

DataInputStream(input); int count = input.available(); byte[] ary = new byte[count];

inst.read(ary); for (byte bt : ary) { char k = (char) bt;

System.out.print(k+"-");

}
Here, we are assuming that you have following data in "testout.txt" file:

JAVA

Output:

J-A-V-A

Success

Java DataOutputStream Class

Java DataOutputStream class allows an application to write primitive Java data types to the output stream in a machine-independent way.

Java application generally uses the data output stream to write data that can later be read by a data input stream.

Java DataOutputStream class methods

Method Description

int size() It is used to return the number of bytes written to the data output
stream.
void write(int b) It is used to write the specified byte to the underlying output stream.

void write(byte[] b, int off, int It is used to write len bytes of data to the output stream.
len)

void writeBoolean(boolean v) It is used to write Boolean to the output stream as a 1-byte value.

void writeChar(int v) It is used to write char to the output stream as a 2-byte value.
void writeChars(String s) It is used to write string to the output stream as a sequence of
characters.

void writeByte(int v) It is used to write a byte to the output stream as a 1-byte value.
void writeBytes(String s) It is used to write string to the output stream as a sequence of bytes.

void writeInt(int v) It is used to write an int to the output stream

void writeShort(int v) It is used to write a short to the output stream.

void writeShort(int v) It is used to write a short to the output stream.

void writeLong(long v) It is used to write a long to the output stream.

void writeUTF(String str) It is used to write a string to the output stream using UTF-8 encoding in
portable manner.
void flush() It is used to flushes the data output stream.

Example of DataOutputStream class

In this example, we are writing the data to a text file testout.txt using DataOutputStream class.

package com.javatpoint;

import java.io.*;
public class OutputExample {
public static void main(String[] args) throws IOException { FileOutputStream file = new
FileOutputStream(D:\\testout.txt);
DataOutputStream data = new DataOutputStream(file); data.writeInt(65);
data.flush(); data.close();
System.out.println("Succcess...");
}
}
Output:

Succcess...

testout.txt:

A
1.3 Reading and Writing Files

1. How to perform reading and writing files ? Explain with example(NOV/DEC 2020)
2. Explain in detail about the following with sample program
i) Reading from file ii) Writing in a file

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.

The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination. The two
important streams are FileInputStream and FileOutputStream Here is a hierarchy of classes to deal with Input and Output streams.

FileInputStream

Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such as
image data, audio, video etc. Java FileInputStream example 1: read single character import java.io.FileInputStream;

public class DataStreamExample { public static void main(String args[]){

try{

FileInputStream fin=new FileInputStream("D:\\testout.txt");

int i=fin.read();

System.out.print((char)i); fin.close();

}catch(Exception e){System.out.println(e);}

Note: Before running the code, a text file named as "testout.txt" is required to be created. In this file, we are having following content:

Welcome to CSE department.


After executing the above program, you will get a single character from the file which is 87 (in byte form). To see the text, you need to convert
it into character.

Output:

Java FileOutputStream Example 1: write byte import java.io.FileOutputStream;

public class FileOutputStreamExample { public static void main(String args[]){

try{

FileOutputStream fout=new FileOutputStream("D:\\testout.txt");

fout.write(65); fout.close();

System.out.println("success...");

}catch(Exception e){System.out.println(e);}

Output:

Success

The content of a text file testout.txt is set with the data A. testout.txt

Write to a File

The next operation which we can perform on a file is "writing into a file". In order to write data into a file, we will use the FileWriter class and
its write() method together. We need to close the stream using the close() method to retrieve the allocated resources.

Let's take an example to understand how we can write data into a file.
WriteToFile.java

// Importing the FileWriter class import java.io.FileWriter;

// Importing the IOException class for handling errors import java.io.IOException;

class WriteToFile { public static void main(String[] args) {

try {

FileWriter fwrite = new FileWriter("D:FileOperationExample.txt"); // writing the content into the

FileOperationExample.txt file fwrite.write("A named location used to store related information is referred to as a File.");

// Closing the stream fwrite.close();

System.out.println("Content is successfully wrote to the file.");

} catch (IOException e) {

System.out.println("Unexpected error occurred");

e.printStackTrace();

Read from a File

The next operation which we can perform on a file is "read from a file". In order to write data into a file, we will use the Scanner class. Here, we
need to close the stream using the close() method. We will create an instance of the Scanner class and use the hasNextLine() method
nextLine() method to get data from the file.

Let's take an example to understand how we can read data from a file.

ReadFromFile.java

// Importing the File class import java.io.File;


// Importing FileNotFoundException class for handling errors import java.io.FileNotFoundException;

// Importing the Scanner class for reading text files import java.util.Scanner; class

ReadFromFile { public static void main(String[] args) {

try {

// Create f1 object of the file to read data

File f1 = new File("D:FileOperationExample.txt"); Scanner dataReader =

new Scanner(f1); while (dataReader.hasNextLine()) {

String fileData = dataReader.nextLine();

System.out.println(fileData);

dataReader.close();

} catch (FileNotFoundException exception) {

System.out.println("Unexcpected error occurred!");

exception.printStackTrace();

}}}

Examples:

1. In the below example, we will use FileInputStream class to read the file.
Code:

import java.io.*; class main{ public static void

main(String[] args) throws IOException { try{


// loading a file into f variable

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

// initializing x to 0

int x = 0;

// while loop untill the end of the file.

while ((x = f.read())!=-1){

// printing the character

System.out.print((char)x);

// closing a file

f.close();

catch(Exception e)

// printing exception

System.out.println(e);

}}

2. In the below example, we will use BufferedInputStream class to read the file.

Code:
import java.io.*; class main{ public static void main(String[] args) throws IOException {

try{

// loading a file into f1 variable using FileInputStream

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

// loading a file into f2 variable using BufferInputStream

BufferedInputStream f2 = new BufferedInputStream(f1);

// using the available method

System.out.println("Available bytes: "+f2.available());

int x = 0;

// while loop untill the end of the file.

while ((x = f2.read())!=-1){ // printing the character

System.out.print((char)x);

System.out.println(); // closing a file

f2.close();

catch(Exception e){

// printing exception

System.out.println(e);

}}}
Output:

Available bytes: 24

Hello I am Soham Medewar

3. In the below example we will use ByteArrayInputStream class to read the file.
Code:

import java.io.*; class main{ public static void main(String[] args) throws IOException { try{

// loading a file into f1 variable using FileInputStream FileInputStream f1 = new

FileInputStream("input.txt");

int x = 0;

String S = "";

// while loop untill the end of the file.

while ((x = f1.read())!=-1){

// printing the character

S = S+(char)x;

// closing a input stream f1.close();

// converting string to array of bytes byte[] b = S.getBytes();

// declaring ByteArrayInputStream

ByteArrayInputStream b1 = new ByteArrayInputStream(b);

x = b1.read(); while(x != -1){


System.out.print((char)x);

x = b1.read();

System.out.println();

// close the input stream

b1.close();

catch(Exception e)

// printing exception

System.out.println(e);

}
}
Output:

Hello I am Soham Medewar

2. GENERICS
1. Why parameterized types are important? Outline Java generics with an example. (NOV/DEC 2021)
2. Outline parameter type bounds with an example. (NOV/DEC 2021)

Generic programming enables the programmer to create classes,interfaces and methods that automatically works with all types of
data(Integer, String, Float etc). It has expanded the ability to reuse the code safely and easily.

Advantage of Java Generics

There are mainly 3 advantages of generics. They are as follows:

1) Type-safety : We can hold only a single type of objects in generics. It doesn’t allow to store other objects.
2) Type casting is not required: There is no need to typecast the object. 3)Compile-Time Checking: It is checked at compile time so
problem will not occur at runtime. The good programming strategy says it is far better to handle the problem at compile time than
runtime.

2.1 Generic class

• A class that can refer to any type is known as generic class.

• Generic class declaration defines set of parameterized type one for each possible invocation of the type parameters

Example:

class TwoGen<T, V>

T ob1; V ob2;
TwoGen(T o1, V o2)

ob1 = o1; ob2 = o2;

void showTypes() {

System.out.println("Type of T is " + ob1.getClass().getName()); System.out.println("Type of V is " + ob2.getClass().getName());

T getob1()

return ob1;

V getob2()

return ob2;

}}

public class MainClass{

public static void main(String args[])

TwoGen<Integer, String> tgObj = new TwoGen<Integer, String>(88,"Generics"); tgObj.showTypes(); int v =

tgObj.getob1(); System.out.println("value: " + v);

String str = tgObj.getob2(); System.out.println("value: " + str);


}

2.2 Generic Method

Like generic class, we can create generic method that can accept any type of argument. public class

TestGenerics4{ public static < E > void printArray(E[] elements)

for ( E element : elements)

System.out.println(element );

System.out.println();

public static void main( String args[] )

Integer[] intArray = { 10, 20, 30, 40, 50 };

Character[] charArray = { 'J', 'A', 'V', 'A'}; System.out.println( "Printing Integer Array" );

printArray( intArray );

System.out.println( "Printing Character Array" ); printArray( charArray );

}
2.3 Bounded type

The type parameters could be replaced by any class type. This is fine for many purposes, but sometimes it is useful to limit the types that
can be passed to a type parameter

Syntax :

<T extends superclass> Example class Stats<T extends

Number>

T[] nums;

Stats(T[] o)

nums = o;

double average()

double sum = 0.0; for(int i=0; i < nums.length; i++) sum +=

nums[i].doubleValue(); return sum / nums.length;

public class MainClass { public static void main(String args[])

Integer inums[] = { 1, 2, 3, 4, 5 };

Stats<Integer> iob = new Stats<Integer>(inums); double v = iob.average();


System.out.println("iob average is " + v);

Double dnums[] = { 1.1, 2.2, 3.3, 4.4, 5.5 };

Stats<Double> dob = new Stats<Double>(dnums); double w = dob.average(); System.out.println("dob

average is " + w);

2.4 Restrictions on Generics

To use Java generics effectively, you must consider the following restrictions

• Cannot Instantiate Generic Types with Primitive Types

• Cannot Create Instances of Type Parameters

• Cannot Declare Static Fields Whose Types are Type Parameters

• Cannot Use Casts or instanceof With Parameterized Types

• Cannot Create Arrays of Parameterized Types

• Cannot Create, Catch, or Throw Objects of Parameterized Types

• Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase to the Same Raw Type

3. STRINGS
1. Compare String & StringBuffer Class. (2) (NOV/DEC 2021)
2. List the methods in String Class. (2) (NOV/DEC 2021)
3. Write a Java program to count the number of vowels in a given sentence. (2) (NOV/DEC 2021)
4. Write a Java program to reverse the given sentence. (2) (NOV/DEC 2021)

3.1 Basic String class


In java, string is basically an object that represents sequence of char values. Java String provides a lot of concepts that can be
performed on a string such as compare, concat, equals, split, length, replace, compareTo, intern, substring etc.
In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
String s="javatpoint";
There are two ways to create String object:
• By string literal
• By new keyword

String Literal - Java String literal is created by using double quotes. For Example: String s="welcome";

By new keyword - String s=new String("Welcome"); Example 1: Create a String in

Java class Main { public static void main(String[] args) {

// create strings

String first = "Java";

String second = "Python";

String third = "JavaScript";

// print strings

System.out.println(first); // print Java

System.out.println(second); // print Python

System.out.println(third); // print JavaScript

Creating strings using the new keyword class Main { public static void

main(String[] args) { // create a string using new

String name = new String("Java String");

System.out.println(name); // print Java String

}
}

3.2 String methods


String methods:
1. char charAt(int index) returns char value for the particular index
2. int length() returns string length
3. static String format(String format, returns formatted string
Object... args)
4. static String format(Locale l, String returns formatted string with given locale
format, Object... args)
5. String substring(int beginIndex) returns substring for given begin index
6. String substring(int beginIndex, int returns substring for given begin index and end
endIndex) Index
7. boolean contains(CharSequence s) returns true or false after matching the sequence of
char value
8. static String join(CharSequence returns a joined string
delimiter, CharSequence... elements)
9. static String join(CharSequence returns a joined string
delimiter, Iterable<? extends
CharSequence> elements)
10. boolean equals(Object another) checks the equality of string with object
11. boolean isEmpty() checks if string is empty
12. String concat(String str) concatinates specified string
13. String replace(char old, char new) replaces all occurrences of specified char value
14. String replace(CharSequence old, replaces all occurrences of specified
CharSequence new) CharSequence
15. static String equalsIgnoreCase(String compares another string. It doesn't check case.
another)
16. String[] split(String regex) returns splitted string matching regex
17. String[] split(String regex, int limit) returns splitted string matching regex and limit
18. String intern() returns interned string
19. int indexOf(int ch) returns specified char value index
20. int indexOf(int ch, int fromIndex) returns specified char value index starting with
given index
21. int indexOf(String substring) returns specified substring index
22. int indexOf(String substring, int returns specified substring index starting with
fromIndex) given index
23. String toLowerCase() returns string in lowercase.
24. String toLowerCase(Locale l) returns string in lowercase using specified locale.
25. String toUpperCase() returns string in uppercase.
26. String toUpperCase(Locale l) returns string in uppercase using specified locale.

27. String trim() removes beginning and ending spaces of this string.

28. static String valueOf(int value) converts given type into string. It is overloaded.

Example

public classstringmethod
{
public static void main(String[] args)
{
String string1 = new String("hello"); String string2 = new
String("hello"); if (string1 == string2)
{
System.out.println("string1= "+string1+" string2= "+string2+" are equal");

} else
{
System.out.println("string1= "+string1+" string2= "+string2+" are Unequal");
}
System.out.println("string1 and string2 is= "+string1.equals(string2));
String a="information";
System.out.println("Uppercase of String a is= "+a.toUpperCase()); String b="technology";
System.out.println("Concatenation of object a and b is= "+a.concat(b)); System.out.println("After concatenation Object a is=
"+a.toString()); System.out.println("\"RIT\'s\" is the greatest\\ college in chennai"); System.out.println("Length of Object a is=
"+a.length());
System.out.println("The third character of Object a is= "+a.charAt(2));
StringBuffer n=new StringBuffer("Technology");
StringBuffer m=new StringBuffer("Information");
System.out.println("Reverse of Object n is= "+n.reverse()); n= new
StringBuffer("Technology");
System.out.println("Concatenation of Object m and n is= "+m.append(n)); System.out.println("After concatenation of Object m is=
"+m);
}
}

Output

string1= hello string2= hello are Unequal string1 and string2 is= true
Uppercase of String a is= INFORMATION
Concatenation of object a and b is= informationtechnology
After concatenation Object a is= information
"Joseph's" is the greatest\ college in chennai
Length of Object a is= 11
The third character of Object a is= f
Reverse of Object n is= ygolonhceT
Concatenation of Object m and n is= InformationTechnology

3.3 String Buffer Class

Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer class in Java is the same as String
class except it is mutable i.e. it can be changed.

Important methods of StringBuffer class

Mutable String:
A String that can be modified or changed is known as mutable String. StringBuffer and StringBuilder classes are used for
creating mutable strings.

StringBuffer Class append() Method

The append() method concatenates the given argument with this String.
Program

Class StringBufferExample

public static void main(String args[])

StringBuffer sb=new StringBuffer("Hello "); sb.append("Compiler");//now original string is

changed System.out.println(sb);//prints Hello Java

Output:

Hello Compiler

StringBuffer insert() Method:

The insert() method inserts the given String with this string at the given position. Program:

class StringBufferExample2
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello "); sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}

Output:

HJavaello
StringBuffer replace() Method

The replace() method replaces the given String from the specified beginIndex and endIndex.

StringBufferExample3.java class StringBufferExample3{ public static

void main(String args[]){ StringBuffer sb=new StringBuffer("Hello");

sb.replace(1,3,"Java");

System.out.println(sb);//prints HJavalo

OUTPUT:

HJavalo

StringBuffer delete() Method

The delete() method of the StringBuffer class deletes the String from the specified beginIndex to endIndex. StringBufferExample4.java

class StringBufferExample4{ public static void main(String args[]){ StringBuffer sb=new StringBuffer("Hello"); sb.delete(1,3);

System.out.println(sb);//prints Hlo

OUTPUT

Hlo
StringBuffer reverse() Method

The reverse() method of the StringBuilder class reverses the current String. StringBufferExample5.java

class StringBufferExample5{ public static void main(String args[]){

StringBuffer sb=new StringBuffer("Hello"); sb.reverse();

System.out.println(sb);//prints olleH

} }

OUTPUT

OlleH

StringBuffer capacity() Method

The capacity() method of the StringBuffer class returns the current capacity of the buffer. The default capacity of the buffer is 16. If the
number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current
capacity is 16, it will be (16*2)+2=34. StringBufferExample6.java class StringBufferExample6{ public static void main(String args[]){

StringBuffer sb=new StringBuffer();

System.out.println(sb.capacity());//default 16 sb.append("Hello");

System.out.println(sb.capacity());//now 16 sb.append("java is my favourite language");

System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2

} }

OUTPUT

16

16 34
StringBuffer ensureCapacity() method

The ensureCapacity() method of the StringBuffer class ensures that the given capacity is the minimum to the current capacity. If it is greater
than the current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
StringBufferExample7.java class StringBufferExample7{

public static void main(String args[]){

StringBuffer sb=new StringBuffer();

System.out.println(sb.capacity());//default 16 sb.append("Hello");

System.out.println(sb.capacity());//now 16 sb.append("java is my favourite language");

System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2 sb.ensureCapacity(10);//now

no change System.out.println(sb.capacity());//now 34 sb.ensureCapacity(50);//now (34*2)+2

System.out.println(sb.capacity());//now 70

} }

Output:

16

16

34

34

70

Barcode Reading using Java

1. What is Barcode
2. Java API to Read Barcode from Image
3. Read Barcode from an Image
4. Recognize Barcode of Specific Type
5. Read Multiple Barcodes from an Image
6. Get X and Y Coordinates of Barcode
7. Read Barcode From Specific Region of Image

// This code example demonstrates how to read barcode from an image.


// The path to the image directory
String dataDir = "C:\\Files\\BarCode\\";
// Initialize barcode reader
BarCodeReader reader = new BarCodeReader(dataDir + "CodeText.jpg");
// Read barcode and show results
for (BarCodeResult result : reader.readBarCodes()) {
System.out.println("CodeText: " + result.getCodeText());
System.out.println("Symbology type: " + result.getCodeType());
}

// This code example demonstrates how to read barcode multiple barcodes from an image. // The path to the image directory
String dataDir = "C:\\Files\\BarCode\\";

// Initialize barcode reader


BarCodeReader reader = new BarCodeReader(dataDir + "MultipleBarcodes.png",
DecodeType.ALL_SUPPORTED_TYPES);

// Read all types of barcode available on the input image for (BarCodeResult result :
reader.readBarCodes()) {
System.out.println("CodeText: " + result.getCodeText());
System.out.println("Symbology type: " + result.getCodeType());
System.out.println("-------------------------"); }

// This code example demonstrates how to read barcode of a specific decode type from an image.
// The path to the image directory
String dataDir = "C:\\Files\\BarCode\\";

// Get buffured image


BufferedImage img = ImageIO.read(new File(dataDir + "CODE_39_STANDARD.jpg"));

// Initialize barcode reader


BarCodeReader reader = new BarCodeReader(img, DecodeType.CODE_39_STANDARD);

// Read barcode of type Code39Extended


for (BarCodeResult result : reader.readBarCodes()) {
System.out.println("CodeText: " + result.getCodeText());
System.out.println("Symbology type: " + result.getCodeType());
}

// This code example demonstrates how to read barcode from specific region of an image. // The path to the image directory
String dataDir = "C:\\Files\\BarCode\\";

// Get BufferedImage java.awt.image.BufferedImage img = javax.imageio.ImageIO.read(new java.io.File(dataDir +


"specificRegion.png"));

// Create an instance of BarCodeReader class // and specify an area to look for


the barcode
BarCodeReader reader = new BarCodeReader(img, new Rectangle(0, 0, 700, 100),
DecodeType.ALL_SUPPORTED_TYPES);

// Read all barcodes in the provided area


for (BarCodeResult result : reader.readBarCodes()) {
System.out.println("CodeText: " + result.getCodeText());
System.out.println("Symbology type: " + result.getCodeType()); }

// This code example demonstrates how to read X & Y region point of barcodes from an image.
// The path to the image directory
String dataDir = "C:\\Files\\BarCode\\";
// Initialize barcode reader
BarCodeReader reader = new BarCodeReader(dataDir + "Code39Std.png", DecodeType.ALL_SUPPORTED_TYPES);

// Read barcode for (BarCodeResult result : reader.readBarCodes()) {


if (result.getRegion() != null) {
// Display x and y coordinates of all the barcodes detected
Point[] point = result.getRegion().getPoints();
System.out.println("Top left coordinates: X = " + point[0].x + ", Y = " + point[0].y);
System.out.println("Bottom left coordinates: X = " + point[1].x + ", Y = " + point[1].y);
System.out.println("Bottom right coordinates: X = " + point[2].x + ", Y = " + point[2].y);
System.out.println("Top right coordinates: X = " + point[3].x + ", Y = " + point[3].y);
}
}

OOP - Assignment - Unit-4

Category - Easy
Create a C# program to record a video using Camera.

Category - Medium
Create a Java Program to read data through a barcode scanner.

Category - Hard
Implement Library Management System using the concepts learnt in Unit-4 (or)
Implement Railway Reservation System using the concepts learnt in Unit-4
DEPARTMENT OF COMPUTER SCIENCE &
ENGINEERING
MODEL EXAMINATION Branch : CSE
Sub Code : CS3391 Year/Sem: II/III
Sub Name : Object Oriented Programming

Part A (2 Marks)
Sl.no Questions Blooms
CO Level*
1 Write a Java program to reverse the given sentence. CO4 B3

2 Write a Java program to count the number of vowels in a CO4 B3


given sentence.

3 Write a program to read multiple Integer values from a CO4 B3


single line of input in Java.

Point out the syntax of buffered reader to connect to the CO4 B1


keyboard
4
5 Illustrate any four character stream class.. CO4 B3

Define Generic Class CO4 B1


6
Create a simple generic class with examples. CO4 B6
7
Show how virtual machines are used in generic CO4 B3
programming.
8
Sl.no CO Blooms Level*
Questions (Only
B5 & B6)
1 Develop a java program to Convert a given String CO4 B6
into a Palindrome.

2 Develop a Java Program to copy the contents of one CO4 B6


file to other file.
Part B (13 Marks)
Sl.no CO Blooms
Questions Level*

1 Illustrate String handling class in Java with example. CO4 B3

2 Compute String Palindrome using three different logics. CO4 B4

3 Write a Java Program to compute the perfect numbers up CO4 B3


to N in a file named as “perfect.txt”
4 Illustrate in detail about CO4 B4
i) Reading from a file
ii) Writing in a file
5 Write a Generic Java program to sort any five
Integers/float/double/character elements CO4 B3
Write a java program to implement bounded types (extend
superclass) with generics.
6 CO4 B3
Develop a simple Generic class example with two type
parameter U & V separated by “,”.
7 CO4 B3

Part C (15 Marks)


Java - Generics - MCQ

1. Which of these data type cannot be type parameterized?


A. Array
B. List
C. Map
D. Set

2. Which of the following reference types cannot be generic?


A. Anonymous inner class
B. Interface
C. Inner class
D. All of the mentioned

3. Which of the following allows us to call generic methods as a normal method?


A. Type Interface
B. Interface
C. Inner class
D. All of the mentioned

4. What are the common type parameters?


A. T - Type
B. E - Element
C. K - Key
D. All of these

5. Why are generics used?


A. Generics make the code faster
B. Generics make the code more optimized and readable
C. Generics add stability to your code by making more of your bugs detectable at
compiletime
D. Generics add stability to your code by making more of your bugs detectable at
theruntime

6. Which of these Exception handlers cannot be type parameterized?


A. Catch
B. Throw
C. Throws
D. All of the mentioned
7. What is Type Erasure?
A. Replace generic types with objects
B. Replace bounded types (More on these in a later question) with the first bound class
C. Insert the equivalent of casts when retrieving generic objects
D. All of the above
8. Why should we use Generics?
A. The Java compiler enforces tighter type checks on generic code at compile time
B. Generics support programming types as parameters
C. Generics enable you to implement generic algorithms
D. All of these

9. Which of these types cannot be used to initiate a generic type?


A. Integer class
B. Float class
C. Primitive Types
D. Collections

10. Which of these types cannot be used to initiate a generic type?


A. Integer class
B. Float class
C. Primitive Types
D. Collections

11. Which of the following are the benefits of Java generics?


A. Type-safety
B. Typecasting is not required
C. Compile-Time Checking
D. All of these

12. Why are generics used?


A. Generics make code faster
B. Generics make code more optimized and readable
C. Generics add stability to your code by making more of your bugs detectable at
compiletime
D. Generics add stability to your code by making more of your bugs detectable at a runtime

13. Which of these types cannot be used to initiate a generic type?


A. Integer class
B. Float class
C. Primitive Types
D. Collections

14. Which of the following reference types cannot be generic?


A. Anonymous inner class
B. Interface
C. Inner class
D. All of the mentioned

15. Generics does not work with?


A. Set
B. List
C. Tree
D. Array

16. Which of the following allows us to call generic methods as a normal method?
A. Type Interface
B. Interface
C. Inner class
D. All of the mentioned

17. Which of these instances cannot be created?


A. Integer Instance
B. Generic Class Instance
C. Generic Type Instance
D. Collection Instances

18. Which of these is a correct way of defining of a generic method?


A. name(T1, T2, "¦, Tn) { /* "¦ */ }
B. public name { /* "¦ */ }
C. class name[T1, T2, "¦, Tn] { /* "¦ */ }
D. name{T1, T2, "¦, Tn} { /* "¦ */ }

19. Which of these types cannot be used to initiate a generic type?


A. Integer class
B. Float Class
C. Primitive Types
D. Collections

20. What is the default value of byte variable?


A. 0
B. 0.5
C. null
D. undefined

21. Which of the following reference types cannot be generic?


A. Anonymous inner class
B. Interface
C. Inner class
D. D. All of the mentioned

22. Which of these type parameters is used for a generic class to return and accept a
number?
A. K
B. N
C. T
D. V

23. Which of the following is incorrect statement regarding the use of generics and
parameterized types in Java?
A. Generics provide type safety by shifting more type checking responsibilities to
thecompiler
B. Generics and parameterized types eliminate the need for down casts when using
JavaCollections
C. When designing your own collections class (say, a linked list), generics
andparameterized types allow you to achieve type safety with just a single class
definition as opposed to defining multiple classes
D. All of the mentioned

24. Which of the following allows us to call generic methods as a normal method?
A. Type Interface
B. Interface
C. Inner class
D. All of the mentioned

25. Why are generics used?


A. Generics make code more fast
B. Generics make code more optimised and readable
C. Generics add stability to your code by making more of your bugs detectable at
compiletime
D. Generics add stability to your code by making more of your bugs detectable at a runtime

26. Which of the following statements is incorrect about the use of generic and
parameterized types in Java?
A. When designing your own class of collections, generic and parameterized types
allowyou to achieve type security with a single class definition rather than defining
multiple classes
B. Generic and parameterized types removes the need for top-down conversions
whenusing Java collections
C. Generic type in Java ensures type safety by transferring type checking responsibilities
tothe compiler
D. All the answers are true
NAME :

CLASS :
JAVA string
DATE :
20 Questions

1. Is String a primitive data type?

A Both B No

C Yes

2. Which method to use to find length of a string?

A length() B long()

C size() D count()
3. Which data type gets returned from length() method in String class?

A int B number

C String D double
4. String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

What is the correct way to find the length of "txt" string?

A float len = txt.length(); B double len = length(txt);

C int len = length(txt); D int len = txt.length();


5. Which is correct method to convert String into uppercase

A toUpperCase() B changeUpperCase()

C toUpper() D convertUpperCase()
6. String txt = "Hello World";
System.out.println(txt.toUpperCase()); Choose the

correct output.

A HELLO WORLD B Hello World C "HELLO WORLD" D Hello world

7. Choose correct purpose of indexOf() in String class.

returns the character of the first


A returns the index (the position) of the last B occurrence of a specified character in a string
occurrence of a specified text in a string

returns the index (the position) of the first returns the index (the position) of the first
C occurrence of a specified text in a string D occurrence of a specified text in a string
(excluding whitespace) (including whitespace)
8.
String x = "10";
String y = "20";
String z = x + y;
System.out.println(z); Guess
the output.

A 10 20 B 1020

C 30 D "10 20"

9.
What will be the output of below code?

String statement = "Outfit of the day";


System.out.println(statement.Substring(3,6));

A tfit B it of

C FIT D fit
10. Choose most appropriate purpose of trim() method in String?

A to cut String at desired index B to get a substring of the string


to remove extra white spaces from start
D
C to remove white spaces and end of String
11. What is the return type of equalsIgnorecase() method?

A int B String

C char D boolean
12. What is the most appropriate way to check if two Strings are identical?

A string1 == string2 B string1.equalsIgnorecase(string2)

C string1.same(string2) D string1.equals(string2)
13. (Multiple answer question)
Pick all NON-primitive datatypes from below :

A String B int

C primitive D Array
14. What is the correct relation between length and last-index of array?

A last-index is always 1 more than the length B last-index is always 1 less than the length
last-index is 1 less than the length (but not
C last-index is always equal to the length D
always)

15.
String word = "A few good men"; What is
word.length()?

A 13 B 15

C 14

16.
String word = "A few good men"; What is
word.charAt(7) ?

A good men B 7

C g D o

17.
String word = "A few good men";
What is word.startsWith("A few") ?

A false B true
18. String word = "A few good men"; What is
word.endsWith("man") ?

A true B false

19.
String word = "A few good men"; What is
word.indexOf(“f”)?

A 0 B 1

C 3 D 2

20.
String word = "A few good men"; What is
word.substring(3, 7) ?

A few B few[space]

C ew go D ew g
NAME :

CLASS :
Java I/O Streams
DATE :
30 Questions

1. Which of these is a type of stream in Java?

A Byte stream B Long stream

C Short stream D Integer stream


2. Which of these is used to read a string from the input stream?

A getLine() B read()

C get() D readLine()
3. Which of these class is used to read characters and strings in Java from console?

A StringReader B InputStreamReader

C BufferedStreamReader D BufferedReader
4. Which of these class contains the methods print() & println()?

A System B System.out

C BufferedOutputStream D PrintStream
5. ……………………. class is used to increase the efficiency of input operations.

A FileInputStream B DataInputStream

C BufferedInputStream D PipeInputStream
6. A stream is a sequence of data.In Java a stream is composed of?

A Bytes B Both A & B

C None of the above D Bits


7. These commonly used methods of

1) public abstract int read()throws IOException


2) public int available()throws IOException
3) public void close()throws IOException

A InputStream class B Input/OutputStream class C OutputStream

class D None of the above

8. Which of the following is FALSE about Java Streams ?


Byte stream uses InputStream and
Java defines only two types of streams –
A OutputStream classes for input and B
Byte stream and character stream.
output operation.

Character stream uses InputStream and Like in any other language, streams are
C D OutputStream classes for input and used for input and output operations. output
operation.

9. Which of these classes are used by character streams for input and output operations?

A InputStream B Writer C Reader D

InputOutputStream

10. How to represent end of file in java?

A null B EOF

C -1 D \0

11. Which is used to converts the byte-oriented stream into character-oriented stream?

A InputStreamReader B Console

C Scanner D DataInputStream
12. The PrintStream class provides methods to?

A Write data to another stream B read data to another stream

C write data to same stream D read data to same stream


13. The stream tokenizer class can recognize identifiers, numbers, quoted strings, and various comment
styles?

A True B False

14. Which of the following is/are False ?

Both InputStream and OutputStream class is


The PipedInputStream and
an abstract class. It is the superclass of all
A PipedOutputStream classes can be used to B
classes representing an output stream of
read and write data simultaneously?
bytes.

Java application uses an output stream to read


Breaking a string or stream into meaningful data from a source, it may be a file, an array,
C independent words is known as tokenization. D peripheral device or socket.
15. Which of these packages contain classes and interfaces used for input & output operations of a
program?

A all of the mentioned B java.lang

C java.util D java.io
16. Which of these class is not related to input and output stream in terms of functioning?

A File B InputStream

C Reader D Writer
17. Which of these class is used to read and write bytes in a file?

A FileReader B FileInputStream

C FileWriter D InputStreamReader
18. Which of these method of InputStream is used to read integer representation of next available byte
input?

A get() B scanf()

C read() D getInteger()
19. What is the output of this program?

import java.io.*; public class


filesinputoutput
{ public static void main(String[] args)
{
String obj = "abc"; byte b[]
= obj.getBytes();
ByteArrayInputStream obj1 = new ByteArrayInputStream(b); for (int i
= 0; i < 2; ++ i)
{ int c; while ((c =
obj1.read()) != -1)
{ if(i ==
0)
{
System.out.print((char)c);
}
}
}
}
}

A abc B ABC

C AB D ab
20. What is the output of this program?

import java.io.*; public class


filesinputoutput
{
public static void main(String[] args)
{
String obj = "abc"; byte b[]
= obj.getBytes();
ByteArrayInputStream obj1 = new ByteArrayInputStream(b); for (int i
= 0; i < 2; ++ i)
{ int
c;
while ((c = obj1.read()) != -1)
{ if (i ==
0)
{
System.out.print(Character.toUpperCase((char)c));
}
}
}
}
}

A AB B abc

C ABC D ab

21. Which of these class is used to read characters in a file?

A FileInputStream B InputStreamReader

C FileWriter D FileReader
22. Which of these method of FileReader class is used to read characters from a file?

A read() B scanf()

C get() D getInteger()
23. Which of these is a process of writing the state of an object to a byte stream?

A Externalization B File Filtering

C All of the mentioned D Serialization


24. Which of these is an interface for control over serialization and deserialization?

A Serializable B FileFilter

C Externalization D ObjectInput
25. Which of these is method of ObjectOutputStream class used to write the object to output stream as
required?

A Write() B StreamWrite()

C writeObject() D write()
26. Which of these is method of ObjectIntputStream class used to read the object from input stream as
required?

A StreamRead() B readObject()

C Read() D read()

27. How an object can become serializable?

A No object is serializable B Any object is serializable

If a class or any superclass implements If a class implements java.io.Serializable

C D

java.io.Serializable interface class

28. What is serialization?

Turning object in memory into stream of Turning stream of bytes into an object in

A B

bits memory

Turning stream of bits into an object in Turning object in memory into stream of

C D

memory bytes

29. What is deserialization?

Turning object in memory into stream of


A
bits

C Turning object in memory into stream of bytes D Turning stream of bytes into an object in
memory

30. What type of members are not serialized?

A public B private

C transient D protected
Turning stream of bits into an object in
B memory
String - Practice Programs

Parenthesis problem:-

1.https://leetcode.com/problems/generate-parentheses
2.https://leetcode.com/problems/score-of-parentheses
3.https://leetcode.com/problems/valid-parentheses
4.https://leetcode.com/problems/valid-parentheses
5.https://leetcode.com/problems/remove-outermost-parentheses
6.https://leetcode.com/problems/different-ways-to-add-parentheses/
7.https://leetcode.com/problems/remove-invalid-parentheses
8.https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses
9.https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses
10.https://leetcode.com/problems/longest-valid-parentheses/

Counting of substring based on some condition:-

1.https://leetcode.com/problems/number-of-wonderful-substrings
2.https://leetcode.com/problems/sum-of-beauty-of-all-substrings/
3.https://leetcode.com/problems/maximum-number-of-occurrences-of-a-substring
4.https://leetcode.com/problems/number-of-wonderful-substrings

Check types of string:-

1.https://leetcode.com/problems/isomorphic-strings
2.https://leetcode.com/problems/valid-anagram
3. https://leetcode.com/problems/additive-number
4.https://leetcode.com/problems/buddy-strings
5.https://leetcode.com/problems/longest-happy-prefix
6.https://leetcode.com/problems/increasing-decreasing-string
7.https://leetcode.com/problems/check-if-a-string-can-break-another-string
8.https://leetcode.com/problems/determine-if-two-strings-are-close
9.https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent
10.https://leetcode.com/problems/check-if-word-equals-summation-of-two-words
11.https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal

Palindromic string:-
1.https://leetcode.com/problems/palindrome-partitioning
2.https://leetcode.com/problems/palindrome-partitioning-ii
3.https://leetcode.com/problems/valid-palindrome
4.https://leetcode.com/problems/shortest-palindrome
5.https://leetcode.com/problems/palindrome-pairs
6.https://leetcode.com/problems/longest-palindrome
7.https://leetcode.com/problems/longest-palindromic-subsequence
8.https://leetcode.com/problems/find-the-closest-palindrome
9.https://leetcode.com/problems/palindromic-substrings
10.https://leetcode.com/problems/valid-palindrome-ii
11.https://leetcode.com/problems/longest-chunked-palindrome-decomposition
12.https://leetcode.com/problems/break-a-palindrome
13. https://leetcode.com/problems/can-make-palindrome-from-substring
14.https://leetcode.com/problems/palindrome-partitioning-iii
15.https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-
palindrom e
16.https://leetcode.com/problems/remove-palindromic-subsequences
16.https://leetcode.com/problems/construct-k-palindrome-strings
17.https://leetcode.com/problems/split-two-strings-to-make-palindrome

Sorting on String:-
1.https://leetcode.com/problems/sort-characters-by-frequency
2.https://leetcode.com/problems/custom-sort-string

Longest and shortest kind of String Problem :-

1.https://leetcode.com/problems/longest-duplicate-substring
2.https://leetcode.com/problems/longest-string-chain
3.https://leetcode.com/problems/longest-common-subsequence
4.https://leetcode.com/problems/longest-happy-string
5.https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-
uniquecharacters
6.https://leetcode.com/problems/find-longest-awesome-substring
7.https://leetcode.com/problems/largest-substring-between-two-equal-characters
8.https://leetcode.com/problems/largest-odd-number-in-string

You might also like