Professional Documents
Culture Documents
Polymorphism Inheritance Encapsulation Abstraction Class Object Method
Polymorphism Inheritance Encapsulation Abstraction Class Object Method
Polymorphism Inheritance Encapsulation Abstraction Class Object Method
1. Polymorphism
2. Inheritance
3. Encapsulation
4. Abstraction
5. Class
6. Object
7. Method
6. What is an array? Explain in detail about array types in java with an example
program.
Array
1. An array is a collection of variables of homogeneous type that occupy
contiguous memory locations.
2. Arrays of any type can be created and may have one or more dimensions.
3. A specific element in an array is accessed by its index.
4. Arrays offer a convenient means of grouping related information. In Java all
arrays are dynamically allocated
Types of Arrays
1. One Dimensional
2. Two Dimensional
Module 2
1. Compare and contrast method overloading and overriding in java
Method Overloading:
Method Overloading is a Compile time polymorphism. In method overloading,
more than one method shares the same method name with different signature in
the class. In method overloading, return type can or can not be be same, but we
must have to change the parameter because in java, we can not achieve the
method overloading by changing only the return type of the method.
Method Overriding:
Method Overriding is a Run time polymorphism. In method overriding, derived
class provides the specific implementation of the method that is already provided
by the base class or parent class. In method overriding, return type must be
same or co-variant (return type may vary in same direction as the derived class).
Output :
2. Discuss the role of abstract class in java. Explain in detail with an example
program
3. Justify your answer, why java does not support Multiple Inheritance through
classes?
From the code, we see that: On calling the method fun() using Test object will
cause complications such as whether to call Parent1’s fun() or Child’s fun()
method.
Therefore, in order to avoid such complications Java does not support multiple
inheritance of classes.
Syntax
Following is the syntax of a constructor −
class ClassName {
ClassName() {
}
}
Example
Public class MyClass {
Int num;
MyClass() {
num = 100;
}
}
Parameterized Constructors
Most often, you will need a constructor that accepts one or more parameters.
Parameters are added to a constructor in the same way that they are added to a
method, just declare them inside the parentheses after the constructor's name.
Example
Here is a simple example that uses a constructor −
// A simple constructor.
class MyClass {
int x;
First Statement is used to import Vector class from util package which is
contained inside java.
Second statement imports all the classes from util package.
Built-in Packages
These packages consist of a large number of classes which are a part of Java
API.Some of the commonly used built-in packages are:
1) java.lang:
2) java.io:
3) java.util:
4) java.applet:
5) java.awt:
6) java.net:
User-defined packages
These are the packages that are defined by the user. First we create a directory
myPackage (name should be same as the name of the package). Then create
the MyClass inside the directory with the first statement being the package
names.
2. Develop a java program to implement multiple inheritance.
interface Backend {
// abstract class
public void connectServer();
}
class Frontend {
java.connectServer();
Output
Java can be used as backend language.
Java can also be used as frontend.
3. Develop a java program for interface to find areas of different shapes.
Output :
Area of Rectangle is 200
Area of Circle is 706.85
4. Compare and contrast String and StringBuffer in java Programming Language
String String Buffer
It is an immutable class and its object It is a mutable classes which can be
can’t be modified after it is created used to do operation on string object
Methods are not synchronized All methods are synchronized in this
class.
It is fast Multiple thread can’t access at the
same time therefore it is slow
If a String is created using constructor Heap Space
or method then those strings will be
stored in Heap Memory as well as
SringConstantPool
5. What is String in java? Explain different methods in String Class with an
example Program.
Strings are used for storing text.
A String variable contains a collection of characters surrounded by double
quotes:
In Java, a string is a sequence of characters. For example, "hello" is a string
containing a sequence of characters 'h', 'e', 'l', 'l', and 'o'.
We use double quotes to represent a string in Java
length() method
The length() method returns the length of a specified string.
Example
Return the number of characters in a string:
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println(txt.length());
Output : 26
charAt() method
The charAt() method returns the character at the specified index in a string.
Example
Return the first character (0) of a string:
String myStr = "Hello";
char result = myStr.charAt(0);
System.out.println(result);
Output : H
trim() method
The trim() method removes whitespace from both ends of a string.
Example
String myStr = " Hello World! ";
System.out.println(myStr);
System.out.println(myStr.trim());
Output :
Hello World!
Hello World!
indexOf() method
The indexOf() method returns the position of the first occurrence of specified
character(s) in a string.
Example
String myStr = "Hello planet earth, you are a great planet.";
System.out.println(myStr.indexOf("planet"));
Output : 6
replace() method
The replace() method searches a string for a specified character, and returns a
new string where the specified character(s) are replaced.
Example
String myStr = "Hello";
System.out.println(myStr.replace('l', 'p'));
Output : Heppo
delete()
The java.lang.StringBuffer.delete() method removes the characters in a
substring of this sequence. The substring begins at the specified start and
extends to the character at index end - 1 or to the end of the sequence if no such
character exists. If start is equal to end, no changes are made.
package com.tutorialspoint;
Example
import java.lang.*;
public class StringBufferDemo {
public static void main(String[] args) {
StringBuffer buff = new StringBuffer("Java lang package");
System.out.println("buffer = " + buff);
// deleting characters from index 4 to index 9
buff.delete(4, 9);
System.out.println("After deletion = " + buff);
}
}
Let us compile and run the above program, this will produce the following result −
buffer = Java lang package
After deletion = Java package
deletecharat()
The java.lang.StringBuffer.deleteCharAt() method removes the char at the
specified position in this sequence. This sequence is shortened by one char.
Example
package com.tutorialspoint;
import java.lang.*;
public class StringBufferDemo {
public static void main(String[] args) {
StringBuffer buff = new StringBuffer("Java lang package");
System.out.println("buffer = " + buff);
// deleting character from index 4 to index 9
buff.delete(4, 9);
System.out.println("After deletion = " + buff);
buff = new StringBuffer("amit");
System.out.println("buffer = " + buff);
// deleting character at index 2
buff.deleteCharAt(2);
System.out.println("After deletion = " + buff);
}
}
Let us compile and run the above program, this will produce the following result −
buffer = Java lang package
After deletion = Java package
buffer = amit
After deletion = amt
append()
This method updates the value of the object that invoked the method. The
method takes boolean, char, int, long, Strings, etc.
Example
public class Test {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Test");
sb.append(" String Buffer");
System.out.println(sb);
}
}
charat()
The java.lang.StringBuffer.charAt() method returns the char value in this
sequence at the specified index. The first char value is at index 0, the next at
index 1, and so on, as in array indexing.
Example
package com.tutorialspoint;
import java.lang.*;
public class StringBufferDemo {
public static void main(String[] args) {
StringBuffer buff = new StringBuffer("Tutorials Point");
System.out.println("buffer = " + buff);
// returns the char at index 4
System.out.println("character = " + buff.charAt(4));
buff = new StringBuffer("amrood admin ");
System.out.println("buffer = " + buff);
// returns the char at index 6, whitespace gets printed here
System.out.println("character = " + buff.charAt(6));
}
}
Let us compile and run the above program, this will produce the following result −
buffer = Tutorials Point
character = r
buffer = amrood admin
character =
Module 4
1. With an example program illustrate user defined exception handling
Throw
The throw keyword in Java is used to explicitly throw an exception from a method
or any block of code. We can throw either checked or unchecked exception. The
throw keyword is mainly used to throw custom exceptions.
Syntax:
throw Instance
Example:
throw new ArithmeticException("/ by zero");
Example
// Java program that demonstrates the use of throw
class Test
{
public static void main(String[] args)
{
System.out.println(1/0);
}
}
Example
// Java program to illustrate error in case
// of unhandled exception
class tst
{
public static void main(String[] args)
{
Thread.sleep(10000);
System.out.println("Hello Geeks");
}
}
Java Threads
Threads allows a program to operate more efficiently by doing multiple things at
the same time.
Threads can be used to perform complicated tasks in the background without
interrupting the main program.
A thread is a:
• Facility to allow multiple activities within a single process
• Referred as lightweight process
• A thread is a series of executed statements
• Each thread has its own program counter, stack and local variables
• A thread is a nested sequence of method calls
• Its shares memory, files and per-process state
Creating a Thread
There are two ways to create a thread.
It can be created by extending the Thread class and overriding its run() method:
Extend Syntax
public class Main extends Thread {
public void run() {
System.out.println("This code is running in a thread");
}
}
Implement Syntax
public class Main implements Runnable {
public void run() {
System.out.println("This code is running in a thread");
}
}
Running Threads
If the class extends the Thread class, the thread can be run by creating an
instance of the class and call its start() method:
Extend Example
public class Main extends Thread {
public static void main(String[] args) {
Main thread = new Main();
thread.start();
System.out.println("This code is outside of the thread");
}
public void run() {
System.out.println("This code is running in a thread");
}
}
Output
This code is outside of the thread
This code is running in a thread
If the class implements the Runnable interface, the thread can be run by passing
an instance of the class to a Thread object's constructor and then calling the
thread's start() method:
Implement Example
public class Main implements Runnable {
public static void main(String[] args) {
Main obj = new Main();
Thread thread = new Thread(obj);
thread.start();
System.out.println("This code is outside of the thread");
}
public void run() {
System.out.println("This code is running in a thread");
}
}
Output
This code is outside of the thread
This code is running in a thread
Differences between "extending" and "implementing" Threads
The major difference is that when a class extends the Thread class, you cannot
extend any other class, but by implementing the Runnable interface, it is possible
to extend from another class as well, like: class MyClass extends OtherClass
implements Runnable.
4. What is Daemon Thread? Demonstrate Daemon thread with an example
Daemon thread is a low priority thread (in context of JVM) that runs in
background to perform tasks such as garbage collection (gc) etc., they do not
prevent the JVM from exiting (even if the daemon thread itself is running) when
all the user threads (non-daemon threads) finish their execution. JVM terminates
itself when all user threads (non-daemon threads) finish their execution, JVM
does not care whether Daemon thread is running or not, if JVM finds running
daemon thread (upon completion of user threads), it terminates the thread and
after that shutdown itself.
Output:
Daemon thread executing
user(normal) thread executing
Example 2: DaemonThreadEx2.java
If you call the setDaemon() method after starting the thread (start() method), it
would throw IllegalThreadStateException. This clearly means that you can call
setDaemon() method only before starting a thread.
public class DaemonThreadEx2 extends Thread {
public void run(){
System.out.println("Thread is running");
}
public static void main(String[] args){
DaemonThreadEx2 t1=new DaemonThreadEx2();
t1.start();
// It will throw IllegalThreadStateException
t1.setDaemon(true);
}
}
Output:
Exception in thread "main" Thread is running
java.lang.IllegalThreadStateException
at java.lang.Thread.setDaemon(Unknown Source)
at beginnersbook.com.DaemonThreadEx2.main(DaemonThreadEx2.java:13)
Output
Starting Thread - 1
Starting Thread - 2
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 1 exiting.
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.
Syntax
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
If an error occurs, we can use try...catch to catch the error and execute some
code to handle it:
Example
public class Main {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}
Finally
The finally statement lets you execute code, after try...catch, regardless of the
result:
Example
public class Main {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
}
}
}
Example
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or
older, print "Access granted":
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18
years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...)
}
}
Example
checkAge(20);
2. Demonstrate to read data (BufferReader) from a file and write data into
another text file using BufferWriter
Output:
Welcome to javaTpoint.
3. Write a java program to write data into a text file using FileWriter.
BufferedWriter
Java BufferedWriter class is used to provide buffering for Writer instances. It
makes the performance fast. It inherits Writer class. The buffering characters are
used for providing the efficient writing of single arrays, characters, and strings.
FileWriter
Java FileWriter class is used to write character-oriented data to a file. It is
character-oriented class which is used for file handling in java. Unlike
FileOutputStream class, you don't need to convert string into byte array because
it provides method to write string directly.
FileReader
Java FileReader class is used to read data from the file. It returns data in byte
format like FileInputStream class. It is character-oriented class which is used for
file handling in java.
StringWriter
Java StringWriter class is a character stream that collects output from string
buffer, which can be used to construct a string. The StringWriter class inherits the
Writer class. In StringWriter class, system resources like network sockets and
files are not used, therefore closing the StringWriter is not necessary.
StringReader
Java StringReader class is a character stream with string as a source. It takes an
input string and changes it into character stream. It inherits Reader class. In
StringReader class, system resources like network sockets and files are not
used, therefore closing the StringReader is not necessary.
InputStreamReader
An InputStreamReader is a bridge from byte streams to character streams: It
reads bytes and decodes them into characters using a specified charset. The
charset that it uses may be specified by name or may be given explicitly, or the
platform's default charset may be accepted.
OutputStreamWriter
OutputStreamWriter is a class which is used to convert character stream to byte
stream, the characters are encoded into byte using a specified charset. write()
method calls the encoding converter which converts the character into bytes. The
resulting bytes are then accumulated in a buffer before being written into the
underlying output stream. The characters passed to write() methods are not
buffered. We optimize the performance of OutputStreamWriter by using it with in
a BufferedWriter so that to avoid frequent converter invocation.
CharArrayReader
The CharArrayReader is composed of two words: CharArray and Reader. The
CharArrayReader class is used to read character array as a reader (stream). It
inherits Reader class.
CharArrayWriter
The CharArrayWriter class can be used to write common data to multiple files.
This class inherits Writer class. Its buffer automatically grows when data is
written in this stream. Calling the close() method on this object has no effect.
5. What are the methods available in the Character Streams? Discuss
6. What are the methods available in the PrintWriter Class? Discuss.