Unit 1
Unit 1
PART 1
Java Architecture:
Java architecture refers to the overall design and structure of the Java programming
language, its runtime environment, and the tools used to develop Java applications.
Java architecture has three major components: JRE, JDK and JVM. Java Architecture
explains each and every step on how java programs are compiled and executed. The
Java architecture is built on the principles of platform independence, security, and
reliability.
2. The Java code is compiled into bytecode using the Java compiler (javac). The
bytecode is a platform-independent format that can be executed on any system
that has a Java Virtual Machine (JVM) installed. The bytecode will be stored in
class files (.class) format.
3. The JVM class loader loads the bytecode class files into memory and verifies that
it is a valid Java program. The JVM byte code verifier will check the byte code
and ensures the following:
The code follows JVM specifications.
There is no unauthorized access to memory.
The code doesn’t cause any stack overflows.
There is no illegal data conversions in code such as float to object references.
4. Once the code is verified, JVM will convert the byte code into machine code. The
JVM also performs various tasks such as memory management and garbage
collection.
5. JVM may also use JIT compiler which will help JVM to execute the program faster
as JIT compiler will cache the code for future reuse.
6. Finally, the hardware specific machine code is created and JVM loads and verifies
the machine code in memory. The machine code is specific to the hardware and
operating system, and the JVM takes care of generating the appropriate machine
code for the target system. The machine code generated by the Java Virtual
Machine (JVM) is executed by the underlying hardware and operating system of
the computer on which the Java program is running.
Java Buzzwords
The features of Java are also known as Java buzzwords. The list of major Java
feature or buzzwords are given below:
1. Simple: Java is designed to be easy to learn and use, with a syntax that is
similar to other popular programming languages such as C++ and C#.
3. Portable: Java code is portable, which means that it can be moved easily from
one platform to another (one OS or hardware architecture to another), as long
as there is a JVM available on each platform.
4. Platform independent: Java programs can run on any platform that has a Java
Virtual Machine (JVM) installed, which means that a program written on one
platform can be run on any other platform without modification. When we say
that Java is platform-independent, it means that it is not tied to a particular
operating system or hardware architecture. This is because Java programs are
compiled into bytecode, which is then interpreted by the Java Virtual Machine
(JVM) at runtime.
11. Distributed: Java has built-in support for distributed computing, making
it easy to create applications that run across multiple machines on a network.
12. Dynamic: Java supports dynamic class loading, which allows new classes
to be loaded and integrated into a program at runtime. This feature is useful for
creating flexible, modular programs that can be extended and customized as
needed.
B. Classpath Variables:
In this example, "MyClass" is the name of the main class that is being executed.
PART 2
Arrays
Q. A non-empty array A of length n is called on array of all possibilities if it contains all
numbers between 0 and A.length-1 inclusive. Write a method named isAllPossibilities
that accepts an integer array and returns 1 if the array is an array of all possiblities,
otherwise it returns 0. (5)[2077]
Q. An array is called balanced if it's even numbered elements (a[0], a[2], etc.) are
even and its odd numbered elements (a[1], a[3],etc.) are Odd. Write a function named
is Balanced that accepts an array of integers and returns 1 if the array is balanced
otherwise it returns 0. [5][2075]
Java array is a data structure used to store a fixed-size sequence of elements of the
same data type. In Java, arrays are indexed. The first element is indexed as 0, the last
element as n-1, and so on.
Arrays are classified into two types:
Single dimensional Array
Multidimensional Array
It is also called 1-D array. To declare an array in Java, you need to specify the data
type of the elements that the array will hold and the size of the array. For example, to
declare an array of integers that can hold five elements, you can use the following
code:
int[] numbers = new int[5];
In this code, the ‘int’ keyword specifies the data type of the elements that the array
will hold, and the ‘5’ specifies the size of the array. The ‘new’ keyword is used to
allocate memory for the array.
You can also initialize the elements of an array when you declare it, like this:
int[] numbers = {1, 2, 3, 4, 5};
This code creates an array of integers with five elements and initializes them to the
values 1, 2, 3, 4, and 5.
To access the elements of 1-D array, you can use the array index, which starts at
zero. For example, to access the first element of the numbers array, you can use the
following code:
int firstNumber = numbers[0];
In this code, numbers[0] accesses the first element of the numbers array.
You can also use loops to iterate over the elements of an array. For example, to print
all the elements of the numbers array, you can use the following code:
for (int i = 0; i < numbers.length; i++)
{
System.out.println(numbers[i]);
}
In this code, numbers.length returns the size of the numbers array, and the for loop
iterates over the array elements using the index variable i.
2. Multidimensional Array
Java arrays can be multidimensional, meaning that they can hold more than one arrays
as elements. The multidimensional array with two arrays as elements is 2-D array and
that with three arrays as elements is 3-D array. In Java, multidimensional arrays are
represented as arrays of arrays, where each element of the array is another array.
Two-dimensional array
It is a way to represent data in a tabular or matrix format, where data is arranged in
rows and columns.
To declare a two-dimensional array in Java, you need to specify the number of rows
and columns. For example, to declare a two-dimensional array of integers with 3 rows
and 4 columns, you can use the following code:
int[][] matrix = new int[3][4];
In this code, matrix is a two-dimensional array with 3 rows and 4 columns.
You can initialize the elements of this array using a nested loop.
For example, to initialize the elements of the matrix array with random integers
between 0 and 9, you can use the following code:
import java.util.Random;
int[][] matrix = new int[3][4];
Random random = new Random();
for (int i = 0; i < matrix.length; i++)
{
for (int j = 0; j < matrix[i].length; j++)
{
matrix[i][j] = random.nextInt(10);
}
}
In this code, random is a java.util.Random object that generates random integers
between 0 and 9. The nested loops iterate over each element of the matrix array and
assign it a random integer value.
For example, to initialize the elements of the matrix array manually by entering by
user, you can use the following code:
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
int[][] matrix = new int[3][4];
for (int i = 0; i < matrix.length; i++)
{
for (int j = 0; j < matrix[i].length; j++)
{
System.out.print("Enter element [" + i + "][" + j + "]: ");
matrix[i][j] = scanner.nextInt();
}
}
In this code, scanner is a java.util.Scanner object that reads input from the user. The
nested loops iterate over each element of the matrix array and prompt the user to
enter a value for each element. The nextInt() method of the Scanner class reads the
next integer value entered by the user and assigns it to the current element of the
array.
To access the elements of a two-dimensional array in Java, you need to use two
indices, one for the row and one for the column. For example, to access the element in
the second row and third column of the matrix array, you can use the following code:
int element = matrix[1][2];
In this code, matrix[1][2] accesses the element in the second row and third column of
the matrix array.
foreach in Java
foreach loop provides an alternative approach to traverse the array or collection in
Java. The advantage is that it eliminates the possibility of bugs and makes code more
readable. It traverses each element one by one. The drawback is that, it cannot
traverse elements in reverse order and cannot have option to skip any element
because it does not work on an index basis. But, it is recommended to use it because it
makes the code readable.
Syntax: for(data_type variable_name: array_name)
{
//body of foreach loop
}
Example:
class forEachDemo{
public static void main(String args[]){
int a[]={10, 11, 12, 13};
for(int i:a)
{
System.out.println(i);
}
}
}
Classes and objects
Q. Define class. How do you create a class in Java? Differentiate class with interface.
[5][2076]
Class is a blueprint of real world objects that specifies what data and what methods will
be included in objects of the class. The class is a description group of objects having
similar properties. A class is also called user defined data type or programmers defines
data type because we can define new data types according to our needs by using
classes.
Syntax: class <class_name>{
field;
method;
}
Objects are instances of classes. We can say that objects are variables of class type.
Memory for instance variables are not allocated at the time of class declaration rather
at the time of object creation. Thus, we can say that objects have physical
existence and classes are only concepts.
Creating objects: It can be done using the new operator. The new operator
dynamically allocates (that is, allocates at run time) memory for an object and returns
a reference to it. This reference is the address in memory, of the object allocated by
new. This reference is then stored in the variable. Thus, in Java, all class objects must
be dynamically allocated.
Syntax: Class_name object_varibale = new Class_name();
Ex: Box mybox = new Box();
Simple example of class and objects:
public class Car
{
String model;
int year;
public Car (String model, int year) //Constructor
{
this.model = model;
this.year=year;
}
public void info()
{
System.out.println("The model of car manufactured in " + year + " "+" is"
+
model);
}
Types of modifiers
There are two types of modifier keywords in Java. They are:
1. Access modifiers: private, default, protected and public
2. Non-access modifiers: static, final, abstract, synchronized and volatile.
static int sum(int a, int b,int c){ //changing the number of parameter
return a+b+c;
}
Inheritance
Q. Define inheritance. Discuss the benefits of using inheritance. Discuss multiple
inheritance with suitable example.(1+2+7)[2074]
Inheritance is a mechanism in which one class inherits the properties and features of
another class. Inheritance represents IS-A relationship. In inheritance, a new class
called child class or sub class is created based on existing classes (called parent class)
in order to inherit the existing classes’ features and properties. In the new class, new
methods and fields can also be added. With the use of inheritance, the information is
made manageable in a hierarchical order. A class that is derived from another class is
Subclass. The class from where a subclass inherits the features is called
superclass/base class/parent class.
Inheritance uses the concept of the code reusability. It allows to use the field
and method of the existing class in the new class. Reusing the existing code saves time
and money and increases the program’s reliability.
Syntax for deriving a subclass from existing class:
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword is used to inherit the properties of class. The meaning of
“extends” is to increase the functionality.
Types of inheritance
1. Single inheritance
2. Multiple Inheritance
3. Hierarchical inheritance
4. Multilevel inheritance
1. Single inheritance:
In multiple inheritance, a class is derived from more than one existing classes. Java
does not support. The multiple inheritance. In Java, multiple inheritance
can be implemented by interface.
3. Hierarchical inheritance
In hierarchical inheritance, two or more classes inherit the properties of one existing
class. Two or more classes are derived from one base class.
Example:
4. Multi-level inheritance
Interface
Q. Differentiate class with interface.[5][2076]
Q. Describe the responsibility of Serializable interface.
Q. Define inheritance. Discuss the benefits of using inheritance. Discuss multiple
inheritance with suitable example.(1+2+7)[2074]
Q. Why multiple inheritance is not allowed in Java using classes? Give an example.(5)
[2077]
@Override @Override
public double getArea() public double getPerimeter()
{ {
return Math.PI * return 2 * (length + width);
radius * radius; }
} }
C++, and commonly other languages supports multiple inheritance using purely only
the classes. While java doesn’t support it. Java doesn’t allow multiple inheritance
because it can lead to several ambiguity problems. One of such problem is the
“diamond problem” that occurs during multiple inheritance in Java. So, to avoid such
problem Java does not support multiple inheritance.
Diamond problem
The diamond problem arises when a class inherits from two or more classes that have
a common superclass and those two inherited classes also have a common method
with the same signature.
We will discuss this problem with the help of the diagram given
alongside. The figure shows multiple inheritance because Class
D extends both classes B & C. And, classes B and C both are
derived from class A.
Now let’s assume we have a method in class A and class B &C
overrides that method in their own way. Now here, since D is
extending both B & C, so, if D wants to access that method then
D will be unsure or undecidable which method to call (either the
overridden method in B or the overridden method in C). This is the Ambiguity problem
which can cause the compiler to be unable to decide which method implementation to
use. That’s the main reason why Java doesn’t support multiple inheritance.
Example of diamond problem
class C extends A
class A {
{ public void foo() {
public void foo() { System.out.println("C.foo()");
}
System.out.println("A.foo()"); }
} class D extends B, C // compile error: can’t inherit
} from multiple classes
{
class B extends A public static void main(String[] args)
{ {
public void foo() { D d = new D();
d.foo(); // ambiguous call to foo() method
System.out.println("B.foo()"); }
} }
}
In this example, classes B and C both inherit from class A and override the foo()
method. Class D tries to inherit from both classes B and C, but this is not
allowed in Java as it does not support multiple inheritance and here if we try
to compile this code, compiler throws an error: "cannot inherit from multiple
classes".
Way of achieving multiple inheritance in java:
In Java, multiple inheritance can be achieved through interfaces.
In Java, a class can extend only one class but not more than one classes which is
because java does not support multiple inheritance. But, an interface can extend from
one or many interfaces. Similarly, one class can extend any number of interfaces. This
is how we can achieve multiple inheritance in java using interfaces.
Example:
interface A public class Main {
{ public static void main(String[]
void methodA(); args) {
} MyClass myClass = new
interface B MyClass();
{ myClass.methodA();
void methodB(); myClass.methodB();
} }
class MyClass implements A, B }
{
public void methodA() {
System.out.println("methodA()
called");
}
public void methodB() {
System.out.println("methodB()
called");
}
}
Interface Vs Class
1. Final Modifier
The final modifier in java can be used with classes, method and member variables. To
use it, just write final in beginning of variable, method or class. It is used to restrict the
user. It means that, the variable, class or a method with final modifier keyword makes
that the programmer cannot modify or change the value anymore. The actual meaning
depends on whether it is applied to a class, a variable, or a method. The final modifier
is used for following purposes:
a. To define constants (final keyword when used with variable)
Final keyword is used with variable to declare them as a constant. Once the value is
assigned to final variable, it cannot be changed during the runtime.
Example:
public class Circle{ void area()
private final float pi=3.14; {
private int r; float a=pi*r*r;
Circle(int x) System.out.println(“area”,a);
{ }
Pi=3.1; //cannot be changed }
because Pi is
//defined as final.
r=x;
}
2. Static Modifier
Static variables and methods belong to the class rather than an instance of the class.
In Java, the static modifier is used to declare a variable, method, or inner class as a
class-level entity rather than an instance-level entity. When a variable or method is
declared as static, it belongs to the class as a whole, and there is only one copy of it
regardless of how many objects of that class are created.
a. Static variables: A static variable is shared by all instances of the class. If a
value is assigned to a static variable, it becomes available to all instances of the
class, and any modification to it will be reflected across all instances.
b. Static methods: A static method can be called directly on the class without
creating an instance of the class. This is useful when you need to perform a task
that doesn't require any object-specific state.
c. Static blocks: A static block is used to initialize the static variables or perform
any other static initialization tasks. It is executed once when the class is loaded
into memory, before any instances of the class are created.
d. Static inner classes: A static inner class is a nested class that is declared as
static. It can be accessed without creating an instance of the enclosing class,
and it cannot access non-static members of the enclosing class.
3. Abstract modifier
In Java, the abstract modifier is used to declare a class or method that has no
implementation and must be implemented by a subclass. Abstract classes cannot be
instantiated directly, and can only be used as a base class for other classes that extend
them. Abstract methods must be overridden by a subclass to provide a concrete
implementation.
Here are some key features of abstract classes and methods in Java:
a. Abstract classes: An abstract class is a class that is declared using the abstract
keyword and has at least one abstract method. Abstract classes can have both
abstract and non-abstract methods, and can also have variables, constructors,
and static methods. However, abstract classes cannot be instantiated directly,
and can only be used as a superclass for other classes that extend them.
d. Benefits: The main benefit of using abstract classes and methods is that they
allow for greater flexibility and code reuse in object-oriented programming.
Abstract classes provide a common interface for a group of related classes, while
abstract methods allow subclasses to provide their own implementation of a
method while adhering to a common interface.
// Inner class
public class InnerClass
{
public int getX( ){
return x;
}
}
Packages
Related classes can be bundled together in a collection called a package. Packages are
containers for similar classes that helps programmer to manage different classes.
When we create any Java program the java.lang package is imported by default. We
need not to write the package name at the top of the program.
The main advantages of using a package are that it helps you to organize your work
because:
You can set the control over access to the components of a package.
Packages helps to manage classes and hence the searching/locating and usage
of classes, interface etc. are simplified.
You can enlarge the "name space", and prevents naming conflicts: for example,
the Vector class in one package, java.util package differs from the Vector class
in another package, NL.uva.wins.datastructures.
It simplifies the naming of classes, For example: after importing the java.awt
class you can use short names like Button and TextField instead of the full
names java.awt.Button and java.awt.TextField, respectively.
Packages are stored in a hierarchical manner and are explicitly imported into new class
definitions. Some of the existing packages in Java are: java.lang, java.io etc.
Creating a Package
When creating a package, you should choose a name for the package and put a
package statement with that name at the top of every classes source files that you
want to include in that package. the package statement should be in the first line of
the source file.
Creating a package in Java involves the following steps:
1. Choose a suitable package name for your package according to the naming
convention. This name should be in lowercase letters and separated by dots if it
contains multiple words. For example, if you are creating a package for a
calculator program, you could name the folder "com.mycompany.calculator".
2. Create a package: Create a new folder for your package with the package name.
3. Create your Java classes: Create one or more Java classes which you want to
include in your package.
4. Add the package declaration: For including classes in your package, add the
package declaration at the top of each Java class file, to specify which package
the class belongs to. For example, if your package name is
"com.mycompany.calculator", you would add the following line to the top of your
Java class:
package com.mycompany.calculator;
Example: In this example, we have a class named MyClass that is included in the
myapp package.
package com.example.myapp;
public class MyClass
{
public void display(){ //must be public to get accessed from
another package
System.out.println("Hello, world!");
}
public static void main(String[] args)
{
MyClass c=new MyClass();
c.display();
}
}
There are two main ways of accessing classes in another package. One way is to add
the full package name in front of every class name.
Example:
jav.util.Date today=new java.util.Date()
Another is using the import keyword to import a specific class or whole package. The
import statement will be given at the top of the file just below the package statement.
‘
Example:
import java.util.*;
Date today= new Date();
Different way of accessing the package
1. Importing a Single Class of a package: The statement import java.lang.String;
imports the class String from the java.lang package (Here lang is inner package
which lies inside java package). After this statement, the signature of the
getDisplayCustom method can be defined by
public void getDisplayCustom(String g){ }
instead of by
public void getDisplayCustom(java.lang.String g){ }
2. Importing All Classes inside a package: If you want to import all the classes
and interfaces from a package, for instance, the entire java.lang package, use the
import statement with the asterisk (*) wildcard character.
import java.lang.*;
Importing all classes of a package may slow down compilation, but has no other
effects on efficiency.
Example:
Import myapp.*; //must import myapp.* which means all in myapp to
access //classes in it.
public class NextClassOfNextPackage
{
public static void main(String[] args)
{
System.out.println("I am next class of next package");
MyClass a=new MyClass(); //You can instantiate class of
imported package.
a. display(); //You can use method of imported package’s class
using its
//object.
}
}
PART 3
Exception Handling
What is exceptional handling and why it should be handled?
Exceptions are unexpected events that disrupt the normal flow of program execution,
such as division by zero, null pointer exceptions, and file I/O errors. Exception handling
is a mechanism in Java that allows developers to handle and recover from runtime
errors and exceptions that occur during program execution, while keeping the
application’s normal flow intact. The good thing about exception handling is that java
developer can handle the exceptions in such a way so that the program doesn’t get
terminated suddenly and the user get a meaningful error message.
An exception can occur for many reasons. Some of them are:
If we want to access the array index which is out of range or size of array.
Opening an unavailable file
Loss of network connection during network related task
Invalid SQL query operation
Invalid arithmetic operations such as divide by zero case
Invalid user input like invalid type input
Device/hardware failure
The java.lang.Throwable class is the root class of Java Exception hierarchy which is
inherited by two subclasses: Exception and Error. The hierarchy of Java Exception
classes is given below:
In Java, there are several keywords that are used in exceptional handling. Here are
some of the basic keywords:
a. try: The try block contains the code that may throw an exception.
b. catch: The catch contains the code that handles the exception thrown by try
block. Catch block catches the exception and handles it appropriately. It is
followed by the type of exception that it can catch.
c. finally: The finally block is used to execute code after the try block, regardless
of whether an exception is thrown or not. Code inside finally block is always
executed regardless either exception occurs or not in try block. This block is
typically used to clean up resources, such as closing files or database
connections.
2. throw: The throw keyword is used to manually throw an exception. This is useful
when you need to handle a specific exception case or when you want to create your
own exception class.
3. throws: The throws keyword is used to declare the exceptions that a method may
throw. This allows the calling code to handle the exception appropriately.
4. finally: The finally block is used to define a set of statements that will be executed
after the execution of the try and catch blocks, regardless of whether an exception
is thrown or not. The finally block is often used for releasing resources or cleaning
up after the try block.
5. Multiple catch blocks: In some cases, a single try block may throw multiple types of
exceptions. In this case, multiple catch blocks can be used to handle each exception
type differently.
6. Custom Exception Classes: Custom exception classes can be created to handle
specific types of exceptions that are not covered by the built-in exception classes.
This allows for more specific and customized exception handling.
1. try-catch blocks
Java provides a structured way to handle exceptions using try-catch blocks. The try
block includes the code that might generate an exception. The catch block includes the
code that is executed when there occurs an exception inside the try block and the
catch block catches the exception and handles it appropriately.
try{
//code
}
catch(exception) {
// code
}
Example:
import java.*;
public class TryCatchDemo
{
public static void main(String[] args)
{
try {
int d = 5 / 0;
System.out.println("Print" + d);
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " +
e.getMessage());
//or, simply you can handle as:
//System.out.println("Cannot divide by zero”);
}
}
}
2. try-finally blocks
Example:
public class TryWithFinally
{
public static int method()
{
try {
System.out.println("Try Block with return type");
return 10;
} finally {
System.out.println("Finally Block always execute");
}
}
public static void main(String[] args)
{
System.out.println(method());
}
}
try {
System.out.print("Enter the numerator: ");
int numerator = input.nextInt();
When you need to perform clean-up operations: The finally block can be used to
clean up or reset the state of your program. For example, if you are working
with a database, you might want to close the database connection in the finally
block to ensure that it is always closed, even if an exception is thrown.
When you need to perform final actions: If you need to perform some final
actions before exiting the program, such as logging or sending a notification, you
can use the finally block to do this. This is particularly useful in long-running
programs that need to be shut down gracefully.
In summary, the finally block is not always mandatory when handling exceptions, but it
is useful in situations where you need to release resources, perform clean-up
operations, or perform final actions.
The throw keyword is used to manually throw an exception. This is useful when you
need to handle a specific exception case or when you want to create your own
exception class.
The Java throw keyword is used to throw an exception explicitly or manually. We
specify the exception object which is to be thrown. The Exception has some message
with it that provides the error description. These exceptions may be related to user
inputs, server, etc.
Syntax for Java Throw keyword is given below:
throw new exception_class(“error message”);
Example
Throw an exception if age is below 18 (print “Access denied”). If age is 18 or older,
print “Access granted”:
5. Java throws keyword
In Java, the throws keyword is used in method signatures to indicate that the method
may throw one or more types of exceptions. When a method is declared with the
throws keyword, the calling code is required to handle or propagate any checked
exceptions that the method may throw.
Example:
public void readFile(String filename) throws IOException
{
// code to read a file
}
In this example, the readFile method takes a filename as input and may throw an
IOException if an error occurs while reading the file. By including the throws keyword
in the method signature, we are indicating to the calling code that it must handle or
propagate the IOException if it is thrown.
It's important to note that if a method declares that it throws a checked exception, the
calling code must handle or propagate the exception. This can be done by either
catching the exception with a try-catch block or declaring the exception with the throws
keyword in the calling method's signature. If the exception is not handled or
propagated, the compiler will generate an error.
Example:
public class Example {
public static int divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
return a / b;
}
public static void main(String[] args) {
try {
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
}
Example:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
In this example, we use the InvalidInputException class to indicate that the user input
is invalid. If the input is less than zero, we throw a new InvalidInputException with a
descriptive error message. In the main method, we catch this exception and print the
error message to the console.
Note that when you define a user-defined exception class, you should provide a clear
and informative error message in the constructor. This will help developers diagnose
and fix problems more quickly. Additionally, you should only define new exceptions
when none of the existing exception classes are appropriate for your specific use case.
Difference between throw and throws
Concurrency
Concurrency is the ability of a program to execute multiple tasks simultaneously. In
Java, there are several ways to achieve concurrency. The most approach to achieve
concurrency in Java is threads.
Threads
One of the simplest ways to achieve concurrency in Java is through threads. A thread
is a lightweight process that runs within a larger process. By creating multiple threads
within a program, each thread can execute a different task simultaneously. Java
provides a Thread class and Runnable interface to create and manage threads. For
example= A word processor can have one thread running in foreground as an editor
and another in the background auto saving the document!
In Java thread programming, multithreading is a process by which we can execute
multiple threads simultaneously.
Advantages of threads:
This leads to maximum utilization of CPU.
Multithreading is used to achieve multitasking.
The path of execution of each thread is different, And they are independent so that
even if an exception comes in one thread, it does not affect other threads.
A multithreaded program contains two or more parts that run simultaneously. Each
part of such a program is called a thread. It is mostly used to create games and
animations.
Types of threads:
There are two types of thread in this. First user thread and second daemon thread.
Daemon threads are used when we want to clean the application and they are used in
the background.
Old questions
i. What is package? How can you create your own package in Java? Explain with
example. (1+4) [2078]
ii. Describe the responsibility of Serializable interface. Write a program to read an
input string from the user and write the vowels of that string in VOWEL.TXT and
consonants in CONSOLNANT.TXT (2+8) [2077]
iii. A non-empty array A of length n is called on array of all possibilities if it contains
all numbers between 0 and A.length-1 inclusive. Write a method named
isAllPossibilities that accepts an integer array and returns 1 if the array is an
array of all possiblities, otherwise it returns 0. (5)[2077]
iv. When does the finally block is mandatory in while handling exception? Describe
with a suitable scenario. (5)
[2077]
v. What is the task of manifest file? Write the procedure to create it. [2 + 3][2077]
vi. Why multiple inheritance is not allowed in Java using classes? Give an example.
(5)[2077]
vii. Why synchronization in essential in multithreading? Describe. (5)[2077]
viii. Write short notes on. [2.5+2.5][2077]
a. JAVA beans and JAR file
b. MVC design pattern
ix. Why do we need to handle the exception? Distinguish error and exception, Write
a program to demonstrate your own exception class. [1+2+7]
[2075]
x. An array is called balanced if it's even numbered elements (a[0], a[2], etc.) are
even and its odd numbered elements (a[1], a[3],etc.) are Odd. Write a function
named is Balanced that accepts an array of integers and returns 1 if the array is
balanced otherwise it returns 0. [5][2075]
xi. Define the chain of constructor. What is the purpose of private constructor? [5]
[2075]
xii. Write down the life cycle of thread. Write a program to execute multiple threads
in priority base. [2+3][2075]
xiii. When do we use final method and final class? Differentiate between function
overloading and function overriding.[2+3][2075]
xiv. Give any two differences between class and bean. Write the steps to create JAR
files. [2+3][2075]
xv. What is exception handling? Discuss the use of each keyword (try, catch, throw,
throws and finally) with suitable Java program.[2076]
xvi. Define class. How do you create a class in Java? Differentiate class with
interface.[5][2076]
xvii. Write a simple Java program that reads a file named "Test.txt" and displays its
contents.[5][2076]
xviii. Discuss MVC design pattern with example.[5][2076]
xix. Define Java Bean. How is it different from other Java programs? What is design
pattern?[5][2076]
xx. Define inheritance. Discuss the benefits of using inheritance. Discuss multiple
inheritance with suitable example.(1+2+7)[2074]
xxi. .Write an object oriented program to find area and perimeter of rectangle. (5)
[2074]
xxii. 5. Write a simple java program that reads data from one file and writes the data
to another file (5) [2074]
xxiii. Describe multithreading in Java.(5)[2074]
xxiv. What is multithreading? How can you write multithreaded programs in java?
Discuss with suitable example.(10)[2073]
xxv. Write an object oriented program to find the area and perimeter of rectangle.(5)
[2073]
xxvi. Write the simple java program that reads data from one file and writes data to
another file.(5)[2073]
xxvii. What is exception handling? Discuss exception handling in detail with suitable
example. (10)[2071]