DCA7102 - Programming in Java
DCA7102 - Programming in Java
2114100139
Name: DHANANJAY
Address: B-19 House No 151 Chhawla
New Delhi - 110071
Signature:
Assignment Set – 1
Ques 1.
a. Discuss the architecture of Java with the help of suitable diagram. Explain their entire
technicality in detail.
Ans: The Java Architecture is made up of the JVM, JRE, and JDK. It combines the processes of
interpretation and compilation. It lists each step required to create a Java programme. Each step in
the compilation and execution of a programme is described in the Java Architecture. Simply said,
the following points and diagram will show how Java architecture is structured:
1. Java has two processes: compilation and interpretation.
2. After the JAVA code is written, the JAVA compiler comes into the picture that converts
this code into byte code that can be understood by the machine.
3. The Java Virtual Machine (JVM) turns the created bytecode into machine code, i.e. (.class
file)
4. The machine then executes the programme.
Source Code Java Virtual
Machine (JVM)
Java Compiler
Operating
System (OS)
Byte Code
JVM Architecture
Class loader: The class loader is a component of the JVM. It is employed in the loading of class
files. When we launch a Java program, the class loader loads it first.
Method Area: It’s where you’ll keep all of your class information. Static variables, static blocks,
static methods, and instance methods are all stored in this section.
Heap: When the JVM boots up, it creates a heap. During the application’s runtime, it may grow
or shrink in size.
Stack: A thread stack is the same as a JVM stack. It is a data region established in the JVM
memory for a single execution thread. A thread’s JVM stack is used to hold numerous items like
local variables, partial results, and data for calling methods and returning data.
Native Stack: All native methods used in your program are included in this category.
Execution Engine: It comprises of JIT compiler and Garbage collector.
JIT Compiler: The runtime environment includes the Just-In-Time (JIT) compiler. To increase
the efficiency of Java applications, this compiler produces bytecodes at runtime. The JIT compiler
is enabled by default. When a compiled method is compiled, the JVM refers to it as a method. The
JIT compiler translates bytecode to machine code and compiles it for execution “just-in-time.”
Garbage Collector: The garbage collector, which is a Java program, is used to manage the
memory. Mark and Sweep are the two steps of the system. The garbage collector uses Mark to
distinguish between used and unused memory chunks. The Sweep clears the Mark of the specified
object.
Native Interface: The Java Native Interface acts as a bridge between Java method calls and native
library calls.
Native Libraries: Java Native Libraries are libraries that include code or programs written in
languages other than Java, such as C, C++, and others. With the help of Java Native Interface
(JNI), they can be integrated into the Java application as needed.
b. What is Unicode? Explain. Discuss the various data types available in java programming
in detail.
Ans: UNICODE. Universal Character Encoding.
Almost all of the written programming languages in the world can be represented using the
universal international standard character encoding known as Unicode.
Since a character in Unicode takes up two bytes, Java also uses two bytes for characters.lowest
value:\u0000
highest value:\uFFFF
Example:
Boolean one = false
Ques 2.
a. Explain the various utilities of ‘super’ keyword in context to inheritance? Explain each
utility with the help of java program.
Ans: In Java, the super keyword is a reference variable that is used to refer to the object of the
immediate parent class. When you create a subclass instance, an implicit instance of the parent
class is also created and is referred to by the super reference variable.
When referring to an immediate parent class instance variable, use super. The data member or field
of the parent class can be accessed using the super keyword. When the fields of the parent class
and the child class match, it is used.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}
}
Output:
black
white
In the above example, Animal and Dog both classes have a common property color. If we print
color property, it will print the color of current class by default. To access the parent property, we
need to use super keyword.
b. How java handles exceptions? Discuss the utility of ‘try’ and multiple ‘catch’ statement
with the help of java program.
Ans: The term exception in Java means the occurrence of an exceptional event. It is defined as an
abnormality that occurs while the program is in execution which hinders the successful execution
of the program, which means the way the program is meant to produce the result it doesn’t do so.
The rest of the block's code won't run if an exception occurs at the try block's statement. Therefore,
it is advised against keeping code in a try block that won't throw an exception.
A single try block in Java can include several catch blocks. We need numerous catch blocks to
handle various exception kinds when statements in a single try block cause multiple exceptions.
In Java, this mechanism is known as a multi-catch block.
Output:
A number cannot be divided by zero, Illegal operation in java
I am out of try-catch block
3. What are streams in java? Discuss their various types. Explain at least 5 pre-defined
methods and their functionality used through stream classes.
Ans: Java uses streams to manage all input and output. A stream is a collection of bytes that travels
via a communication link from a source to a destination. A programme is the source of a stream if
it sends data into it. Similar to that, it is the stream's destination if it is reading from one. Because
they abstract the specifics of input/output (I/O) operations, streams are effective.
The input and output streams are the two types of streams most frequently utilised. Each stream
performs a certain function. Only an output stream can be written to, and only an input stream can
be read from.
Some streams fall under the category of mode streams because they read from or write to a
particular location, such as memory or a disc file. Some streams are classified as filters. Filters are
used to read data from one stream and write it to another stream.
The stream classes of java.io packages are categorized into two groups based on the data type on
which they operate:
• Byte Stream: Provide support for handling I/O on bytes.
• Character stream: Provide support for handling I/O on characters.
InputStream and OutputStream are the two main classes for byte streams. Subclasses of these
abstract classes are created to offer different I/O capabilities. The output class hierarchy's
foundation is laid by the OutputStream class, whereas the input class hierarchy's is laid by the
InputStream class.
Input Stream
Sequence Object Input Filter Input ByteArray File Input Piped Input
Input Stream Stream Stream Input Stream Stream Stream
Output
Stream
Buffered
Data Output
Output
Stream
Stream
JDK 1.1 introduces the Reader and the Writer classes for Unicode I/O. These classes support
internationalization.
Reader Class Hierarchy
Reader
Writer
Markable streams enable the placement of "bookmarks" and the ability to reset the stream. Then,
starting from the location marked, this stream can be read. If a stream is marked, it needs some
memory to maintain track of the information between the mark and the stream's current position.
Methods of OutputStream
write() - writes the specified byte to the output stream
write(byte[] array) - writes the bytes from the specified array to the output stream
flush() - forces to write all data present in output stream to the destination
close() - closes the output stream
Example:
import java.io.FileOutputStream;
import java.io.OutputStream;
public class Main {
public static void main(String args[]) {
String data = "This is a line of text inside the file.";
try {
OutputStream out = new FileOutputStream("output.txt");
Methods of InputStream
read() - reads one byte of data from the input stream
read(byte[] array) - reads bytes from the stream and stores in the specified array
available() - returns the number of bytes available in the input stream
mark() - marks the position in the input stream up to which data has been read
reset() - returns the control to the point in the stream where the mark was set
markSupported() - checks if the mark() and reset() method is supported in the stream
skips() - skips and discards the specified number of bytes from the input stream
close() - closes the input stream
Example:
import java.io.FileInputStream;
import java.io.InputStream;
class Main {
public static void main(String args[]) {
byte[] array = new byte[100];
try {
InputStream input = new FileInputStream("input.txt");
System.out.println("Available bytes in the file: " + input.available());
// Read byte from the input stream
input.read(array);
System.out.println("Data read from the file: ");
// Convert byte array into string
String data = new String(array);
System.out.println(data);
// Close the input stream
input.close();
} catch (Exception e) {
e.getStackTrace();
}
}
}
Assignment Set – 2
• Extends: The keyword extends used to create inheritance between two classes and two interfaces.
• Implements: To generate inheritance across classes and interfaces, the word "implements" is
used.
The most essential interface of the collections system is the Collection interface, which is the root
interface of all archives in the API (Application programming interface). This is the highest level
of the collection hierarchy in Java. You can use simple ways to add and remove elements from the
Collection.
The Collection interface is an addition to the Iterable interface. The Iterator procedure is the only
one there is in the Iterable interface (). The iterator object is to be retrieved via the iterator method.
The array's elements that make use of this iterator object can be looped over.
b. Discuss java annotation, and java custom annotation in detail with the help of java
example.
Ans:
Java annotation
Java code can have meta data added using Java annotations. Java annotations are meta data, thus
they don't directly influence how the code is executed, though some sorts of annotations can be
utilised in that way.
Many things can be done with annotations, including:
• Information for the compiler - The compiler can utilise annotations to identify mistakes or turn
off warnings.
• Processing at compile-time and deployment-time - Software tools can process annotation data to
produce code, XML files, and other things.
• Runtime processing - Runtime analysis is possible for some annotations.
There are a few things that the programmer needs to keep in mind.
1. There shouldn't be any throws clauses in the method
2. The method must return a primitive data type, a String, a Class, an enum, or an array of these
data types.
3. There should be no parameters in the method.
4. To define annotation, we should attach @ immediately before the interface keyword.
5. It might provide the method a default value.
Types of Annotation
There are three types of annotations.
1. Marker Annotation
2. Single-Value Annotation
3. Multi-Value Annotation
Marker Annotation
An annotation that has no method, is called marker annotation.
For example:
@interface MyAnnotation{}
The @Override and @Deprecated are marker annotations.
Single-Value Annotation
An annotation that has one method, is called single-value annotation.
For example:
@interface MyAnnotation{
int value();
}
Multi-Value Annotation
An annotation that has more than one method, is called Multi-Value annotation.
For example:
@interface MyAnnotation {
int value1();
String value2();
String value3();
}
Ques 2.
a. Discuss any 5 component classes of swing. Demonstrate a program which shows their
utility.
Ans:
1. ImageIcon
The ImageIcon component creates an icon sized-image from an image residing at the source URL.
Example:
ImageIcon homeIcon = new ImageIcon("src/images/home.jpg");
This returns an icon of a home button. The string parameter is the path at which the source
image is present.
2. JButton
To construct a push button on the user interface, utilise the JButton class. There may be display
text or a picture on the button. When clicked and double-clicked, it causes an event. By using one
of its constructors, a JButton can be added to the programme.
Example:
JButton okBtn = new JButton("Ok");
This constructor returns a button with text Ok on it.
3. JLabel
For rendering read-only text labels or images on the user interface, utilise the JLabel class.
No event is produced by it.
Example:
JLabel textLbl = new JLabel ("This is a text label.");
This constructor returns a label with text.
JLabel imgLabel = new JLabel (homeIcon);
It returns a label with a home icon.
4. JTextField
An editable single-line text box is produced by JTextField. The box allows users to enter
unformatted content. Call the function Object() { [native code] } of the text field and feed
it an optional integer parameter to initialise it. This setting controls the box's width, which
is determined by the number of columns. The amount of characters that can be entered into
the box is unrestricted.
Example:
JTextField txtBox = new JTextField(20);
It renders a text box of 20 column width.
5. JTextArea
A multi-line text box is rendered using the JTextArea class. The field allows users to enter
unformatted text similarly to the JTextField. JTextArea's function Object() { [native code]
} also anticipates two integer parameters that specify the text-height area's and width in
terms of columns. The user's ability to enter any amount of characters in the text-area is
not limited.
Example:
JTextArea txtArea = new JTextArea ("This text is default text for text area.", 5, 20);
The above code renders a multi-line text-area of height 5 rows and width 20 columns, with
default text initialized in the text-area.
Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingControlDemo {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public SwingControlDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingControlDemo swingControlDemo = new SwingControlDemo();
swingControlDemo.showImageIconDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java Swing");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.add(b);
mainFrame.setVisible(true);
}
private static ImageIcon createImageIcon(String path,
String description) {
java.net.URL imgURL = SwingControlDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
private void showImageIconDemo(){
headerLabel.setText("Control in action: ImageIcon");
ImageIcon icon = createImageIcon("/resources/java_icon.png","Java");
JLabel commentlabel = new JLabel("", icon,JLabel.CENTER);
controlPanel.add(commentlabel);
mainFrame.setVisible(true);
}
}
b. What is multithreading? Discuss its life cycle with the help of suitable diagram.
Ans: Java provides multithreaded programming, enabling you to design programmes that adhere
to the requirements for networked and interactive systems in the real world. C and C++ do not
support multithreading, whereas Java does. A thread is a simple operation. CPU efficiency is
increased by multithreading. Several threads can be created within a programme, and they can all
run simultaneously or concurrently with one another. The ability to simultaneously write in a word
document and play a game while listening to music is an example of a real-world requirement. The
Java run-time system enables you to build interactive systems that operate smoothly and offers a
solution for multi-process synchronisation.
Ques 3. How Java Server Pages can be created? Discuss all the steps involved along with
suitable java example.
Ans: In general, Java Server pages are text files that combine traditional HTML and fresh scripting
tags. JSPs have an HTML appearance, but when they are initially called, they are converted into
Java Servlets. The HTML from the JSP file and embedded dynamic material that is defined by the
new tags are combined to create the final servlet. Some of them will only be composed of Java
code; this is especially helpful when the JSP is in charge of something specific, such maintaining
application flow.
JSPPage.jsp
<html>
<head>
<title> JSPPage </title>
</head>
<%
int demvar=0;%>
<body>
Count is:
<% Out.println(demovar++); %>
<body>
</html>
Demo.jsp's explanation of the code
HTML start tag on line 1 of the code
Head tag in code line two
Code Lines 3 to 4: Closing head tag and title tag, i.e. Demo JSP
Code Line 5,6: Initializing the variable demo in the scriptlet tag
Code Lines 7 and 8: A text to be printed in the output is in the body tag (Count is: )
Code Line 9: Scriplet tag that attempts to output the demovar variable with an increased value
Code Line 10-11: Closed HTML and body tags
JSP Servlet Class :
Public class servletJSP extends HttpServlet {
Public void _jspservice(HttpServletRequest request, HttpServletResponse response)
throws IOException,ServletException {
PrintWriter out = response.getWriter();
Response.setContentType(“text/html”);
out.write(“<html><body>”);
int var = 0;
out.write(“Count is :”);
out.print(var++);
out.write(“</body></html>”);
}
}
Output : Count is: 1