0% found this document useful (0 votes)
68 views9 pages

Soniya Hariramani JAVA PROGRAMMING

The document is an internal assignment for a student named Ritesh Kumar Karn for their MCA semester 3 Java programming subject. It contains their responses to two questions - an explanation of the Java virtual machine and why Java is platform independent, and describing packages in Java and explaining four predefined packages in more detail.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views9 pages

Soniya Hariramani JAVA PROGRAMMING

The document is an internal assignment for a student named Ritesh Kumar Karn for their MCA semester 3 Java programming subject. It contains their responses to two questions - an explanation of the Java virtual machine and why Java is platform independent, and describing packages in Java and explaining four predefined packages in more detail.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

INTERNAL i ASSIGNMENT

NAME RITESH KUMAR KARN


SESSION NOV 2023
PROGRAM MASTER OF COMPUTER APPLICATIONS (MCA)
SEMESTER III
SUBJECT CODE & NAME DCA7102 & JAVA PROGRAMMING
ROLL NO 2214503076
BATCH 04
Set-I

Q.1. Explain java virtual machine? Why is java considered as platform independent?
Ans - Java Virtual Machine (JVM) is the kernel or core of the Java Execution Environment
(JRE), which allows Java applications to run on multiple platforms without any modifications.
It follows the process of abstraction between compiled Java code and the underlying hardware
and operating system. Here is a complete description of the Java Virtual Machine and why Java
is considered platform independent:

Java Virtual Machine (JVM):


JVM is a virtualized workstation that defines and completes the Java bytecode. A compiled
form of Java source code. It plays an important role in making Java application platform
independent. Below are the main functions of JVM:

Executing bytecode:
Java source code is compiled into an intermediate form called bytecode. Bytecode is a set or
group of instructions that the JVM can read and execute.

Platform independence:
Unlike traditional compiled languages, Java is not compiled directly into hardware- and
operating-system-specific machine code. In its place, Java code is compiled into bytecode,
which is platform-independent.

Just-In-Time (JIT) compilation:


The JVM uses a Just-In-Time compiler to change bytecode into native machine code at
runtime. This allows Java applications to achieve performance comparable to natively
compiled languages.

Memory Management:
The JVM takes care of memory management, including waste or garbage collection, which
automatically or certainly frees memory captured by objects that are no longer in use.

Safety features:
The JVM add in security or safety features such as sandboxing that limit possibly malicious
operations and boost the overall security of Java applications.

Platform independence in Java:


Write Once, Go Anywhere (WORA)
Java's platform independence is summarized in the "Write Once, Run Anywhere" (WORA)
theory. Developers can write Java code on one platform and assume it to run or work on any
another platform with a compatible JVM.

Bytecode Portability:
The Java bytecode is platform independent, allowing it to run on any device that has a JVM
installed. This eliminates the need for recompilation when changing Java applications among
platforms.

Hardware abstraction:
The JVM abstracts away hardware details and delivers a constant runtime conditions regardless
of the underlying hardware architecture.
Operating system neutrality:
Java applications can run on another operating systems without change as long as there is a
JVM friendly with that operating system.

Q.2. What are packages in java? Explain any 4 pre- defined packages in details.
Ans - In Java, packages are a way to organize classes and interfaces into a single namespace.
This helps avoid name conflicts and provides a way to unify groups of related classes.
Packaging is essential for creating modular and maintainable Java applications. A hierarchical
structure for thread management makes it easier to organize and manage your code base.

Java has four predefined packages, each of which has a specific purpose.

java.lang:

The java.lang package is one of the most important Java packages. This class is automatically
imported into all Java programs, making the class visible to all programs without an explicit
import statement. This package contains basic classes and interfaces needed for basic
programming in Java. Some of the main classes in this file/folder are:
Object: The root class for all Java classes.
String: Represents a sequence of characters and is commonly used in Java programming.
System: Provides access to the system, such as input/output streams and environment variables.
Mathematics: includes all methods of mathematical operations.
Java.lang classes are very important to the fundamentals of Java programming and are widely
used in almost all Java programs.

java.util:
The java.util package provides a set of useful classes and interfaces for working with various
data structures and operations. Contains classes that help you manage dates, times, and other
common tasks for collections such as lists, collections, and maps. The key lessons of this
package are:

ArrayList, LinkedList: Dynamic array and linked list implementations respectively.


HashMap, TreeMap: Implementation of hash tables and treemap for storing key-value pairs.
Collections: includes a variety of useful techniques for managing collections such as sorting
and searching.
Developers often use java.util classes to efficiently manage and manipulate data structures in
their programs.

java.io:
The java.io package provides classes that perform I/O operations in Java. It includes teaching
reading and writing files, working with streams and serialization. Some of the main classes in
this folder are:

File: Indicates a file or directory.

Q.3 . Explain the collection hierarchy.


Ans - In computer science, collection or group of hierarchy refers to the organization and
classification or sorting of data structures used to store and manage collections of elements.
Collections are important in programming because they permit you to group related data and
execute several operations on it efficiently. Hierarchies typically include several interfaces and
classes that serve specific purposes and specify different features. At the peak level of the
collection hierarchy are interfaces or lines that identify the assumed basic functionality of the
collection. The most famous interface:Group interface:This is the root interface of a collection
hierarchy that represents a collection of objects.Add defines basic methods such as adding,
subtracting, and including that are common to all collections.List of interfaces:It extends the
Collections interface and provides positional access to elements using indexes. Allows
repeating elements and preserves the order in which elements are inserted. Notable
implementations include Array List and LinkedList.Configure the interface:Extends the
collection interface, but does not allow for some elements.Functions include HashSet and Tree
Set.Queue interface:Collections are used to store elements before processing.It follows the
First-In-First-Out (FIFO) principle.Common implementations include LinkedList and Priority
Queue.Card interface:Represents a collection of key-value pairs.Each key is associated with a
specific value and a unique key.HashMap and TreeMap are popular implementations.These
interfaces provide a high-level view of the collection and create common methods that different
concrete classes must apply. Concrete classes, in turn, provide specific implementations of
these interfaces, customizing their behavior for different use cases.For example, the Java
collection framework includes many classes that implement these interfaces:Array
List:Implements the Enumeration interface using a resizable dynamic array.It provides fast
random access, but it can be more efficient for frequent insertions and deletions.Linked List:It
implements List and Queue interfaces using doubly linked lists.Enables efficient insertion and
removal at both ends.HashSet:Implement the Set interface using the Set table.Provides constant
average complexity for core operations.TreeSet:Implements the Set interface using a self-
aligning binary search tree.Ordered elements, useful for scenarios that require an ordered
arrangement.HashMap:Implements card interface using Hash table.Provides quick access to
elements via key pairs.TreeMap:It implesments the Map interface using a self-adjusting binary
search tree.Entries are ordered by their key.Understanding the collection hierarchy is essential
to choosing the right data structure for a given problem. Each class and interface has advantages
and disadvantages, and the appropriate choice depends on the requirements of our application,
such as application frequency, interference and search frequency, as well as element
arrangement and uniqueness. By using the collection hierarchy effectively, programmers can
optimize the functionality and performance of their applications.

Set-II

Q.4. Explain the various categories of primitive data types used in java programming. Write
a suitable java program for any two primitive data type categories.
Ans - In Java programming, primitive / fundamental statistics sorts are the fundamental or
regular additives for retaining and manipulating simple values. statistics sorts fall into two
categories: numeric and non-numeric. Now I inspect or look at each category and i'm give an
explanation for a Java software using primitive records kinds from every.

A Numeric records sorts:

In Java, the numeric statistics type is applied or used to symbolize a numbers. it's miles
different divided into integral type and floating point kind.

necessary types:

byte: this records type is an eight-bit signed -plus integer. The series is from -128 to 127.
brief: sixteen-bit -plus integer amongst -32,768 and 32,767.
int: this is a -plus signed 32-bit integer with a big or huge range of about 2 billion to two
billion.

duration: two-plus integer with a greater c language of 64 bits.


A Program i #Java program demonstrating the use of int and long:

public class NumericExample {


public static void main(String[] args) {
int myInt = 42;
long myLong = 123456789012345L;

System.out.println("Integer Value: " + myInt);


System.out.println("Long Value: " + myLong);
}
}

Floating point type:

float: 32-bit IEEE 754 floating point. Suitable for showing decimal numbers.

double: 64-bit IEEE 754 floating point. It delivers higher accuracy related to flotation.

A Program - #Java program explaining the use of float and double:

public class FloatingPointExample {


public static void main(String[] args) {
float myFloat = 3.14f;
double myDouble = 2.71828;

System.out.println("Float Value: " + myFloat);


System.out.println("Double Value: " + myDouble);
}
}

B Non-Numeric Data Types:

Non-numeric data types in Java are used to represent characters and boolean values.

Char

The char data type is a 16-bit Unicode character. It can store a single character, such as a letter,
number, or special symbol.

Here is a Java program demonstrating the use of the character:

public class CharExample {


public static void main(String[] args) {
char myChar = 'A';
System.out.println("Character Value: " + myChar);
}
}
Boolean:

The Boolean data type is used for variables that hold true or false values. It is usually used for
conditional sentences.

Here is a Java program that demonstrates the use of Boolean:

public class BooleanExample {


public static void main(String[] args) {
boolean isJavaFun = true;
boolean isCodingHard = false;

System.out.println("Java is Fun: " + isJavaFun);


System.out.println("Coding is Hard: " + isCodingHard);
}
}

This type of data is very important for effective programming, so computer programmer choose
the suitable type based on the wants of their application. The following patterns show how to
declare and use variables of various primitive data types in a Java program.

Q.5. What are exceptions in java? Explain any 4 exception classes in detail. Write a suitable
java program to explain the utility of exceptions
Ans –
Exceptions in Java:
An exception in Java is an incident / event or situation that appears during program execution
and interrupts the normal flow of program instructions. When an exception occurs, the Java
Virtual Machine (JVM) creates an object known as "exception object" to handle the exception.
The Java programming language delivers or provides a powerful and thorough exception
mechanism to handle such situations.

Common exception classes in Java:

1 Arithmetic Extraction:
An exemption occurs when an arithmetic operation encounters an exception. For example,
dividing a number by zero throws an Arithmetic Exception. Here's an example:
public class ArithmeticExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // Division by zero
} catch (ArithmeticException e) {
System.out.println("Exception: " + e.getMessage());
}
}
}
2 Null Pointer Exception:

This exception happens when you try to retrieve or modify an object reference that holds a
value. This is a common runtime error and can be keep away by confirming that the object is
initialized correctly.

example:

public class NullPointerExceptionExample {


public static void main(String[] args) {
String str = null;
try {
int length = str.length(); // Attempting to access the length of a null string
} catch (NullPointerException e) {
System.out.println("Exception: " + e.getMessage());
}
}
}

3 Array Index Out of Bounds Exception:

This exception is thrown when an attempt is made to access an array element with an out-of-
bounds pointer.

example:

public class ArrayIndexOutOfBoundsExceptionExample {


public static void main(String[] args) {
int[] numbers = {1, 2, 3};
try {
int value = numbers[5]; // Accessing an element outside the array bounds
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception: " + e.getMessage());
}
}
}

4 File Not Found Exception:


This exception is thrown when an attempt is made to access a file that cannot be found. This is
usually encountered when dealing with file I/O operations.

Example –

import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;

public class FileNotFoundExceptionExample {


public static void main(String[] args) {
try {
File file = new File("nonexistent.txt");
FileReader reader = new FileReader(file); // Attempting to read from a nonexistent file
} catch (FileNotFoundException e) {
System.out.println("Exception: " + e.getMessage());
}
}
}

Java Program Demonstrating Exception Handling:

import java.util.Scanner;

public class NumberFormatExceptionExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

try {
System.out.print("Enter a number: ");
String userInput = scanner.nextLine();

int number = parseNumber(userInput);


System.out.println("You entered: " + number);

} catch (NumberFormatException e) {
System.out.println("NumberFormatException: " + e.getMessage());
System.out.println("Please enter a valid number.");

} finally {
// Close any resources or perform cleanup code here
scanner.close();
}
}

private static int parseNumber(String input) {


return Integer.parseInt(input);
}
}

Q.6 - Differentiate between JDBC and ODBC drivers?

Ans - JDBC (Java Database Connectivity) and ODBC (Open Database Connectivity) are each
widespread techniques for packages to have interaction or cooperate with databases. yet, they
be distinctive in structure, execution, implementation and the systems they are designed to run
on.

JDBC (Java Database Connectivity):


JDBC is a Java-based API (application Programming Interface) that lets in Java packages to
cooperate or interact with databases. It provides a fixed of lessons and interfaces that permit
Java packages to hook up with and perform square queries against the database. one of the
important blessings of JDBC is platform independence in view that Java is a pass-platform
language.

JDBC contains of two principal components: the JDBC API and the JDBC driver. The JDBC
API affords or preserve a hard and fast of classes and interfaces that pick out how Java
programs relate with the database. A JDBC driving force, at the every other hand, is a platform-
precise method that transforms JDBC calls into database calls. There are 4 varieties of JDBC
drivers:

1 (JDBC-ODBC Bridge driving force): This driving force transmutes JDBC calls to ODBC
calls, permitting Java applications to get entry to databases thru ODBC.

2 (API-local motive force): This motive force handles a database-precise API to attach at once
with the database. presents better overall performance than JDBC-ODBC Bridge driver
drivers.

3 (community Protocol motive force): This driving force turns JDBC calls into middleware
protocols and then into database calls. provide get entry to to the database across the network.

4 (thin driving force): this is a clear Java driver that connects without delay with the database
with the database's local protocol. that is a form of JDBC motive force this is platform
independent and normally used.

ODBC (Open Database Connectivity):


ODBC is a fashionable interface that permits you to get right of entry to statistics in a database
control gadget (DBMS) the usage of square. not like JDBC, ODBC isn't a language unique and
is designed to paintings with numerous programming languages, along with C, C++, and Java.
It makes use of a driving force supervisor and a driver to partner to an ODBC database.

The ODBC driving force indicates as an intermediate among the utility and the database. The
ODBC driver supervisor, that is a core aspect of ODBC, handles verbal exchange or interplay
between applications and their parallel ODBC drivers. ODBC drivers are available for a huge
range of databases, requiring them a flexible option for connecting to databases.

however at the same time JDBC and ODBC assist the aim of providing database connections,
JDBC is designed exclusively for Java programs and offers a platform-unbiased solution. on
the every other hand, ODBC is language person and can be used with special programming
languages like Java with the help of bridge drivers like JDBC-ODBC Bridge motive force.

You might also like