Java Lab Manual - Final
Java Lab Manual - Final
INDEX
[Link] CONTENTS
1 VISION/MISION
2. PEO
3. POS
4. COS
5. MAPPING OF CO & PO
6. SYLLABUS
7. BOOKS
8. INSTRUCTIONAL METHODS
9. LEARNING MATERIALS
dimensional array
3. Write a java program to perform Matrix Multiplication
and Transpose of a Matrix
1. Vision
4|Page
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
To become renowned Centre of excellence in computer science and engineering and make
competent engineers & professionals with high ethical values prepared for lifelong learning.
Mission
M1: To impart outcome based education for emerging technologies in the field of
computer science and engineering.
M2: To provide opportunities for interaction between academia and industry.
M3: To provide platform for lifelong learning by accepting the change in technologies
M4: To develop aptitude of fulfilling social responsibilities.
2. PEO
[Link] provide students with the fundamentals of Engineering Sciences with more emphasis in
Computer Science &Engineering by way of analyzing and exploiting engineering challenges.
2. To train students with good scientific and engineering knowledge so as to comprehend,
analyze, design, and create novel products and solutions for the real life problems.
3. To inculcate professional and ethical attitude, effective communication skills, teamwork
skills, multidisciplinary approach, entrepreneurial thinking and an ability to relate engineering
issues with social issues.
4. To provide students with an academic environment aware of excellence, leadership, written
ethical codes and guidelines, and the self-motivated life-long learning needed for a successful
professional career.
5. To prepare students to excel in Industry and Higher education by Educating Students along
with High moral values and Knowledge
[Link]
• Engineering Knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems in IT.
• Problem analysis: Identify, formulate, research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences in IT.
• Design/development of solutions: Design solutions for complex engineering problems
and design system components or processes that meet the specified needs with
appropriate consideration for the public health and safety, and the cultural, societal, and
environmental considerations using IT.
5|Page
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
4. CO
5. MAPPING OF CO & PO
6|Page
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
Semester Subject Code L/T/P CO
1.
Develop
an in
JAVA depth
understan
ding of
program
P H H H H M L - - M L L M
ming &
apply by
writing
Object
Oriented
PROGR programs
AMMIN in Java
G
[Link]
tand &
IV 4CS4-25 Develop
packages
,
P Interfaces H H H H M L - - M L L M
, Strings
and
exception
handling
in Java
LAB
3. Create
applicatio
ns
involving
P file H H H H M L - - M L L M
handling,
concurre
ncy and
applet
6. SYLLABUS
7|Page
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
List of Experiment:
1. Develop an in depth understanding of programming in Java: data types, variables,
operators, operator precedence, Decision and control statements, arrays, switch
statement, Iteration Statements, Jump Statements, Using break, Using continue,
return.
2. Write Object Oriented programs in Java: Objects, Classes constructors, returning
and passing objects as parameter, Inheritance, Access Control, Using super, final
with inheritance Overloading and overriding methods, Abstract classes, Extended
classes.
3. Develop understanding to developing packages & Interfaces in Java: Package,
concept of CLASSPATH, access modifiers, importing package, Defining and
implementing interfaces.
4. Develop understanding to developing Strings and exception handling: String
constructors, special string operations, character extraction, searching and comparing
strings, string Buffer class. Exception handling fundamentals, Exception types,
uncaught exceptions, try, catch and multiple catch statements. Usage of throw,
throws and finally.
5. Develop applications involving file handling: I/O streams, File I/O.
6. Develop applications involving concurrency: Processes and Threads, Thread
Objects, Defining and Starting a Thread, Pausing Execution with Sleep, Interrupts,
Joins, and Synchronization. Indicative List of exercises:
7. Programs to demonstrate basic concepts e.g. operators, classes, constructors,
control & iteration statements, recursion etc. such as complex arithmetic, matrix
arithmetic, tower of Hanoi problem etc.
8. Development of programs/projects to demonstrate concepts like inheritance,
exception handling, packages, interfaces etc. such as application for electricity
department, library management, ticket reservation system, payroll system etc.
9. Development of a project to demonstrate various file handling concepts.
10. Develop applications involving Applet: Applet Fundamentals, using paint
method and drawing polygons. It is expected that each laboratory assignments to
given to the students with an aim to In order to achieve the above objectives.
7. BOOKS:-
8|Page
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
Text books:-
Reference Books:-
8. INSTRUCTIONAL METHODS:-
8.1. Direct Instructions:
• Coding
• Problem solving
9. LEARNING MATERIALS:-
9|Page
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
INSTRUCTIONS OF LAB
DO’s
DON’Ts
Don’t mishandle the system.
Don’t leave the system on standing for long.
Don’t bring any external material in the lab.
Don’t make noise in the lab.
Don’t bring the mobile in the lab. If extremely necessary then keep ringers off.
10 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
• All the students are supposed to prepare the theory regarding the next program.
• Students are supposed to bring the practical file and the lab copy.
• Previous programs should be written in the practical file.
• Any student not following these instructions will be denied entry in the lab.
11 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
Assignment 1
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Any entity that has state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical. An Object can be defined as an instance of a
class. An object contains an address and takes up some space in memory. Objects can
communicate without knowing the details of each other's data or code. The only necessary thing
is the type of message accepted and the type of response returned by the objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
Class
Collection of objects is called class. It is a logical entity. A class can also be defined as a
blueprint from which you can create an individual object. Class doesn't consume any space.
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
etc. In Java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something; for example, a cat speaks meow, dog barks woof,
etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example phone
call, we don't know the internal processing. In Java, we use abstract class and interface to
achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation.
For example, a capsule, it is wrapped with different medicines. A java class is the example of
encapsulation. Java bean is the fully encapsulated class because all the data members are
private here.
Basic was gaining in popularity and usage but as someone said: "People program in VB not
because they like programming in Basic, but because of VB's fancy interface." Several other
languages such as a da, Smalltalk and 4GLs such as Natural had their adherents in industry
and academia, but there was still a definite sense of unrest.
Java therefore turned out to be the right language at the right time, just as the other strong
languages - Fortran, Cobol, Pascal and C++ - were. Continuing this analogy, one could say
that Ada and Small talk were the wrong languages for their time. Ada, for all its excellent
points, always felt as if it was behind the trends, and Small talk,
For all its failings, was ahead of the pack in many ways. To gain wide acceptance, a language
has to get things just right. In essence it needs to:
• espouse the paradigm of the day,
• add something new and significant,
• be readily available.
Java was able to achieve all three. It is firmly object-oriented (currently the major paradigm);
it broke new ground in its use of the Internet and browsers as an execution base; and it was
immediately downloadable for free. It is evident that Java has become a language of choice
among commercial developers of new systems, and those needing to give old systems a face-
lift in the Web age (Java Soft, 1997). It is also clear that teaching institutions are switching
over to Java in large numbers, or considering doing so (Schaller, 1997).
14 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
classcalculator{
public static void main(String args[]){
Scanner input = new Scanner([Link]);
[Link]("Enter a ");
Scanner a = [Link]();
[Link] ("Enter b ");
Scanner b = [Link]();
[Link](a+b);
[Link](a-b);
[Link](a*b);
[Link](a/b);
[Link](a%b);
}}
OUTPUT-
15
50
15 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
Assignment 2
import [Link];
publicclass Ascending _Order
{
publicstaticvoid main(String[] args)
{
int n, temp;
Scanner s = newScanner([Link]);
[Link]("Enter no. of elements you want in array:");
n = [Link]();
int a[] = newint[n];
[Link]("Enter all the elements:");
for (int i = 0; i < n; i++)
{
a[i] = [Link]();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
[Link]("Ascending Order:");
for (int i = 0; i < n - 1; i++)
{
[Link](a[i] + ",");
}
[Link](a[n - 1]);
}
}
Output:
Ans. Java array is an object which contains elements of a similar data type. It is a data structure
where we store similar elements. We can store only a fixed set of elements in a Java array. Array
in java is index-based, the first element of the array is stored at the 0 index.
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in Java which grows
automatically.
Code-
// return -1
class GFG {
17 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
int n = [Link];
if(arr[i] == x)
return i;
return -1;
intarr[] = { 2, 3, 4, 10, 40 };
int x = 10;
[Link](arr);
if (result == -1)
else
}}
c = new int[m][q];
t = new int[q][m];
Scanner s = new Scanner([Link]);
[Link]("Enter the elements of matrix A: ");
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
a[i][j] = [Link]();
}
}
[Link]("Enter the elements of matrix B: ");
for(int i = 0; i < p; i++){
for(int j = 0; j < q; j++){
b[i][j] = [Link]();
}
}
for(int i = 0; i < m; i++){
for(int j = 0; j < q; j++){
for(int k = 0; k < n; k++){
c[i][j] += a[i][k]*b[k][j];
}
}
}
[Link]("Elements of result matrix C are: ");
for(int i = 0; i < m; i++){
for(int j = 0; j < q; j++){
[Link](c[i][j]+"\t");
}
[Link]("\n");
}
for(int i = 0; i < q; i++){
for(int j = 0; j < m; j++){
t[i][j] = c[j][i];
}
}
[Link]("Elements of transpose matrix T are: ");
for(int i = 0; i < q; i++){
for(int j = 0; j < m; j++){
19 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
[Link](t[i][j]+"\t");
}
[Link]("\n");
}
}
}
class Driver{
public static void main(String[] args){
Scanner s = new Scanner([Link]);
[Link]("Enter no of rows in first matrix: ");
int m = [Link]();
[Link]("Enter no of columns in first matrix: ");
int n = [Link]();
[Link]("Enter no of rows in second matrix: ");
int p = [Link]();
[Link]("Enter no of columns in second matrix: ");
int q = [Link]();
if(n == p){
Matrix obj = new Matrix();
[Link](m,n,p,q);
}
else{
[Link]("Matrix multiplication cannot be
performed...");
}}}
OUTPUT-
Enter no of rows in first matrix:
3
Enter no of columns in first matrix:
3
Enter no of rows in second matrix:
3
Enter no of columns in second matrix:
3
Enter the elements of matrix A:
111
222
20 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
333
Enter the elements of matrix B:
123
123
111
Elements of result matrix C are:
3 5 7
6 10 14
9 15 21
Elements of transpose matrix T are:
3 6 9
5 10 15
7 14 21
Assignment 3
21 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
classLamp{
booleanisOn;
voidturnOn(){
// initialize variable with value true
isOn=true;
[Link]("Light on? "+isOn);
}
voidturnOff(){
// initialize variable with value false
isOn=false;
[Link]("Light on? "+isOn);
}
}
classMain{
publicstaticvoid main(String[]args){
2. Write a java program to implement class and object concept using Scanner class
class abc1{
void display()
{
Scanner input = new Scanner([Link]);
[Link]("Enter a ");
Scanner a = [Link]();
[Link]("Enter b ");
Scanner b = [Link]();
22 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
int z=a+b;
[Link]("The sum of two numbers is" + z);
}
}
Public class Main
{
public static void main(String args[]){
abc a1=new abc1();
[Link]();
}
OUTPUT - Enter a
10
Enter b
5
The sum of two number is 15
Assignment 4
Ans. Operator in java is a symbol that is used to perform operations. For example: +,
-, *, / etc. There are many types of operators in java which are given below:
Unary Operator , Arithmetic Operator, Shift Operator, Relational Operator, Bitwise
Operator, Logical Operator, Ternary Operator and Assignment Operator.
Code-
classoper{
public static void main(String args[]){
int a=10;
int b=5;
[Link](a+b);
[Link](a-b);
[Link](a*b);
[Link](a/b);
[Link](a%b);
}}
OUTPUT- 15
5
50
2
0
2. Write a java program to implement decision making and control statements using
break and continue keywords
Ans .
The switch statement is a multiway branch statement. It provides an easy way to
dispatch execution to different parts of code based on the value of the expression.
Code-
classSwitchCaseDemo
{
public static void main(String args[])
{
int i = 9;
switch (i) {
case 0:
[Link]("i is zero.");
break;
case 1:
[Link]("i is one.");
break;
24 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
case 2:
[Link]("i is two.");
break;
default:
[Link]("i is greater than 2.");
}}}
OUTPUT - i is greater than 2.
Break –
The break statement in Java programming language has the following two usages −
When the break statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement
Code-
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
break;
}
[Link]( x );
[Link]("\n");
}}}
OUTPUT -
10
20
Continue –
The continue keyword can be used in any of the loop control structures. It causes the
loop to immediately jump to the next iteration of the loop. In a for loop, the continue
keyword causes control to immediately jump to the update statement.
3. Write a java program to implement iteration statements in java using break and
continue keywords
In a while loop or do/while loop, control immediately jumps to the Boolean
expression.
Code-
public class Test {
25 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
26 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
[Link](20,30)
[Link](10,10)
[Link](10,10)
}}
OUTPUT - The sum of two no. is 30
The subtraction of two no. is -10
The multiply of two no. is 100
The division of two no. is 1
class C
{
publicvoiddisp()
{
[Link]("C");
}
}
class A extends C
{
publicvoiddisp()
{
[Link]("A");
}
}
class B extends C
{
publicvoiddisp()
{
[Link]("B");
}
class D extends A
{
publicvoiddisp()
{
[Link]("D");
27 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
}
publicstaticvoid main(Stringargs[]){
D obj=newD();
[Link]();
}
}
Output:
D
Assignment 5
28 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
Interface looks like a class but it is not a class. An interface can have methods and variables just
like the class but the methods declared in interface are by default abstract (only method
signature, no body, see: Java abstract method). Also, the variables declared in an interface are
public, static & final by default.
interfaceMyInterface
{
/* compiler will treat them as:
* public abstract void method1();
* public abstract void method2();
29 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
*/
publicvoid method1();
publicvoid method2();
}
classDemoimplementsMyInterface
{
/* This class must have to implement both the abstract methods
* else you will get compilation error
*/
publicvoid method1()
{
[Link]("implementation of method1");
}
publicvoid method2()
{
[Link]("implementation of method2");
}
publicstaticvoid main(Stringarg[])
{
MyInterfaceobj=newDemo();
obj.method1();
}
}
Output:
implementation of method1
30 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
}
staticint add(double a, double b, double c){
return (int)(a+b+c);
}}
class over{
public static void main(String args[ ]) {
[Link]([Link](31,19));
[Link]([Link](31,19,10));
}}
Output -
50
60
31 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
Assignment 6
2- Java String class provides a lot of methods to perform operations on string such as
compare(), concat(),
equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
· How to create a string object?
There are two ways to create String object:
· By string literal
· By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
· String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If
the string already exists in
the pool, a reference to the pooled instance is returned. If the string doesn't exist in the
pool, a new string instance is
created and placed in the pool. For example:
· String s1="Welcome";
· String s2="Welcome"
2) By new keyword
String s=new String("Welcome");//creates two objects and one reference variabl
32 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
In such case, JVM will create a new string object in normal (non-pool) heap memory, and
the literal "Welcome"
will be placed in the string constant pool. The variable s will refer to the object in a heap
(non-pool).
33 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
[Link](s);
OUTPUT-:
AMIT
Amit
Amit
34 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
String s4="Saurav";
[Link]([Link](s2));//true
[Link]([Link](s3));//true
[Link]([Link](s4));//false
}
}
Output:
true
true
false
Output:
true
false
3) String compare by compareTo() method
The String compareTo() method compares values lexicographically and returns an integer
value that describes if
first string is less than, equal to or greater than second string.
Suppose s1 and s2 are two string variables. If:
· s1 == s2 :0
· s1 >s2 :positive value
· s1 <s2 :negative value
class Teststringcomparison4{
public static void main(String args[]){
35 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
[Link]([Link](s2));//0
[Link]([Link](s3));//1(because s1>s3)
[Link]([Link](s1));//-1(because s3 < s1 )
}
}
Output:
0
1
-1
3 String class overrides the StringBuffer class doesn't override the equals()
equals()method of Object method of Object class
class. So you cancompare the
contents of two stringsby
equals() method.
36 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
}
return t;
}
public static String concatWithStringBuffer(){
StringBuffersb = new StringBuffer("Java");
for (int i=0; i<10000; i++){
[Link]("Tpoint");
}
[Link]();
}
public static void main(String[] args){
longstartTime = [Link]();
concatWithString();
[Link]("Time taken by Concating with String: "+
([Link]()-
startTime)+"ms");
startTime = [Link]();
concatWithStringBuffer();
[Link]("Time taken by Concating with StringBuffer:
"([Link]()-
startTime)+"ms");
}
}
Output-:
Time taken by Concating with String: 578ms
Time taken by Concating with StringBuffer: 0ms
37 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
“thread of execution” when one process is divided into sub-tasks. Each smaller task does
not hijack the CPU until it finishes like in the older multiprogramming but rather a fair
share amount of the CPU time called quantum.
Just to make it easy to remember, both multiprogramming and multitasking operating
systems are (CPU) time sharing systems. However, while in multiprogramming (older
OSs) one program as a whole keeps running until it blocks, in multitasking (modern OSs)
time sharing is best manifested because each running process takes only a fair quantum of
the CPU time.
Multiprogramming
In a multiprogramming system there are one or more programs loaded in main memory
which are ready to execute. Only one program at a time is able to get the CPU for
executing its instructions (i.e., there is at most one process running on the system) while
all the others are waiting their turn.
The main idea of multiprogramming is to maximize the use of CPU time. Indeed,
suppose the currently running process is performing an I/O task (which, by definition,
does not need the CPU to be accomplished). Then, the OS may interrupt that process and
give the control to one of the other in-main-memory programs that are ready to execute
(i.e. process context switching). In this way, no CPU time is wasted by the system
waiting for the I/O task to be completed, and a running process keeps executing until
either it voluntarily releases the CPU or when it blocks for an I/O operation. Therefore,
the ultimate goal of multiprogramming is to keep the CPU busy as long as there are
processes ready to execute.
Multithreading
Multithreading in java is a process of executing multiple threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing
and multithreading, both are used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared
memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.
Java Multithreading is mostly used in games, animation, etc.
Code -
class A extends Thread{
public void run(){
[Link]("thread is running ");
}
public static void main(String args[]){
38 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
2. Write a java program to create, start and run a thread using Runnable interface?
Ans. PROCESS-
An executing program is called a process.
Every process has its separate address [Link]-based multitasking allows a
computer to run two or more than two programs [Link] between
two processes is expensive and [Link] switching from one process to another
process is expensive.A process has its own address space, global variables, signal
handlers, open files, child processes, accounting [Link] are also called
heavyweight [Link]-based multitasking is not under the control of [Link] are
working on text editor it refers to the execution of a process.
THREAD -
A thread is a small part of a process.
All the threads of a process share the same address space cooperatively as that of a
[Link]-based multitasking allows a single program to run two or more threads
[Link] between two threads is less expensive as compared to
[Link] switching from one thread to another thread is less expensive as
compared to process.A thread has its own register, state, stack, program [Link]
are also called lightweight [Link]-based multitasking is under the control of
[Link] are printing a file from text editor while working on it that resembles the
execution of a thread in the process.
Code -
class Run1 implements Runnable{
public void run(){
[Link]("thread is running ");
}
public static void main(String args[]){
A a1 = new A();
Thread obj = new Thread(a1);
[Link]();
}}
OUTPUT - thread is running
39 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
40 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
{[Link](300);}
catch(InterruptedException e) {[Link](e);}
[Link](i);
}}}
classnamecheck{
public static void main(String args[]){
String tn = [Link]().getName();
[Link](tn);
A obj1 = new A();
[Link]("Name of obj1:"+[Link]());
[Link]();
try{
[Link](); }
catch(Exception e){[Link](e);}
A obj2 = new A();
[Link]("obj3"));
[Link]("After changing name of obj2:"+[Link]());
[Link]();
} }
OUTPUT -
main
Thread-0
1
2
3
4
5
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The [Link] package contains all the
classes required for input and output operations.
We can perform file handling in Java by Java I/O API.
Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream
because it is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with the
console.
41 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
Output:
Success...
}
}
Note: Before running the code, a text file named as "[Link]" is required to be created. In
this file, we are having following content:
Welcome to javatpoint.
Assignment 7
Ans-
An exception (or exceptional event) is a problem that arises during the execution of a
program. When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios where
an exception occurs.
A network connection has been lost in the middle of communications or the JVM has run
out of memory.
Some of these exceptions are caused by user error, others by programmer error, and
others by physical resources that have failed in some manner.
Based on these, we have three categories of Exceptions. You need to understand them to
know how exception handling works in Java.
For example, if you use FileReader class in your program to read data from a file, if the
file specified in its constructor doesn't exist, then a FileNotFoundException occurs, and
the compiler prompts the programmer to handle the exception.
Example
[Link];
[Link];
Unchecked exceptions −An unchecked exception is an exception that occurs at the time
of execution. These are also called as Runtime Exceptions. These include programming
bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at
the time of compilation.
For example, if you have declared an array of size 5 in your program, and trying to call
the 6th element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs.
Example
public class Unchecked_Demo {
Output
Exception in thread "main" [Link]: 5
atExceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)
Errors −These are not exceptions at all, but problems that arise beyond the control of the
user or the programmer. Errors are typically ignored in your code because you can rarely
do anything about an error. For example, if a stack overflow occurs, an error will arise.
They are also ignored at the time of compilation.
Exception Hierarchy
All exception classes are subtypes of the [Link] class. The exception class is
a subclass of the Throwable class. Other than the exception class there is another subclass
called Error which is derived from the Throwable class.
Errors are abnormal conditions that happen in case of severe failures, these are not
handled by the Java programs. Errors are generated to indicate errors generated by the
runtime environment. Example: JVM is out of memory. Normally, programs cannot
recover from errors.
The Exception class has two main subclasses: IOException class and RuntimeException
Class.
45 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
Syntax
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}
The code which is prone to exceptions is placed in the try block. When an exception
occurs, that exception occurred is handled by catch block associated with it. Every try
block should be immediately followed either by a catch block or finally block.
A catch statement involves declaring the type of exception you are trying to catch. If an
exception occurs in protected code, the catch block (or blocks) that follows the try is
checked. If the type of exception that occurred is listed in a catch block, the exception is
passed to the catch block much as an argument is passed into a method parameter.
Example
The following is an array declared with 2 elements. Then the code tries to access the 3rd
element of the array which throws an exception.
// File Name : [Link]
import [Link].*;
46 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
Output
Exception thrown :[Link]: 3
Out of the blockst common checked and unchecked Java's Built-in Exceptions.
Multiple Catch Blocks
A try block can be followed by multiple catch blocks. The syntax for multiple catch
blocks looks like the following −
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}
The previous statements demonstrate three catch blocks, but you can have any number of
them after a single try. If an exception occurs in the protected code, the exception is
thrown to the first catch block in the list. If the data type of the exception thrown matches
ExceptionType1, it gets caught there. If not, the exception passes down to the second
catch statement. This continues until the exception either is caught or falls through all
catches, in which case the current method stops execution and the exception is thrown
down to the previous method on the call stack.
Example
Here is code segment showing how to use multiple try/catch statements.
try {
47 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
You can throw an exception, either a newly instantiated one or an exception that you just
caught, by using the throw keyword.
Try to understand the difference between throws and throw keywords, throws is used to
postpone the handling of a checked exception and throw is used to invoke an exception
explicitly.
Example
import [Link].*;
public class className {
48 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
Example
import [Link].*;
public class className {
Using a finally block allows you to run any cleanup-type statements that you want to
execute, no matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax −
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}
Example
public class ExcepTest {
Output
Exception thrown :[Link]: 3
First element value: 6
The finally statement is executed
As displayed in the above diagram, Applet class extends Panel. Panel class extends
Container which is the subclass of Component.
50 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
[Link] is painted.
[Link] is stopped.
[Link] is destroyed.
[Link] class
The Component class provides 1 life cycle method of applet.
public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.
51 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
//[Link]
[Link];
[Link];
public class First extends Applet{
}
Note: class must be public because its object is created by Java Plugin software that
resides on the browser.
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains applet tag in
comment and compile it. After that run it by: appletviewer [Link]. Now Html file is
not required but it is for testing purpose only.
//[Link]
[Link];
[Link];
public class First extends Applet{
}
/*
<applet code="[Link]" width="300" height="300">
52 | P a g e
Jaipur Engineering College and Research Centre,Jaipur
Department of Computer Science and Engineering
Java Programming Lab [4CS4 - 25]
</applet>
*/
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac [Link]
c:\>appletviewer [Link]
Method paint() is automatically called whenever there is a need to display the applet
window, this need could arise in certain situations -
When the applet window is brought up on the screen for the first time.
When the applet window is brought up on the screen from a minimized state, this leads
the redrawing of the applet window and hence paint() method is automatically called.
When the applet window is stretched to a new size, this leads to redrawing of applet
window to a new size and hence paint() method is automatically called.
Signature of paint() method
public void paint(Graphics g)
The method paint() gives us an access to an object of Graphics class type in our applet
code. Using the object of Graphics class, we can call drawString() method of Graphics
class to write a text message in the applet window.
Example -
import [Link].*;
[Link].*;
/*
<applet code="Applet24" width=400 height=200>
</applet>
*/
public class Applet24 extends Applet
{
String str ="";
{
str=str+"paint-";;
[Link](str,40,100);
[Link]("Hello from the Applet.", 40,40);
[Link]("How are you doing?", 40, 60);
[Link]("We wish you a pleasant day today.", 40, 80);
}
Output
54 | P a g e
Java applets are considered outdated in modern web development due to several factors: they require a browser plugin, which is not natively supported by many of today's browsers, increasing complexity for end-users. Additionally, applets run client-side, posing security risks. These drawbacks, along with the rise of more efficient and secure web technologies like HTML5, CSS3, and JavaScript, have led to the decline of Java applets in favor of more modern solutions .
Method overloading improves readability in Java by allowing multiple methods with the same name but different parameters to coexist. This makes the code more intuitive as the same method name can be used to perform the same action on different types or numbers of inputs, enhancing the program's understanding. Overloading keeps the operation context consistent rather than using different method names, thus improving the program's readability and maintainability .
The main potential drawback of a Java array is its fixed size, which limits its ability to accommodate dynamic storage requirements. This can be mitigated by using Java's collection framework, such as ArrayList or LinkedList, which provides dynamic arrays that can grow as needed during runtime .
The "String constant pool" in Java contributes to memory efficiency by storing only one copy of each distinct string literal in the pool, even if multiple variables reference the same literal. This approach reduces the amount of memory used for string operations, as it avoids creating unnecessary duplicates. When a new string literal is declared, the JVM checks the pool first, and if the literal already exists, it reuses the reference, thus optimizing memory utilization .
The finally block in Java is distinct from catch blocks because it always executes after the try and catch blocks, regardless of whether an exception was thrown or not. This guarantees that cleanup code runs consistently, making it ideal for releasing resources or closing connections. Unlike catch blocks, which handle specific exceptions, finally blocks do not handle exceptions but are used to ensure that the necessary cleanup occurs .
Checked exceptions in Java require programmers to handle potential errors explicitly, either by using a try-catch block or declaring the exception in the method signature with the 'throws' keyword. This enforces compile-time error checking, ensuring that errors are anticipated and managed properly. Conversely, unchecked exceptions are not checked at compile time, potentially leading to runtime errors if not anticipated. As a result, checked exceptions help in building more robust and reliable error handling mechanisms by promoting early detection and handling of exceptional conditions .
Polymorphism in Java is implemented through method overriding, where a subclass provides a specific implementation of a method that is already defined in its parent class. When a subclass object is referred to by a parent class reference, the overridden method in the subclass is invoked at runtime, allowing different behaviors for the same operation based on the object instance. This dynamic method dispatch mechanism is fundamental to achieving polymorphism in Java, enabling flexible and extensible program design .
The Java collection framework offers several advantages over traditional arrays: it provides dynamic storage, allowing collections to grow as needed, whereas arrays have a fixed size. Collections offer a rich set of methods for data manipulation, improved data abstraction, and enhanced performance for certain operations. However, arrays can be simpler and faster for basic operations where fixed size is sufficient. The choice between them depends on the specific needs for dynamism and the complexity of data manipulations required by the application .
Method overriding allows a subclass to provide a specific implementation of a method already defined in its superclass. This feature supports polymorphism in Java, enabling dynamic method dispatch. It allows objects to be treated as instances of their parent class but still execute overridden methods defined in the subclass. This enhances flexibility and code reusability, making systems more modular and easier to maintain and extend .
The Scanner class in Java provides a simple way to read input of various types directly from the console, making it accessible for beginners. However, it may not be as efficient for large-scale input operations due to its relatively slower processing speed compared to other methods like BufferedReader. BufferedReader uses buffering of input data, enabling faster reading of lines, making it more suitable for performance-critical applications. The choice between them depends on the specific requirements for input processing speed and ease of use .