Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
50 views

DCA7102 - Programming in Java

The document provides details about a student named Dhananjay enrolled in a Programming in Java course. It includes the student's enrollment number, name, address, contact details, course details, and a signature. An assignment set-1 is also included which asks questions about Java architecture and data types.

Uploaded by

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

DCA7102 - Programming in Java

The document provides details about a student named Dhananjay enrolled in a Programming in Java course. It includes the student's enrollment number, name, address, contact details, course details, and a signature. An assignment set-1 is also included which asks questions about Java architecture and data types.

Uploaded by

Dhananjay Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Enrolment No: dhananjay.

2114100139
Name: DHANANJAY
Address: B-19 House No 151 Chhawla
New Delhi - 110071

Course Title: Programming in Java


Course Code: DCA7102
Phone No.: 9711440620
Personal Email ID: kumardhananjay@outlook.in
University Email ID: dhananjay.2114100139@mujonline.edu.in

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

Components of Java Architecture


The three primary parts of the Java architecture are the JRE (Java Runtime Environment), JDK
(Java Development Kit), and JVM (Java Virtual Machine).

Java Runtime Environment (JRE)


The JRE software creates a runtime environment in which Java programmes can function. A disk-
based system called the Java Runtime Environment (JRE) combines Java code with the essential
libraries. The Java Virtual Machine (JVM) then starts to execute the Java code. The libraries and
software needed to run Java programmes are all included in the Java Runtime Environment (JRE).
Although JRE is a part of the JDK, it can also be downloaded separately.

Java Development Kit (JDK)


It is a platform for creating Java applets and applications. The Java Development Kit contains JRE,
a compiler, an interpreter or loader, and a number of development tools. We will now go over
these development tools that are included with JDK:
Java is in charge of starting Java applications (loader/executor).
javac(compiler): It is in charge of assembling Java apps.
Javadoc: facilitates the creation of API documentation
Jar is in charge of producing and maintaining all JAR files.

Java Virtual Machine (JVM)


The most significant component of Java is WORA. WORA stands for Write Once, Run Anywhere.
Depending on the feature, we can write our code once and use it across all operating systems and
locations. Our Java software can run on any platform because of the Java Virtual Machine. It is a
part of the Java platform that gives us a platform on which to run Java programmes. The JVM's
primary function is to convert byte code into machine 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

Data Types in Java


Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long,
float and double.
2. Non-primitive data types: The non-primitive data types include and Arrays
Java Primitive Data Types
Primitive data types are the fundamental units of data manipulation in Java. These are the most
fundamental data types that the Java language supports.
Boolean Data Type
There are only two potential values that can be stored using the Boolean data type: true and false.
Simple flags that track true/false situations are utilised with this data type. Although the Boolean
data type only specifies one piece of information, its exact "size" cannot be determined.

Example:
Boolean one = false

Byte Data Type


An illustration of a basic data type is the byte data type. It is an integer with two's complement and
an 8-bit sign. Its range of values is from -128 to 127. (inclusive). Its minimum and maximum
values are -128 and 127 respectively. The default setting is 0. When memory savings are most
needed, like in huge arrays, the byte data type is employed. Because a byte is four times smaller
than an integer, space is conserved. The "int" data type can likewise be replaced with this one.

Short Data Type


The short data type is a 16-bit signed two's complement integer. Its value-range lies between -
32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its
default value is 0. The short data type can also be used to save memory just like byte data type. A
short data type is 2 times smaller than an integer.

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.

Usage of Java super Keyword


1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

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.

Java try block


Try blocks are used in Java to include code that might raise an exception. It has to be applied to
the technique.

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.

Java try blocks must be followed by a finally block or a catch.

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.

Program source code 1:


public class MultiCatchEx1
{
public static void main(String[] args)
{
try
{
int arr[] = new int[6];
arr[3] = 20/0; // Exception occurred.
System.out.println("I am in try block");
}
catch(ArithmeticException ae)
{
System.out.println("A number cannot be divided by zero, Illegal operation in
java");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Accessing array element outside of specified limit");
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
System.out.println("I am out of try-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.

The diagrams below represent the hierarchy of the two streams.

Input Stream Class Hierarchy

Input Stream

Sequence Object Input Filter Input ByteArray File Input Piped Input
Input Stream Stream Stream Input Stream Stream Stream

Pushback Buffered Data Input


Input Stream Input Stream Stream

Output Stream Class Hierarchy

Output
Stream

Object Byte Array


Piped Output Filter Output File Output
Output Output
Stream Stream Stream
Stream 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

BufferedReader CharArrayReader StringReader PipedReader InputStreamReader FilterReader

Writer Class Hierarchy

Writer

BufferedWriter StringWriter PipedWriter CharArrayWriter PrintWriter OutputStreamWriter FilterWriter

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");

// Converts the string into bytes


byte[] dataBytes = data.getBytes();

// Writes data to the output stream


out.write(dataBytes);
System.out.println("Data is written to the file.");
// Closes the output stream
out.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}

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

1. a. Explain the collection hierarchy with the help of diagram.


The entire collection framework hierarchy consists of two distinct sorting interfaces called
SortedSet and SortedMap in addition to the four fundamental interfaces Collection, List, Set, and
Map. All of the interfaces and classes for the collection framework are included in the Java.util
package.

Collection framework mainly consists of four interfaces:


1. List: It has elements that are sequentially ordered, and you may access those items by using
their index positions (starting from 0). It uses ArrayList, Vector, and VectorList
implementations. The list's elements can be added at any location, but they can also be
removed in the same order that they were added. Furthermore, duplicate items may be
stored.
2. Queue: Similar pieces are added to the queue from one end while being removed from the
other end (FIFO – First In First Out). It uses PriorityQueue and LinkedList.
3. Set: A set is a container for a group of distinctive parts. In the Set, duplication is not
permitted. The elements are not kept in a sequential order. We might not receive the
elements when accessing them in the same order that they are stored. The Set interface is
implemented by HashSet, LinkedHashSet, and TreeSet. Only the Iterator can iterate over
Set elements.
4. Map: Map stores the elements in the form of Key/Value pairs. It is extended by SortedMap
and implemented by HashMap and HashTable. It does not contain duplicate values, and
each key can, at most, store one value.

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

Java Custom Annotation


Java Custom annotations or Java User-defined annotations are easy to create and use. The
@interface element is used to declare an annotation.
For example:
@interface MyAnnotation{}

Here, MyAnnotation is the custom annotation name.

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();
}

We can provide the default value also.


For example:
@interface MyAnnotation{
int value() default 0;
}

Let's see the code to apply the single value annotation.

@MyAnnotation(value=10) //The value can be anything.

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();
}

We can provide the default value also.


For example:
@interface MyAnnotation {
int value1() default 1;
String value2() default "";
String value3() default "xyz";
}

Let's see the code to apply the multi-value annotation.


@MyAnnotation (value1=10, value2="ArunKumar”, value3="Ghaziabad")

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);

controlPanel = new JPanel();


controlPanel.setLayout(new FlowLayout());

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.

Life Cycle of a thread


New Thread: A new thread is in the new state when it is created. When the thread is in this state,
it has not yet begun to run. A thread's code has not yet ran and has not begun to execute when it is
in the new state.
Runnable State: A ready-to-run thread is transferred to a runnable state. A thread may be actively
operating in this state or it may be prepared to begin at any moment. The thread scheduler is in
charge of giving the thread enough time to run.
Each thread in a multi-threaded software receives a defined amount of time. Every thread briefly
runs before pausing and giving the CPU to another thread so that others can have a chance to run.
When this occurs, the thread that is now executing and all such threads that are waiting for the
CPU are in a runnable condition.
Blocked/Waiting state: When a thread is temporarily inactive, then it’s in one of the following
states:
• Blocked
• Waiting
Timed Waiting: When a thread calls a method with a time-out parameter, it is in a timed waiting
state. Until the timeout expires or a notification is received, a thread is in this state. For instance,
a thread enters a timed waiting state when it calls sleep or a conditional wait.
Terminated State: A thread terminates because of either of the following reasons:
• Because it exits normally. This happens when the code of the thread has been entirely
executed by the program.
• Because there occurred some unusual erroneous event, like segmentation fault or an
unhandled exception.

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.

JSP involves the following steps:


• JSP page translation
• JSP page compilation (JSP page compilation into _jsp.java)
• Classloading (converting _jsp.java to _jsp.class),
• Instantaneous (Object of generated servlet is created)
• Initialization (container calls the _jspinit() function)
• Request Processing (the container calls the _jspservice() function)
• Destroy (using the container's _jspDestroy() function)

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

You might also like