0% found this document useful (0 votes)
6 views166 pages

42510_java_with_program (1)

Java is an object-oriented programming language known for its simplicity, security, portability, and robust features. It supports multi-threading, is architecture-neutral, and combines compilation and interpretation for high performance. The document also covers Java editions (J2ME, J2EE, J2SE), components like JVM, JRE, and JDK, as well as data types, tokens, operators, and control structures in Java.

Uploaded by

Vadukiya parag
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)
6 views166 pages

42510_java_with_program (1)

Java is an object-oriented programming language known for its simplicity, security, portability, and robust features. It supports multi-threading, is architecture-neutral, and combines compilation and interpretation for high performance. The document also covers Java editions (J2ME, J2EE, J2SE), components like JVM, JRE, and JDK, as well as data types, tokens, operators, and control structures in Java.

Uploaded by

Vadukiya parag
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/ 166

Q-1 Explain history and features of Java

Ans:
❖ Java is a programming language that:
1. Is exclusively object oriented
2. Has full GUI support
3. Has full network support
4. Is platform independent
5. Executes stand-alone or “on-demand” in web browser as
applets
Features:
1) Simple:
● Java inherits the C/C++ syntax and many of the object oriented
features of C++,
● Java supports OOP and does not support pointer which makes
it simpler.

2) Security:
● Java is best known for its security. With Java, we can develop
virus- free systems. Java is secured because:

o No explicit pointer
o Java Programs run inside a virtual machine sandbox

3) Portable:
● Java is portable because it facilitates you to carry the Java
bytecode

● to any platform. It doesn't require any implementation. It can be


implemented in any OS

4) Object-Oriented:

● Object-oriented programming (OOPs) is a methodology that simplifies


software development and maintenance by providing some rules.
● Basic concepts of OOPs are:

1) Object
2) Class
3) Inheritance
4) Polymorphism
5) Abstraction
6) Encapsulation

5) Robust (Healthy, Strong):

● It uses strong memory management.


● There is a lack of pointers that avoids security problems.
● Java provides automatic garbage collection which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
● There are exception handling and the type checking mechanism in Java.
All these points make Java robust.

6) Multi-threaded:
● A thread is like a separate program, executing concurrently. We can
write Java programs that deal with many tasks at once by defining.
7) Object-Oriented:

● Object-oriented programming (OOPs) is a methodology that


simplifies software development and maintenance by providing
some rules.
● Basic concepts of OOPs are:

7) Object
8) Class
9) Inheritance
10) Polymorphism
11) Abstraction
12) Encapsulation

8) Robust (Healthy, Strong):

● It uses strong memory management.


● There is a lack of pointers that avoids security problems.
● Java provides automatic garbage collection which runs on the Java
Virtual Machine to get rid of objects which are not being used by a Java
application anymore.
● There are exception handling and the type checking mechanism in Java.
All these points make Java robust.

9) Multi-threaded:
● A thread is like a separate program, executing concurrently. We
can write Java programs that deal with many tasks at once by
defining multiple threads. The main advantage of multi-threading is
that it doesn't occupy memory for each thread. It shares a common
memory area.

10) Architecture-neutral:
● Java is architecture neutral because there are no implementation
dependent features, for example, the size of primitive types is fixed.
● In C programming, int data type occupies 2 bytes of memory for 32-bit
architecture and 4 bytes of memory for 64-bit architecture. However, it
occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.

11) Interpreted:
● Usually a computer language is either compiled or interpreted. Java
combines these approaches thus making java a two-stage system.
● Java compiler translates source code into byte code instructions. Byte
codes are not machine instructions and so java interpreter generates
machine code that can be directly executed by the machine that is
running the java program.

12) High Performance:


● Java is faster than other traditional interpreted programming
languages because Java bytecode is "close" to native code.
● Java does not support pointer which increases the performance.

13) Distributed:
● Java is distributed because it facilitates users to create distributed
applications in Java. RMI and EJB are used for creating
distributed applications.

14) Dynamic:
● Java is a dynamic language. It supports the dynamic loading of classes.
It means classes are loaded on demand.

Q-2 Explain editions of


Java Ans:
1) Java Platform, Micro Edition (J2ME):

● Java ME, is designed for mobile phones (especially feature phones) and
set-top boxes. Java ME was formerly known as Java 2 Platform, Micro
Edition (J2ME).

● Java ME was designed by Sun Microsystems, acquired by Oracle


Corporation in 2010; the platform replaced a similar technology,
PersonalJava.

2) Java Platform, Enterprise Edition (J2EE):

❖ J2EE stands for Java 2 Platform, Enterprise Edition. J2EE is the


standard platform for developing applications in the enterprise and
is designed for enterprise applications that run on servers.

3) Java Platform, Standard Edition (J2SE):

❖ It has concepts for developing software for Desktop based


(standalone) CUI (command user interface) and GUI (graphical user
interface) applications, applets.

Q-3 Write a short note on JVM, JRE and


JDK Ans:
JVM:

❖ JVM stands for Java Virtual Machine.


❖ All language compilers translate source code into machine code for a specific
computer. Java compiler also does the same thing.

❖ Java compiler produces an intermediate code known as byte code for a


machine that does not exist.
❖ This machine is called the Java Virtual Machine and it exists only inside
the computer memory.

Java Java Compiler Virtual


Program Machine
Process of Compilation

❖ The virtual machine code (Byte Code) is not machine specific.

❖ The machine specific code is generated by the Java Interpreter by acting as an


intermediary between the virtual machine and the real machine as shown in
fig. Interpreter is different for different machine.

JRE:
Process of converting Byte Code into Machine Code
Byte Code Java Interpreter Machine Code
Virtual Machine

❖ The Java Runtime Environment (JRE), also known as Java Runtime, is


part of the Java Development Kit (JDK), a set of programming tools for
developing Java applications. The Java Runtime Environment provides
the minimum requirements for executing a Java application; it consists
of the Java Virtual Machine (JVM), core classes, and supporting files.

JDK:

❖ JDK stands for Java Development Kit.


❖ It is a collection of tools which are used for developing and running the java
program.

Components:-
1) Applet viewer :- it used to view the java applets without using the browser.

2) Javac :- the java compiler translate source code to byte code.


3) Java :- java interpreter runs the applets and application by reading the byte
code.
4) Javadoc: - it creates html format documentation from java source code.
5) Javah :- it produce header file.
6) Javap :- it enables to convert byte code into program description.
7) Jdb :- it is java debugger used for find errors from the programs.

Q-4 Write a short note on compiling and executing basic java


program. Ans:

Steps:
Step 1: Save the program with .java extension (Note: Name of the program
must be same as the name of the class)

Step 2: Open the command prompt and compile your program


javac hello.java (where hello.java is the name of your file)
Step 3: Execute/run the program
java hello
Output: hello

Q-5 Write a short note on java


IDE Ans:
IDE stands for Integrated Development Environment

Netbeans:

❖ NetBeans is an integrated development environment (IDE) for developing


primarily with Java, but also with other languages, in particular PHP,
C/C++, and HTML5 .It is also an application platform framework for Java
desktop applications and others.
❖ The NetBeans IDE is written in Java and can run on Windows, OS
X, Linux, Solaris and other platforms supporting a compatible JVM.
❖ The NetBeans Platform allows applications to be developed from a set
of modular software components called modules. Applications based on
the

NetBeans Platform (including the NetBeans IDE itself) can be extended


by third party developers.
❖ NetBeans IDE is an open-source integrated development environment.
NetBeans IDE supports development of all Java application types (Java
SE (including JavaFX), Java ME, web, EJB and mobile applications).

Eclipse:

● Eclipse is an integrated development environment (IDE). It started in 2001,


when IBM released Eclipse into open source.
● It contains a base workspace and an extensible plug-in system for customizing
the environment.
● Eclipse can be used to develop applications in Java. By means of various plug-
ins, Eclipse may also be used to develop applications in other programming
languages: Ada, C, C++, COBOL, Fortran,

Q-6 Write a short note on data types in

java Ans:

Data type means the type of data.

Integer

❖ Java provides four integer types: byte, short, int, long.


❖ All of these are signed, positive and negative values.

Floating-Point Types

❖ Floating-Point numbers, also known as real numbers, are used when


evaluating expressions that require fractional precision.
❖ For example, calculations such as square root, or transcendental such as sine
and cosine, result in a value whose precision requires a floating-point type.
❖ There are two kinds of floating-point types, float and double, which
represent single and double-precision numbers, respectively.

Character
❖ The data type used to store characters is char.

Boolean:

❖ Java has primitive type, called boolean, for logical values.

❖ It can have only one of two possible values, true or false.

Q-7 Write a short note on java

tokens Ans:

❖ Token is the smallest individual unit of a program.

❖ Tokens are the various Java program elements which are identified by the
compiler
❖ Tokens supported in Java include keywords, variables, constants, special
characters, operations etc.
MCQ
Sr Question Answer
No.
1 The smallest individual unit of Token
program is known as ….
2 ……….are the reserved words keyword
3 Literals means the …….. value
4 How many tokens are available in Variables, Operators,
java? Keywords, Special
Characters, Literals

Q-8 Write a short note on Operators in

java Ans:

❖ An operator is a symbol that tells the computer to perform


certai
n mathematical or logical manipulations.

❖ Following are the types of operators in java:


1) Arithmetic
2) Relational
3) Logical
4) Assignment
5) Conditional
6) Instance Of
7) Sizeof
8) Bitwise
9) Increment/Decrement

1) Arithmetic Operators
Example:
import
java.util.*; class
arithmetic
{
public static void main(String args[])
{
int a,b;
Scanner sc=new Scanner(System.in);
System.out.println(“Enter a”);
a=sc.nextInt();
System.out.println(“Enter b”);
b=sc.nextInt();
System.out.println(“Addition=” +(a+b));
System.out.println(“Sub is” +(a-b));
System.out.println(“Mul is” +(a*b));
System.out.println(“Div is”+(a/b));
System.out.println(“Modulas is” +(a%b));
}
}

2) Relational Operators:

Example:

import
java.util.*; class
arithmetic
{
public static void main(String args[])
{
int a,b;
Scanner sc=new Scanner(System.in);
System.out.println(“Enter a”);
a=sc.nextInt();
System.out.println(“Enter b”);
b=sc.nextInt();
System.out.println(“> than” +(a>b));
System.out.println(“< than” +(a<b));
System.out.println(“>= is” +(a>=b));
System.out.println(“<=”+(a<=b));
System.out.println(“== is” +(a==b));
System.out.println(“!= is” +(a!=b));
}
}
3) Logical Operators:

Example:

import
java.util.*; class
arithmetic
{
public static void main(String args[])
{
int a,b,c;
Scanner sc=new Scanner(System.in);
System.out.println(“Enter a”);
a=sc.nextInt();
System.out.println(“Enter b”);
b=sc.nextInt();
System.out.println(“Enter c”);
c=sc.nextInt();
if(a>b && a>c)
System.out.println(“a is max”);
else if(b>c && b>a)
System.out.println(“b is max”);
else
System.out.println(“c is max”);
}
}

4) Assignment Operators:

Assignment operator is indicated by =

Case 1: (Copy the value to the


variable) a=5
In the above case, 5 is assigned the value
to a

Case 2: (Copy the variable value to another variable)


a=4,b=5
a=b
In the above case, the value of b is assigned to a

Case 3: (Copy the expression to the variable)


a=5,b=4
c=a+b
In the above case, the value of a+b is assigned to c.

Note: Assignment operator is also known as shorthand operator because it


represent shorthand ways to represent the variable.

Example:
a=a+5 a+=5
a=a-4 a-=4
a=a*2 a*=2

5) Conditional Operators:

❖ Conditional operator is indicated by ?

❖ It is also known as ternary operator because it requires 3 parts:

Syntax:
Condition? True part: false part

Example:
(a>b) ? “a is max” : “b is max”

6) Instance of Operator:

❖ It is used to test whether the object is an instance of the specified type


❖ It is also known as type comparison operator because it compares
instance with the class type.

Syntax:

objectname=classname Example:
test t1=new test();

The above example checks whether the t1 is object of the class test or not
7) size of Operator:

❖ It is used to find the size of the variable or the type.

Syntax:
sizeof(variable name);

Example:
int a;
sizeof(a)=4
bytes

8) Bitwise Operator:

❖ Bitwise operator operates on the bits(0 and 1)

❖ Following are the types of bitwise operators.


o Bitwise AND (&)
o Bitwise OR(|)
o Bitwise ExclusiveOR(^)

a b a&b a|b a^b


0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

9) Increment/Decrement Operator:

❖ This operator is used to increment or decrement the value by 1.


❖ There are 2 types of increment and decrement:
o pre-increment (++a)
o Post-increment(a++)
o pre-decrement(--a)
o post-decrement(a--)

Pre-increment Post-Increment
1) In this, value is increment first 1) In this, value is first assigned to
and then it is assigned to the the variable and then it is
variable incremented.
2) ++a 2) a++

Example:
class inc
{
public static void main(String args[])
{
int i=0,j=0;
System.out.println(i++); //post increment
System.out.println(++j); // pre-increment
}

Pre-decrement Post-decrement
2) In this, value is decremented 3) In this, value is first assigned to
first and then it is assigned to the variable and then it is
the variable decremented.

4) --a 2) a--

Example:
class dec
{
public static void main(String args[])
{
int i=0,j=0;
System.out.println(i- -); //post
increment System.out.println(- -j); // pre-
increment
}

Q-9 Write a short note on Decision Control

structures Ans:

❖ Following are the types of decision control structures:

◆ if

◆ if-else
◆ Nested if

◆ else-if ladder

◆ switch case

1) if:

Description: This decision control structure only deals with the true part of
the condition and it works only with one condition.
Syntax:

if(condition)

True par
{
statements;

Example:

i
mp
ort
jav
a.u
til.
*;
cla
ss
dc
{
public static void main(String args[])
{
int a,b;
Scanner
sc=new
2) if-else:
Description: This decision control structure deals with the true and false part of the
condition and it works only with one condition.

If the condition is true then statements inside if are executed and if the condition
is false then statements inside false are executed.
False part

Example:
import
java.util.*; class
dc
{
public static void main(String args[])
{
int a,b;
Scanner sc=new
Scanner(System.in);
System.out.println(“Enter a”);
a=sc.nextInt();
System.out.println(“Enter b”);
b=sc.nextInt();
if(a==b)
System.out.println(“Equal”);
else
System.out,println(“Not Equal”);
}
}
Description:

❖ Nested if means one if inside another if. It is used when you have

i
m
p
or
t
ja
v
a.
ut
il.
*;
cl
as
s
d
c
{
public static void main(String args[])
{
more than 1 condition
import
java.util.*; class
dc
{
public static void main(String args[])
{
int a,b,c;
Scanner sc=new
Scanner(System.in);
System.out.println(“Enter a”);
a=sc.nextInt();
System.out.println(“Enter b”);
b=sc.nextInt();
System.out.println(“Enter c”);
c=sc.nextInt();

if(a>b && a>c)


System.out.println(“a
is max”); else if(b>c && b>a)
System.out.println(“b is max”);
else
System.out.println(“c is max”);

}
}

Description:

5) switch case:
❖ switch case is used with multiple options.
❖ In switch case, the value of the variable is passed which is compared
with the different cases, the case which matches the value is executed.
❖ switch case have 4 keywords: switch, case, default, break

❖ break keyword is used to exit from the particular case


❖ When no case is executed, at that time default case is executed Syntax:
switch(variable)
{
case 1: statement1;
break;
case 2: statement2;
break;
case 3: statement3;
break;
case4: statement4;
break;
default: statement5;
break;
}
Example:

import
java.util.*; class
dc
{
public static void main(String args[])
{
int a,b,ch;
Scanner sc=new
Scanner(System.in);
System.out.println(“Enter a”);
a=sc.nextInt();
System.out.println(“Enter b”);
b=sc.nextInt();
System.out.println(“Enter 1.add 2.sub
3.mul 4.div”); ch=sc.nextInt();
switch(ch)
{
case 1:
System.out.println(a+b);
break;

case 2:
System.out.println(a-b);
break;

case 3:
System.out.println(a*b);
break;

case 4:
System.out.println(a/b);
break;

Q-10 what is loop? List out types of looping structures and explain in

detail Ans:

❖ When same task is to be performed multiple times, then in that case


loop is used.
❖ Following are the types of loop
1) Entry Controlled Loop:

❖ When the condition is checked in the starting of the loop, it is


known as entry controlled loop.
❖ for loop and while loop are known as entry controlled loop.

* for loop:

Syntax:

for(initialization ;condition ;increment/decrement)

{
Statements;

Example:

class loop
{
public static void main(String args[])
{
int i;
for(i=1;i<=5;i++)
{
System.out.println(i);
}
}

* while loop:

Syntax:

Initialization;
while(condition)

{
Statements;
Increment/decrement;

Example:
class loop
{
public static void main(String args[])
{
int i=1;
while(i<=5)
{
Syste
m.out.println(i); i++;
}
2) Exit Controlled Loop:
}

❖ When the condition is checked in the end of the loop, it is known as


exit controlled loop.
❖ do-while loop is example of exit controlled loop

❖ In do-while loop, statements are executed atleast once without


checking the condition.
Syntax:
Initialization; do
{
Statements;
Increment/decrement;
} while (condition);

Example:

class loop
{
public static void main(String args[])
{
i
nt i=1;
do
{
Syste
m.out.println(i); i++;
}while(i<=5);
}

*** Difference between while and do-while loop


while loop do-while loop
It is known as entry controlled loop It is known as exit controlled loop
If the condition is true then only The statements are executed atleast
statements are executed once and after that the condition is
checked.
While loop does not have semicolon do-while loop have terminating
semicolon

Q-11 Write a short note on jumping statements in

java Ans:

❖ Jumping statements transfers the control from one location to


another location.
❖ Following are the types of jumping statements:
o break
o continue

1) break statement:

❖ This statement is used to exit immediately from the loop or program

❖ When the break statement is encountered in the program, the


control directly moves to the end of the program.
Syntax:

for(; ;)

{
if(condition)
break;
}
Example:

class jm
{
public static void main(String args[])
{
int i;
for(i=1;i<=5;i++)
{
if(i==3)
break;
System.out.println(i);
}
}
2) contine statement:

❖ This statement is used to continue back to the re-evaluation of the


condition.
❖ Using continue statement, certain statements are

bypassed. Syntax:

for(; ;)
{
if(condition)
continue;
}
Example:

class jm
{
public static void main(String args[])
{
int i;
for(i=1;i<=5;i++)
{
i
f(i==3)
continue;
System.out.println(i);
}
}

*** Difference between break and continue statement


Q-12 Write a short note on

typecasting Ans:

❖ Typecasting means converting one data type into another datatype.

❖ There are 2 types of type casting in java.

1) Widening data type

❖ Converting a lower data type into a higher one is called widening type
casting. It is also known as implicit conversion or casting down. It is done
automatically.

Example:

class type
{
public static void main(String args[])
{
i
nt x=10;
float y;
y=x;
System.out.println(y);
}
}

❖ Converting a higher data type into a lower one is called narrowing type
casting. It is also known as explicit conversion or casting up. It is done
manually by the programmer.

Example:
class exp1 2) Narrowing data type
{
public static void main(String args[])
{
int x;
doub
le f=2.5; x=(int)f;
System.out.println(x)
;
}
}
Q-13 Write a short note on

Arrays Ans:

❖ Array is the collection of elements that have same data type. All the
elements of array share same array nameThe main concept of array is index
Advantages:

o Code Optimization: It makes the code optimized, we can retrieve or sort


the data efficiently.
o Random access: We can get any data located at an index position.

Disadvantages:
Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime.
1) 1-d array (One Dimensional Array):

❖ The array having only one dimension is known as 1-d


array. Syntax:
Declaration of array:
datatype[] arrayname
O
R datatype arrayname[]
O
R

Initialization of array:
datatype arrayname[]=new datatype[size];
Example 1:
class exp1
{
public static void main(String args[])
{
int i;
int
a[]=new int[5];
a[0]=10;
a[1]=11;
a[2]=12;
a[3]=13;
a[4]=14;
for(i=0;i<a.length;i++)
System.out.println(a[i]);
}
}
Example 2:

class exp1
{
public static void main(String args[])
{
int i;
int a[]={10,11,12,13,14};

for(i=0;i<a.length;i++)
System.out.println(a[i]);
}
}

import java.util.*;
class arr
{
public static void main(String args[])
{
int i;
int a[]=new int[5];
Scanner sc=new
Scanner(System.in); for(i=0;i<5;i++)
{
System.out.println("Enter array
elements");
a[i]=sc.nextInt();
}
for(i=0;i<5;i++)
{
System.out.println("Array ele"
+a[i]);
}
}
}

2) Multi-Dimensional array:
❖ In this array, the data is stored in row and column based index
(also known as matrix form)

Syntax:
Declaration of array:
datatype[][] arrayname
O
R datatype arrayname[][] O

Initialization of array:
datatype arrayname[][]=new datatype[rowsize][columnsize];
Example 1:

class array
{
public static void main(String args[])
{
int i,j;
int a[][]={{1,2},{3,4}};
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
System.out.print(a[i][j
] +" ");
}
System.out.println();
}
}
}
Example 2: inputing the array from user

import java.util.*; class


arr
{
public static void main(String args[])
{
int i,j;
int a[][]=new int[2][3];
Scanner sc=new Scanner(System.in);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
System.out.println("Enter
array elements"); a[i][j]=sc.nextInt();
}

}
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
System.out.println("Array ele" +a[i][j]);
}
Q-14 Write a short note on Command Line

arguments Ans:

❖ The java command-line argument is an argument i.e. passed at


the time of running the java program.
❖ The arguments passed from the console can be received in the
java program and it can be used as an input.

Example 1:

class cmd1
{
public static void main(String args[])
{
System.out.println(args[0]);
}
}

Example 2:

class cmd1
{
public static void main(String args[])
{
int i;
for(i=0;i<args.length;i++)
{
System.out.println(args[i]);
}
}
}

Unit 1 –Class Fundas (Part 2)

Q-1 Explain class and


object Ans:

❖ A class is a template from which objects are created. That is objects


are instance of a class
❖ When you create a class, you are creating a new data-type. You can
use this type to declare objects of that type.
❖ An entity that has state and behavior is known as an object e.g., chair,
bike, marker, pen, table, car, etc.
❖ An object is an instance of a class.

❖ Class defines structure and behavior (data & code) that will be shared
by a set of objects
❖ Each object contains its own copy of each variable defined by the class

Syntax:

class ClassName
{
type instance variable1; Instance
type instance variable2;

type methodname1 (parameter list)


{
body of method;
} Method of class
type methodname2 (parameter list)

{
body of method;
}

Example:
class student
{
int roll;
String name;
}
class sample
{
public static void main(String args[])
{
student s=new
student(); s.roll=1;
s.name="xyz";
System.out.println(s.roll);
System.out.println(s.name);
}
}

Q-2 Explain Encapsulation

Ans:

❖ Encapsulation is one of the fundamental concept of OOP


❖ Encapsulation in Java is a mechanism of wrapping the data (variables) and
code acting on the data (methods) together as a single unit.
❖ In encapsulation, the variables of a class will be hidden from other classes,
and can be accessed only through the methods of their current class.
Therefore, it is also known as data hiding.

To achieve encapsulation in Java:

❖ Declare the variables of a class as private.

❖ Provide public setter and getter methods to modify and view the
variables values.

❖ To achieve encapsulation in Java


: Advantages of Encapsulation:
❖ The fields of a class can be made read-only or write-only.

❖ A class can have total control over what is stored in its fields.
Example:

class test
{
private
int age; public
void get()
{
System.out.println(age);
}
public void set(int age)
{
this.age=age;
}
}

class enc
{
public static void main(String args[])
{
test
t=new test(); t.set(1);
t.get();
}
}

Q-3 Write a short note on Inheritance

Ans:

❖ Inheritance in Java is a mechanism in which one object acquires all the


properties and behaviours of a parent object. It is an important part of
OOPs (Object Oriented programming system).

Terms used in inheritance:

1) Class: A class is a group of objects which have common properties. It is


a template or blueprint from which objects are created.
2) Sub Class/Child Class: Subclass is a class which inherits the other class.
It is also called a derived class, extended class, or child class.
3) Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class

Advantage of Inheritance:
Reusability: As the name specifies, reusability is a mechanism which
facilitates you to reuse the fields and methods of the existing class when you
create a new class. You can use the same fields and methods already defined in
the previous class.

Syntax:

class subclass extends superclass


{
//methods and fields
}
The extends keyword indicates that you are making a new class that
derives from an existing class.

Types of Inheritance:
Note: Multiple inheritance is not supported in Java through class.

1) Single Inheritance :

❖ When a class inherits another class, it is known as a


single inheritance.

Example:
In the below example, Dog is the subclass and Animal is the
ParentClass. So Dog inherits the methodc of the Animal Class and also it
have its own method.

2) Multilevel Inheritance :
❖ When there is a chain of inheritance, it is known as
multilevel inheritance.

❖ ltilevel inheritance, one class inherits from another class, another class
inherits from next class and so on.
class Animal
{
void eat()
{
System.out.println("Eating");
}
}

class Dog extends Animal


{
void bark()
{
System.out.println("Barking");
}
}
class BabyDog extends Dog
{
void sleep()
{
System.out.println(“Sleeping”);
}
}

class single
{
public static void main(String args[])
{
BabyDog
bd=new BabyDog(); d.bark();
d.eat();
d.sleep();
}
}
3) Hierarchical Inheritance :

When two or more classes inherits a single class, it is known


class Animal
{ as hierarchical inheritance.
void eat()
{
System.out.println("Eating");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("Barking");
}
}
class cat extends Animal
{
void sleep()
{
System.out.println(“Sleeping”);
}
}
class single
{
public static void main(String args[])
{
cat
c=new cat(); c.eat();
c.sleep();
Dog d=new Dog();
d.bark();
d.eat();
}
}

4) Multiple Inheritance :

❖ Multiple inheritance is not supported in java by class. The reason is


suppose A, B, and C are three classes. The C class inherits A and B classes.
If A and B classes have the same method and you call it from child class
object, there will be ambiguity to call the method of A or B class.
Example:

class A
{
void msg()
{
System.out.println(“Hello”);
}
}
class B
{
void msg()
{
System.out.println(“Hi”);
}
}
class C extends A,B
{
public static void main(String args[])
{
C c1=new C();
c1.msg();//Which msg() method will be called?
}
}

Will generate compile time error


5) Hybrid Inheritance :
❖ Hybrid inheritance is the combination of more than 1 type of inheritance.

Example:
class Animal
{
void eat()
{
System.out.println("Eating");
}
}

class Dog extends Animal //Single level inheritance


{
void bark()
{
System.out.println("Barking");
}
}
class cat extends Animal //Multilevel inheritance
{
void sleep()
{
System.out.println(“Sleeping”);
}
}

class single
{
public static void main(String args[])
{
cat
c=new cat(); c.eat();
c.sleep();
Dog
d=new Dog();
d.bark(); 59
d.eat();
}
}
Q-3 Write a short note on
Polymorphism Ans:

❖ Polymorphism Polymorphism in Java is a concept by which we


can perform a single action in different ways.
❖ Polymorphism is derived from 2 Greek words: poly and morphs. The
word "poly" means many and "morphs" means forms. So
polymorphism means many forms.

1) Compile time Polymorphism:

❖ It is also known as static polymorphism which is achieved by


method overloading.
❖ Method overloading means methods with same name but
different parameters.
❖ Method can be overloaded by change in number of arguments or
change in type of arguments.
Example:

class overload
{
void add(int a,int b,int c)
{
System.out.println(a+b+c);
}
void add(int a,int b)
{
System.out.println(a+b);
}
}
class method1
{
public static void main(String args[])
{
overl
oad o1=new
overload();
o1.add(2,3,4);
2) Run time Polymorphism:

❖ It is also known as dynamic polymorphism which is achieved by


method overriding.
❖ It is a process in which a function call to the overridden method is
resolved at Runtime.
❖ In the below example, When an object of child class is created, then the
method inside the child class is called. This is because the method in the
parent class is overridden by the child class. Since the method is
overridden, this method has more priority than the parent method inside
the child class. So, the body inside the child class is executed.
Example:

class A
{
void run()
{
System.out.println("Hello");
}
}

class B extends A
{
void run()
{
System.out.println("Hi");
}
}
class sam
{
public static void main(String args[])
{
B
b1=new B(); b1.run();
}
}

Q-4 Write a short note on

Constructor. Ans:

❖ A constructor is a special method which have same name as class name


❖ It is automatically called when object of class is created.
Rules for creating Java constructor

There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructor

There are two types of constructors in Java:

1) Default constructor (no-arg constructor)


2) Parameterized constructor Default Constructor:
❖ A constructor with zero parameter or no argument is known
as default constructor.

Example:

class A
{
A()
{
System.out.println("Default constructor");
}
}

class inhe
{
public static void main(String args[])
{
A a1=new A();
}
}

2) Parameterised Constructor:
❖ A constructor with parameters is known as
parameterised constructor.
Example:

class A
{
i
nt roll;
A(int r)
{
roll=r;
}
void display()
{
System.out.println(roll);
}
}

class inhe
{
public static void main(String args[])
{
A
a1=new A(10);
a1.display();
}
}

Q-5 Write a short note on Constructor

overloading Ans:

❖ A constructor with same name but different parameters is known


as constructor overloading.

Example:
class cons
{
int
roll; String
name;
cons()
{
System.out.println("Hello");
}
cons(int r)
{
roll=r;
}
cons(int r,String n)
{
r
oll=r;
name=n;
}
void display()
{
System.out.prin
tln(roll);
System.out.println(name);
}
}
class consoverload
{
public static void main(String args[])
{
cons
c=new cons(); cons
c1=new cons(10);
cons c2=new
cons(10,"xyz"); c1.display();
c2.display();
}
Q-6 Write a short note on static and non-static members in

java Ans:

Static Variables:

❖ When a variable is declared as static, then a single copy of the variable


is created and shared among all objects at a class level. Static variables
are, essentially, global variables. All instances of the class share the
same static variable.
❖ We can create static variables at class-level only
Example:

class test
{
static int
a=20; void
display()
{
a++;
System.out.println(a);
}
}
class sample
{
public static void main(String args[])
Non-Static Variables:
{
t
est t1=new test();
test t2=new test();
test t3=new test();
t1.display();
t2.display();
t3.display();
}
}

❖ When a variable is declared as non-static, then individual copy of the


variable is created for the different objects. Static variables are, essentially,
local variables. All object of the class share the different non- static
variable.
Example:

class test
{
int
a=20; void
display()
{

a++;
System.out.println(a);
}

}
class sample
{
public static void main(String args[])
{
t
est t1=new test();
test t2=new test();
test t3=new test();
t1.display();
t2.display();
t3.display();
}
}
Q-7 Write a short note on

varargs Ans:

❖ The varrags allows the method to accept zero or multiple arguments.


❖ If we don't know how many argument we will have to pass in the
method, varargs is the better approach.
❖ The varargs uses ellipsis i.e. three dots after the data type. Syntax is
as follows:

Syntax:
return_type method_name(data_type... variableName)
{
}
Example:
class varg
{
static void display(int...values)
{
System.out.println("hello");

for(int i:values)
System.out.println(i);
}
public static void main(String args[])
{
displ
ay(); display(1,2,3,4);
display(12,22);
}
}

Q-8 Write a short note on IIB block in

java Ans:

❖ IIB stands for instance initializer block


❖ Instance Initializer block is used to initialize the instance data member
❖ It run each time when object of the class is created.
Example:
class iib
{

nt
System.out.println(
}

{ age=1
}
IIB

class im
{
public static void
main(String args[])
{
i
Unit-2:- Inheritance and java packages

Q-1 Explain Universal


class Ans:
❖ The Object class is the parent class of all the classes in java
by default. In other words, it is the topmost class of java.
❖ Object class is present in java. Lang package. Every class in Java is
directly or indirectly derived from the Object class.
❖ If a class does not extend any other class then it is a direct child class
of Object and if extends another class then it is indirectly derived.
❖ Therefore the Object class methods are available to all Java classes.

❖ Hence object class acts as a root of inheritance hierarchy in any


Java Program.
❖ The Object class is beneficial if you want to refer any object whose
type you don't know.
❖ Following are the methods of object class.

Sr No. Method Name Description


1 toString() It is used to convert an object to string
Note: It is always recommended to override
toString() method to get our own string
representation.
2 hashcode() It returns a hashvalue that is used to
search the object in the collection
Note: For every object, JVM generates
unique number which is known as hascode.
3 equals It compares given object to “this” object
(the object on which method is called)
4 getClass() It returns the class of the object and is used
to get actual runtime class of the object.
5 finalize() This method is called just before an object
is garbage collected. It is called on an
object when garbage collector determines
that there are no references to the object.
Note: finalize() is just called once on an
object
6 clone() It returns the new object that is exactly
same as this object
7 notify() wakes up single thread, waiting on object’s
monitor
8 notifyall() wakes up all thread, waiting on object’s
monitor
9 wait() Causes the current thread to wait for the
specified milliseconds until another thread
notifies.

Q-2 Write a short note on Access Specifier


Ans:
❖ The access modifiers in Java specifies the accessibility or scope of a
field, method, constructor, or class. We can change the access level of
fields, constructors, methods, and class by applying the access
modifier on it.
❖ There are 4 types of java access modifiers
1. Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class. A class cannot be private
except nested class.

It cannot be accessed from outside the package. If you do not specify any
access level, it will be the default.
//Save this with A.java (Package 1)

pa
cka
ge
pac
k;
clas
sA
{
void display()
{
System.out.println(“Hello”);
}
2. Default: The access level of a default modifier is only within the package.
class A
{
p
rivate int
data=40;
private void
msg()
{
System.out.println("Hello java");
}
}
class Simple
{
public static void main(String args[])
{
A obj=new A();
//Save this with B.java (Package 2)
System.out.println(obj.data);//Compile
package mypack; Time Error obj.msg();//Compile Time
import pack.*; Error
class B }
{
}
public static void main(String args[])
{
A
obj=new A();
obj.display();
}
}

Note:

❖ In the above example, the scope of class A and its method msg() is
default so it cannot be accessed from outside the package.

3. Protected: The access level of a protected modifier is within the package


and outside the package through the inheritance. The protected access
modifier can be applied on the data member, method and constructor. It
cannot be applied on class.
//Save this with A.java (Package 1)

package pack;
public class A
{
protected void display()
{
System.out.println(“Hello”);
}
}

//Save this with B.java (Package 2)

package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B
obj=new B();
obj.display();
}
}

4. Public: The access level of a public modifier is everywhere. It can be


accessed from within the class, outside the class, within the package and
outside the package.

//Save this with A.java (Package 1)

package pack;
public class A
{
public void display()
{
System.out.println(“Hello”);
}
}
//Save this with B.java (Package 2)

package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A
obj=new A();
obj.display();
}
}

Q-3 Write a short note on Constructor in


inheritance Ans:
❖ A constructor in Java is similar to a method with a few differences.
Constructor has the same name as the class name. A constructor
doesn't have a return type.
❖ A Java program will automatically create a constructor if it is not
already defined in the program. It is executed when an instance of the
class is created.
❖ A constructor cannot be static, abstract, final or synchronized. It
cannot be overridden.
❖ When the constructor is used in inheritance, then the constructor of
86
base class is executed first and then constructor of child class is
executed.
Constructor in single level inheritance
Write a short note on Interface Ans:
class parent
{
parent()
{
System.out.println(“Parent class
constructor”);
}
}
class child extends parent
{
child()
{
System.out.println(“Child class
constructor”);
}
}
class sample
{
❖ An interface in Java is a blueprint of a class. It has static constants
public static void main(String args[])
and abstract{methods.
child c=new child();
❖ Interface in }java is used to achieve abstraction and multiple inheritance
}
❖ Interface can only have abstract methods that is methods without body
❖ “Implements” keyword is used when the class implements interface.

Syntax:
interface interfacename
{
returntype methodname();
}
Example:
interface draw
{
void print();
}

class rectangle implements draw


{
public void print()
{
System.out.println("draw rectangle");
}
}
class circle implements draw
{
public void print()
{
System.out.println("draw circle");
}
Multiple inheritance in java using interface:
}
class test
Multiple inheritance means multiple parent class and one child
{
class. public static void main(String args[])
The{ child class inherits from multiple parent class.
circle c1=new
circle(); c1.print();
rectangle
r=new rectangle(); r.print();
}
}

❖ Multiple inheritance is not supported by java. But through


the interface multiple inheritance is achieved in java.
Example:
interface a
{
void display();
}
interface b
{
void display1();
}
class mul implements a,b
{
public void display()
{
System.out.println("hello");
}
public void display1()
{
System.out.println("hi");
}
}

class multiple
{
public static void main(String args[])
{
sam
s=new sam();
s.display();
s.display1();
}
}

Q-4 Write a short note on Object


cloning Ans:
❖ The object cloning is a way to create exact copy of an object.

❖ The clone() method of Object class is used to clone an object.


❖ The clone() method is defined in the Object class.
❖ Every class that implements clone() should call super.clone() to obtain
the cloned object reference.
❖ The class must also implement java.lang.Cloneable interface whose
object clone we want to create otherwise it will throw
CloneNotSupportedException when clone method is called on that
class’s object.

Syntax:
public Object clone() throws CloneNotSupportedException
Example:
class stu implements Cloneable
{
int
rollno; String
name;

stu(int r,String n)
{
this.r
ollno=r;
this.name=n;
}
public Object clone()throws CloneNotSupportedException
{
return super.clone();
}

public static void main(String args[])


{
try
{
stu s1=new
stu(1,"xyz"); stu
s2=(stu)s1.clone();

System.out.println(s2.rollno);
System.out.println(s2.name);
}catch(CloneNotSupportedException c)
{

}
}
}
Q-5 Write a short note on Nested and Inner
Class Ans:
❖ Java inner class or nested class is a class that is declared inside the
class or interface.
❖ We use inner classes to logically group classes and interfaces in one
place to be more readable and maintainable.
❖ Additionally, it can access all the members of the outer class, including
private data members and methods.

Syntax:
class Java_Outer_class
{
//code class Java_Inner_class
{
//code
}
1) Non-Static Nested class:
❖ A non-static nested class is a class within another class. It has access to
members of the enclosing class (outer class). It is commonly known as
inner class
❖ As inner class exists inside outer class, the object of outer class must be
created in order to create object of inner class.

Example:
class outer
{
int
x=10; class
inner
{
int y=4;
}
}

class nested
{
public static void main(String args[])
{
outer o=new
outer(); outer.inner i=o.new
inner();
System.out.println(i.y);
System.out.println(o.x);
}
}
Note: class
Dot operator(.) is used to create the object
of inner class using outer
2) Static Nested class:

❖ Static class inside another class is known as static nested class.


❖ Static nested class are not known as static inner class.
❖ The main difference between static nested class and inner class is that a
static nested class can not access member variables of the outer class.it
is because the static nested class does not require you to create an
object of outer class.

Example:

class outer
{
int x=10;
static class inner
{
int y=4;
}
}

class nested
{
public static void main(String args[])
{
outer.inner i=new outer.inner();
System.out.println(i.y);
System.out.println(i.x);//will generate error
}
}

Q-6 Write a short note on abstract class and final


class Ans:
Abstract Class:
A class which is declared as abstract is known as an abstract class.
It can have abstract and non-abstract methods.
It needs to be extended and its method implemented.
It cannot be instantiated.
Example:
abstract class bike
{
abstract
void run(); void
display()
{
System.out.println("hello");
}
}

class honda extends bike


{
public void run()
{

System.out.println("hi");
}
}

class sampe
{
public static void main(String args[])
{
Final:The final keyword in java ishonda
used to restrict the user. The java final keyword can be
used in many context.h=new
Finalhonda();
can be: h.run();
h.display();
}
▪ Variable
}
▪ Method

▪ Class
❖ A class which cannot be inherited or extended is known as final class.

Example:

final class bike


{

class ja extends bike


{
void display()
{
System.out.println("hi");
}
public static void main(String args[])
{
bike b=new bike();
b.display(); //Compile time error
}
}
Q-7 Write a short note on normal import and static
import Ans:
Normal import:

❖ The import allows the java programmer to access classes of a


package without package qualification
❖ The import provides accessibility to classes and interface

class ke
{
public static void main(String args[])
{
System.out.println(Math.sqrt(25));
System.out.println(Math.pow(2,2));
}
}

static import:

❖ In Java, static import concept is introduced in 1.5 version.


❖ With the help of static import, we can access the static members of a
class directly without class name or any object.
❖ For Example: we always use sqrt() method of Math class by using Math
class i.e. Math.sqrt(), but by using static import we can access sqrt()
method directly.

import static java.lang.Math.*;

class ke
{
public static void main(String args[])
{
System.out.pri
ntln(sqrt(25));
System.out.println(pow(2,2));
}
}

Q-8 what is package? List out the packages in


java Ans:
❖ Package in Java is a mechanism to encapsulate a group of classes,
sub packages and interfaces. Packages are used for: Preventing
naming conflicts
❖ For example there can be two classes with name Employee in two
packages, college.staff.cse.Employee and college.staff.ee.Employee
❖ Following are the types of in built packages:

Built-in Packages:

❖ These packages consist of a large number of classes which are a part of


Java API.
❖ Some of the commonly used built-in packages are:
o java.lang: Contains language support classes(e.g classed which
defines primitive data types, math operations). This package is
automatically imported.
o java.io: Contains classed for supporting input / output operations.
o java.util: Contains utility classes which implement data structures
like Linked List, Dictionary and support ; for Date / Time
operations.
o java.applet: Contains classes for creating Applets.
o java.awt: Contain the classes for implementing the components
of graphical user in java.applet terfaces like button, menus etc.
o java.net: Contain classes for supporting networking operations.
❖ Provides classes that are fundamental to the design of the
Java programming language.
❖ Following are few important classes of java.lang package
1. Math
2. Wrapper Classes
3. String
4. String Buffer
❖ The java.lang.Math class contains various methods for performing basic
numeric operations such as the logarithm, cube root, and trigonometric
functions etc. The various java math methods are as follows:
❖ All the methods of the Math class are static so it can be called by class name
❖ Basic Math methods
❖ The wrapper class in Java provides the mechanism to convert primitive into
object and object into primitive.
❖ autoboxing and unboxing feature convert primitives into objects and objects
into primitives automatically. The automatic conversion of primitive
❖ into an object is known as autoboxing and vice-versa unboxing.
Primitive Wrapper Class Primitive Type Wrapper Class
Type
byte Byte float Float
boolean Boolean int Integer
char Character long Long
double Double short Short
Autoboxing:
❖ The automatic conversion of primitive data type into its corresponding
wrapper class is known as autoboxing, for example, byte to Byte, char to
Character, int to Integer, long to Long, float to Float, boolean to Boolean,
double to Double, and short to Short.

Example:

class wrapper1
{
public static void main(String args[])
{
int a=20;
Integer j=a; //Converting primitive data type to
Integer wrapper class System.out.println(j);
}
}

Unboxing:
❖ The automatic conversion of wrapper type into its corresponding
primitive type is known as unboxing. It is the reverse process of unboxin

class wrapper1
{
public static void main(String args[])
{
Integer a=new Integer(3);
int i=a; //Converting Wrapper class into primitive
data type System.out.println(i);
}
❖ The java.lang.String class represents character strings. All string literals in
Java programs, such as "abc", are implemented as instances of this
class.Strings are constant, their values cannot be changed after they are
created.

String replace(char old, char new) Replaces all occurrences of the specified char value.
static String Compares another string. It doesn't check case.
equalsIgnoreCase(String
another)
int indexOf(int ch) Returns the specified char value index.
String toLowerCase() Returns a string in lowercase.
String toUpperCase() Returns a string in uppercase.
String trim() Removes beginning and ending spaces of this string.

int compareTo(String) Compares this String to another specified String if


match then return zero(0) otherwise not zero(0).
int Compares two strings lexicographically, ignoring case
compareToIgnoreCase(String) differences.

Example:

❖ StringBuffer is a peer class of String that provides much of the functionality


of strings.
❖ The string represents fixed-length, immutable character sequences while
StringBuffer represents growable and writable character sequences
❖ StringBuffer may have characters and substrings inserted in the middle or
appended to the end.
❖ It will automatically grow to make room for such additions and often has
more characters preallocated than are actually needed, to allow room for
growth.

Example:
class stringfunctions
{
public static void main(String args[])
{
StringBuffer s=new
StringBuffer("hello"); System.out.println("Length"
+s.length()); System.out.println("Specified"
+s.insert(2,"hi")); System.out.println("Replace"
+s.replace(1,3,"ee"));
System.out.println("Deleting" +s.delete(1,3));
System.out.println("Reversing" +s.reverse());
System.out.println("Capacity" +s.capacity());
System.out.println("Charat" +s.charAt(2));
System.out.println("Substring" +s.substring(1));

❖ The java.util packages provide support for the event model,


collections framework, date and time facilities, and contain various
utility classes.
❖ Following are the classes in java.util package
❖ Random
❖ Date
❖ GregorianCalendar
❖ Vector
❖ HashTable
❖ StringTokenizer
❖ Collections in Java : Linked List, SortedSet, Stack, Queue, Map
❖ Java Random class is used to generate a stream of
pseudorandom numbers
❖ This class provides various method calls to generate different random
data types such as float, double, int.

import
java.util.*; class
randomn
{
public static void main(String args[])
{
Random r=new Random();
System.out.println("Integer val" +r.nextInt());
System.out.println("Next decimal" +r.nextDouble());
}
}
Example:

Date class in java.lang package

❖ The java.util.Date class represents date and time in java.

Method Description
boolean after(Date date) Tests if current date is after the given date.
boolean before(Date date) Tests if current date is before the given date.
int compareTo(Date date) Compares current date with given date.

boolean equals(Date date) Compares current date with given date for
equality.
long getTime() Returns the time represented by this date
object.
void setTime(long time) Changes the current date and time to given
time.

Example:
import java.util.*;

public class main1


{
public static void main(String[] args)
{
Date d=new Date();
Date d1=new Date(21-
11-2010); Date d2=new
Date(25-6-2022);
// Creating date
System.out.println("Current date: " +d);
System.out.println("Checking"+d1.before
(d)); System.out.println("after" +d.after(d2));
System.out.println("Clone object" +d.clone());
System.out.println("Compare" +d.compareTo(d1));
System.out.println("Equlas" +d.equals(d1));
System.out.println("Time" +d.getTime());
System.out.println("Hashcode" +d.hashCode());
}
}

❖ The java.util.StringTokenizer class allows you to break a string


into tokens. It is simple way to break string.
Example:

import java.util.*;

public class main1


{
public static void main(String[] args)
{
StringTokenizer st=new StringTokenizer("my name is
karishma"); System.out.println("Total number of Tokens:
"+st.countTokens()); while(st.hasMoreTokens())
{
System.out.println(st.nextToken());
}

}
}

❖ Gregorian calendar is a concrete subclass(one which has implementation


of all of its inherited members either from interface or abstract class) of a
Calendar.
❖ The major difference between Gregorian calendar and Calendar class are
that the Calendar class being an abstract class cannot be instantiated.
Calendar cal = Calendar.getInstance();

❖ GregorianCalendar Class being a concrete class, can be instantiated.


So an object of the GregorianCalendar Class
GregorianCalendar gcal = new GregorianCalendar();
Example:

import
java.util.*; class
greg
{
public static void main(String args[])
{
Calendar
cal=Calendar.getInstance(); GregorianCalendar
c=new GregorianCalendar();
System.out.println("Calendar date:"+cal.getTime());
System.out.println("Greg" +c.getTime());
}

❖ The Collection interface is the root interface of the collections


framework hierarchy. A Collection represents a single unit of objects,
i.e., a group.
❖ Java does not provide direct implementations of the Collection
interface but provides implementations of its sub interfaces like List,
Set,
and Queue.

❖ Java Collections can achieve all the operations that you perform on a
data such as searching, sorting, insertion, manipulation, and deletion.
❖ Following are the collections in java:

▪ Vector
▪ HashTable
▪ Linked List
▪ Sorted Set
▪ Stack
▪ Queue
▪ Map

❖ Vector is like the dynamic array which can grow or shrink its size.
Unlike array, we can store n-number of elements in it as there is no
size limit.

void add(int index, Inserts the element at the given position.


Object element)
void add() Adds the elements in vector
void clear( ) Removes all of the elements from this.
int lastElement() Returns the last element of vector
int firstElement() Returns the first element of vector

int indexOf(Object element) Searches for the first occurrence of the


given argument.
boolean remove(Object o) Removes the first occurrence of the
specified element.
void Deletes the component at the specified
removeElementAt(int index) index.
void clone() Creates the clone of vetor.
int capacity() Returns the capacity of vector.
int size( ) Returns the number of components in this
vector.
boolean contains() Checks whether the element is contained in
vector or not.
import
java.util.*; class
greg
{
public static void main(String args[])
{
Vector<Integer>ve=new
Vector<Integer>(5); ve.add(10);
ve.add(20);
ve.add(30);
ve.addElement(40);
System.out.println("Elements of vector" +ve);
System.out.println("Clone" +ve.clone());
System.out.println("Capacity" +ve.capacity());
System.out.println("Size" +ve.size());
System.out.println("Firstelement"
+ve.firstElement()); System.out.println("Firstelement"
+ve.lastElement()); System.out.println("Index"
+ve.indexOf(20)); System.out.println("Contains"
+ve.contains(10)); ve.remove(0);
System.out.println("Elements after removal" +ve);
}
}

❖ The Hashtable class implements a hash table, which maps keys to


values.

put(key,value) Maps the specified key to the specified


value in hashtable
remove(key) Removes the element specified at key in the
hashtable
size() Returns the number of keys in the hashtable
replace(key,value) Replaces the value at given key in the
hashtable
Boolean containsKey(key) Checks if hastable contains specified key or
not
Boolean Checks if hashtable contains specified value
containsValue(value) or not

❖ Linked List is a part of the Collection framework present in java.util


package.
❖ This class is an implementation of the LinkedList data structure which is
a linear data structure where the elements are not stored in contiguous
locations and every element is a separate object with a data part and
address part.
❖ The elements are linked using pointers and addresses.
❖ Each element is known as a node.

add(ele) Adds the element in the linked list


addFirst(ele) Adds the element in the first node of the
linked list
addLast(ele) Adds the element in the last node of the
linked list
remove(ele) Removes the given element from the linked
list
removeFirst() Removes the first element from the linked
list
removeLast() Removes the last element from the linked
list

i
m
p
o
r
t
j
a
v
a
.
u
t
i
l
.
* ❖ Java Collection framework provides a Stack class that models and
;
c
implements a Stack data structure.
l
a
❖ The class is based on the basic principle of last-in-first-out. In addition
to the basic push and pop operations, the class provides three more
functions of empty, search, and peek.

push(ele) Insert the element in the stack

pop() Removes the last element inserted in the


stack
search(ele) Searches the given element in the stack
peek() Returns the first element of the stack
empty() Returns the Boolean value after checking
whether the stack is empty or not

Java Collection framework provides a Queue class that models and implements a Queue
data structure.
❖ The class is based on the basic principle of First-in-first-out.

add(ele) It is used to insert the element in the queue


remove() Removes the head element from the queue
poll() Used to retrieve and removes the head of
queue
peek() Returns the head element of the stack

import
java.util
.*; que
{
public static void main(String args[])
{
PriorityQueue<String> p=new
PriorityQueue<String>(); p.add("abc");
p.add("xyz");
p.add("aaa");

System.out.print
ln("Queue ele: "+p); p.remove();
System.out.print
ln("After removal: "+p);
System.out.println("Poll:
"+p.poll());
System.out.println("After poll:"
+p); System.out.println("Peek:
Q-8 what is User define package? How to create the package
Ans:
❖ The package which is created by the user is known as User
Define Package.
❖ Following are the steps to create the package

Step 1: Create the notepad file


Step 2: Create the folder named “mypackage” and save the above file with
Demo.java
Step 3: Create the file and import the created package
Step 4: Save the file in the root directory outside the “mypackage” folder as
sample.java
Step 5: Compile Package (javac Demo.java)
Step 6: Compile the file in which you imported package (javac sample.java)
Step 7: Run the File

Unit-3
Exception Handling, Threading and Streams (Input and Output)
Q-1 what is Exception Handling?
Ans:
❖ The Exception Handling in Java is one of the powerful mechanism to
handle the runtime errors so that the normal flow of the application can
be maintained.
❖ The core advantage of exception handling is to maintain the normal
flow of the application. An exception normally disrupts the normal
flow of the application; that is why we need to handle exceptions
❖ Types of Java Exceptions
Checked Exception:

❖ The classes that directly inherit the Throwable class except


RuntimeException and Error are known as checked exceptions. For
example, IOException, SQLException, etc. Checked exceptions are
checked at compile-time.
2) UnChecked Exception:

❖ The classes that inherit the RuntimeException are known as unchecked


exceptions. For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not
checked at compile-time, but they are checked at runtime.
3) Error:
❖ Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.
Java Exception Keywords

Keyword Description

try The "try" keyword is used to specify a block where we should place an
exception code. It means we can't use try block alone. The try block
must be followed by either catch or finally.

catch The "catch" block is used to handle the exception. It must be preceded
by try block which means we can't use catch block alone. It can be
followed by finally block later.

finally The "finally" block is used to execute the necessary code of the
program. It is executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It specifies that


there may occur an exception in the method. It doesn't throw an
exception. It is always used with method signature.

class exc
{
public static void main(String args[])
{
try
{
int a=5/0;
}catch(ArithmeticException e)
{
System.out.println(e);
}
finally
{
System.out.println("hi");
}
}
}
MCQ
1) Which is the superclass of all Throwable
the errors and exceptions?

2) Which keyword is used to Try


write the code that contains
error or exception?

3) Which keyword is used to Finally


write the code that must be
compulsory executed?

4) ………Exception is declared Checked Exception


at compile time

Q-2 what is User Defined Exception? How to create it


Ans:
❖ Creating our own Exception is known as custom exception or user-defined
exception. Basically, Java custom exceptions are used to customize the
exception according to user need.
❖ This can be done by extending the class Exception.

class userdefinedexception
{
public static void main(String args[])
{
try
{
throw new myexception(400);
}
catch(myexception e)
{
System.out.println(e);
}
}
}

class myexception extends Exception


{
i
nt n1;
myexcept
ion(int
n2)
{
n1=n2;
Q-3 what is thread? Explain life cycle of
thread Ans:
❖ A thread is a single sequential flow of control within a program. A
process can have multiple threads, all executing at the same time.
❖ There can be more than one thread inside a process. Each thread of
the same process makes use of a separate program counter

❖ In Java, a thread always exists in any one of the following states. These
states are:

1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated

1) New:
❖ Whenever a new thread is created, it is always in the new state. For
a thread in the new state, the code has not been run yet and thus has
not begun its execution.
2) Active:

❖ When a thread invokes the start() method, it moves from the new
state to the active state. The active state contains two states within it:
one is runnable, and the other is running.

Runnable:

❖ A thread that is ready to run is then moved to the runnable


state. In the runnable state, the thread may be running or
may be ready to run at any given instant of time.
❖ It is the duty of the thread scheduler to provide the thread
time to run, i.e., moving the thread the running state
Running:
❖ When the thread gets the CPU, it moves from the runnable to the
running state

3) Blocked/Waiting:
❖ Whenever a thread is inactive for a span of time (not permanently)
then, either the thread is in the blocked state or is in the waiting state.
❖ For example, a thread (let's say its name is A) may want to print some
data from the printer. However, at the same time, the other thread
(let's say its name is B) is using the printer to print some data.
❖ Therefore, thread A has to wait for thread B to use the printer. Thus,
thread A is in the blocked state.

4) Timed Waiting:
❖ Sometimes, waiting for leads to starvation. For example, a thread (its
name is A) has entered the critical section of a code and is not willing
to leave that critical section.
❖ In such a scenario, another thread (its name is B) has to wait forever,
which leads to starvation. To avoid such scenario, a timed waiting
state is given to thread B.
❖ Thus, thread lies in the waiting state for a specific span of time, and
not forever.
❖ A real example of timed waiting is when we invoke the sleep()
method on a specific thread. The sleep() method puts the thread in
the timed wait state.
❖ After the time runs out, the thread wakes up and start its execution
from when it has left earlier.
5) Terminated:

❖ A thread reaches the termination state because of the following


reasons:
❖ When a thread has finished its job, then it exists or terminates
normally.
❖ Abnormal termination: It occurs when some unusual events such
as an unhandled exception or segmentation fault.

Q-4) what is Thread Class? Explain its methods.


Ans:
❖ Thread can be created using following methods:
o Extending Thread Class
o Implementing Runnable interface
o Explicitly creating thread object using Thread Class
Extending Thread Class:
❖ Thread class provide constructors and methods to create and perform
operations on a thread.

class m extends Thread


{
public void run()
{
System.out.println(“Runnin
g”);
}
public static void main(String args[])
{
m m1=new
m(); m1.start();
}
}
2) Implementing Runnable Interface:
❖ The Runnable interface should be implemented by any class whose
instances are intended to be executed by a thread.
❖ Runnable interface have only one method named run().

class m extends implements Runnable


{
public void run()
{
System.out.println(“Runnin
g”);
}
public static void main(String args[])
{
m m1=new m();
Thread t1=new
Thread(m1); t1.start();
}
}

3) Explicitly creating thread object using Thread Class:


❖ If we don’t extend the Thread class, then object of thread class is
created explicitly.
class m extends
{
public static void main(String args[])
{
Thread t1=new Thread(“First
Thread”); t1.start();
System.out.println(“Thread Name:
“+t1.getName());
}
}

Methods of Thread Class:

class th
{

public static void main(String args[])


{
Thread t1=new Thread("First Thread");
System.out.println("Thread Priority:
"+t1.getPriority());
t1.setPri
ority(6); t1.start();
t1.setName("My Thread");
System.out.println("Thread Name: "+t1.getName());
System.out.println("Thread Priority:
"+t1.getPriority());
System.out.println("Daemon Thread:
"+t1.isDaemon());

}
class th1 extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
try
{
Thread.sleep(1
000);
}
catch(InterruptedException
e)
{
System.out.pri
ntln(e);
}
System.out.println(i);
}
}

public static void main(String args[])


{
th1
t=new th1(); t.start();

}
}

Q-5) Write a short note on Thread Synchronization? OR


Write a short note on Multithreading
Ans:

❖ Synchronization in Java is the capability to control the access of multiple


threads to any shared resource.
❖ Java Synchronization is better option where we want to allow only one
thread to access the shared resource.
❖ Synchronization can be achieved by:
o Using Synchronized method
o Using Synchronized block
o Using Static Synchronization

Why use Synchronization?


❖ The synchronization is mainly used to

1. To prevent thread interference.

2. To prevent consistency problem.

❖ Below example shows the scenario where synchronization is not there. In


the below example, thread t1 and thread t2 are not synchronized so thread
t1 prints table of 5 and simultaneously thread t2 prints table of 10. So in
this case, synchronization is required.

class table
{
void printtable(int n)
{
for(int i=1;i<=5;i++)
{
Syst
em.out.println(n*i); try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}
}
class mythread1 extends Thread
{
table t;
mythread1(table t)
{
this.t=t;
}
public void run()
{
t.printtable(5);
}
}
class mythread2 extends Thread
{
table t;
mythread2(table t)
{
this.t=t;
}
public void run()
{
t.printtable(10);
} 145
}
class synch
{
public static void main(String args[])
{
table o=new table();
mythread1 t1=new
mythread1(o); mythread2 t2=new
mythread2(o); t1.start();
t2.start();
}
}

Example with synchronization:

class mythread2 extends Thread


{
table t;
mythread2(table t)
{
this.t=t;
}
public void run()
{
t.printtable(5);
}
}

class synch
{
public static void main(String args[])
{
table o=new table();
mythread1 t1=new
mythread1(o); mythread2 t2=new
mythread2(o); t1.start();
t2.start();
}
}

Q-6) Write a short note on Daemon and Non-Daemon Thread Ans:


Daemon Thread:

❖ Damon thread in java is a low-priority thread that runs in the background


to perform tasks such as garbage collection.
❖ Daemon thread in java is also a service provider thread that provides
services to the user thread.

Non-Daemon Thread:

❖ Non-Damon thread in java is a thread that does not run in the background.

❖ Non-daemon thread in java are not service provider


Q-7) what is Stream? Explain types Ans:
❖ A stream is a sequence of data. In Java, a stream is composed of
bytes. It's called a stream
❖ Java uses the concept of a stream to make I/O operation fast. The java.io
package contains all the classes required for input and output
operations.
❖ In general, a Stream will be an input stream or, an output stream.

● InputStream − this is used to read data from a source.


● OutputStream − this is used to write data to a destination.

❖ Based on the data they handle there are two types of streams −

● Byte Streams − these handle data in bytes (8 bits)


i.e., the byte stream classes read/write data of 8
bits. Using these you can store characters, videos,
audios, images etc.
● Character Streams − these handle data in 16 bit
Unicode. Using these you can read and write text
data only.

Q-8) what is File Class?


Ans:

❖ The File class is an abstract representation of file and directory pathname.


❖ A pathname can be either absolute or relative.
❖ The File class have several methods for working with directories and files
such as creating new directories or files, deleting and renaming directories
or files, listing the contents of a directory etc.
Example:

Creating a new file:


❖ Create a File operation is performed to create a new file.
❖ We use the createNewFile() method of file.
❖ The createNewFile() method returns true when it successfully creates
a new file and returns false when the file already exists.

Example:

import java.io.*;
import java.io.IOException;

class crf
{
public static void main(String args[])
{
try
{
File f=new
File("D:\\hel.txt");
if(f.createNewFile())
System.out.println("Created");
else
System.out.println("Not Created");
}
catch(IOException e)
{
System.out.println(e);
}
}

Getting the file information:


❖ The operation is performed to get the file information. We use several
methods to get the information about the file like name, absolute path,
is readable, is writable and length.
Example:

Q-8) Explain Random Access File?


import java.io.*;
import java.io.IOException;

class crf
{
public static void main(String args[])
{

File f=new
File("D:\\hel.txt"); if(f.exists())
{
System.out.println("Name of file:
"+f.getName()); System.out.println("Path of file:
"+f.getAbsolutePath());
System.out.println("Path of file:
"+f.length());
}
else
{
System.out.println("Does not
exists");
}

Read from the }file:

Write into file:

❖ In order to write data into a file, we will use the FileWriter class and its
write() method together. We need to close the stream using the close()
method to retrieve the allocated resources.

Example:

import java.io.*;
import java.io.IOException;

class crf
{
public static void main(String args[])
{
try
{
FileWriter w=new
FileWriter("d:\\hel.txt");
w.write("Hello");
w.close();
}
catch(IOException e)
{
System.out.println
(e);
}
❖ In order to write data into a file, we will use the Scanner class. Here,
we need to close the stream using the close() method.
❖ We will create an instance of the Scanner class and
use the hasNextLine() method nextLine() method to get data from the
file.

Example:
import java.io.*;
import
java.io.FileNotFoundException; import
java.util.*;

class crf
{
public static void main(String args[])
{
try
{
File f=new
File("D:\\hel.txt"); Scanner s=new
Scanner(f); while(s.hasNextLine())
{
Strin
g fd=s.nextLine();
System.out.println(fd);
}
s.close();
}
catch(FileNotFoundException e)
{
System.out.println(e);
}

}
Delete from the file:

❖ In order to delete a file, we will use the delete() method of the file.
We don't need to close the stream using the close() method because
for deleting a file

Example:
import
java.io.*; class
del
{
public static void main(String args[])
{
File f=new
File("D:\\hel.txt"); if(f.delete())
System.out.println("Deleted");
else
System.out.println("Not Deleted");
}
}

Q-9) what is Random Access File Class? Ans:


❖ A sequential file structure is the common way where records are stored
in order by the record key field.
❖ Random file access is the superimposed mechanism implemented
through Java code to access individual records directly and quickly
without searching through records in the file
❖ The RandomAccessFile class allows you to write programs that can
seek to any location in a file and read or write data at that point.
❖ This type of functionality is very valuable in some programs
Example

im
port
java.
io.*;
class
Ran
dom
1
{
public static void main(String args[])
{
try
{
RandomAccessFile f=new
RandomAccessFile("test1.txt","rw"); f.writeChar(‘k’);
f.write
Int(10);
f.writeDouble(1
0.2); f.seek(0);

System.out.println
(f.readChar());
Q-10) Write a short note on character stream class
Ans:
❖ The java.io package provides character stream classes to overcome the
limitations of byte stream classes which can only handle 8 bit and is
not compatible to work directly with characters.
❖ Character stream classes are used to work with 16 bit.

❖ Generally, character stream classes are used to read the characters


from the source and write them into destination.

Classes of Character Stream


Class Description
Buffered This class provides the methods to read characters from
Reader buffer
FileReader This class provides the methods to read characters from
the file
BufferedWriter This class provides the methods to write the characters
to the buffer
FileWriter This class provides the methods to write the characters
to the file.

File Reader Class and File Writer Class:

❖ Java FileWriter and FileReader classes are used to write and read data
from text files
❖ Unlike FileOutputStream class, you don't need to convert string
into byte array because it provides method to write string directly.
Example of File Reader and File Writer
import java.io.*;
import java.io.IOException;

class ch1
{
public static void main(String args[])
{
try
{
File
Reader f=new
FileReader("D:\\myf.txt")
; int i;
w
hile((i=f.rea
d())!=-1)
System.out.
println((cha
import java.io.*;
import java.io.IOException;

class ch1
{
public static void main(String args[])
{
try
{
FileWriter f=new
FileWriter("D:\\myf6.txt"); f.write("Hello");
Buffered Reader Class and Buffered Writer f.close();
Class:
}
catch(IOException e)
The "BufferedWriter"
{ class of java supports writing a chain
System.out.println(e);
of
}
}
}

❖ characters output stream (Text based) in an efficient way. The Chain-


Of- Characters can be Arrays, Strings etc. The "BufferedReader" class
is used to read stream of text from a character based input stream.
❖ The BufferedReader and BufferedWriter class provides support
for writing and reading
Example of Buffered Reader and Buffered Writer:

import java.io.*;
import java.io.IOException;

class ch1
{
public static void main(String args[])
{
try
{
FileWriter f=new
FileWriter("D:\\myf7.txt"); BufferedWriter b=new
BufferedWriter(f); f.write("Hello");
f.close();

}
catch(IOException e)
{
System.out.println(e);
}
}
}
import java.io.*;
import java.io.IOException;

class ch1
{
public static void main(String args[])
{
try
{
FileReader f=new
FileReader("D:\\myf7.txt"); BufferedReader
b=new BufferedReader(f); int i;
while(i=f.read())!=-1)
{
System.out.printl
n((char)i);
}
b.close();

}
catch(IOException e)
{
System.out.println(e);
}
}
}
Q-11) Write a short note on Byte stream class
Ans:
❖ Byte Stream classes are used to read bytes from the input stream and
write bytes to the output stream. In other words, we can say that Byte
Stream classes read/write the 8-bits.
❖ The Byte Stream classes are divided into two types of classes, i.e., Input
Stream and Output Stream.

InputStreamClass:
❖ The Input Stream class provides methods to read bytes from a
file, console or memory. It is an abstract class and can't be
instantiated.
❖ The subclass of Input Stream class are:
OutputStreamClass:

❖ The Java.io.OutputStream class is the superclass of all classes


representing an output stream of bytes. An output stream accepts
output bytes and sends them to some sink.

Methods of File OutputStream


Methods Description
int write() It is s used to write the byte in the current stream
void flush() This method is used to flush the output stream
void close() It is used to close the output stream

FileInputStreamClass

❖ Java FileInputStream class obtains input bytes from a file.


❖ It is used for reading byte-oriented data (streams of raw bytes) such as
image data, audio, video etc.

Methods of File Input Stream


Methods Description
int read() It is s used to read the byte from the current stream
void flush() This method is used to flush the input stream
void close() It is used to close the input stream

FileOutputStreamClass

❖ FileOutputStream is an output stream used for writing data to a file.


❖ If you have to write primitive values into a file, use FileOutputStream class.
❖ You can write byte-oriented as well as character-oriented data
through FileOutputStream class.

Methods of File Output Stream


Methods Description
int write() It is s used to write the byte in the current stream
void flush() This method is used to flush the output stream
void close() It is used to close the output stream

Example of FileOutputStream and FileInputStream:


import java.io.*;

class inp
{
public static void main(String args[])
{
try
{
FileOutputStream f=new
FileOutputStream("D:\\myf9.txt");
f.write(10);
FileInputStream f1=new
FileInputStream("D:\\myf9.txt"); int i;
while((i=f1.read())!=-1)
{
System.out.println(i);
}
}
catch(IOException e)
{
System.out.println(e);
}
}
}

DataInputStreamClass and DataOutputStream Class:


❖ The DataInputStream class read primitive Java data types from an underlying
input stream in a machine-independent way. While the
DataOutputStream class write primitive Java data types to an output stream in
a portable way.Example of DataInputStream and DataOutputStream:

import
java.io.*;
class da
{
public static void main(String args[])throws
IOException
{
FileOutputStream f=new
FileOutputStream("D:\\myf10.txt");
DataOutputStream f1=new
DataOutputStream(f); f1.write(10);
FileInputStream f2=new
FileInputStream("D:\\myf10.txt"); DataInputStream
f3=new DataInputStream(f2);
i
nt i;
while((i=f3.read(
))!=-1)
{
System.out.println(i);
}

f1.close();
f3.close();
Q-12) Write a short note on Stream Tokenizer Class
Ans:
❖ The Java.io.StreamTokenizer class takes an input stream and parses it into
"tokens", allowing the tokens to be read one at a time.
❖ The stream tokenizer can recognize identifiers, numbers, quoted strings, and
various comment styles.
❖ For StreamTokenizer, the source is a character stream, Reader.

❖ Following constant variables used to decide the type of the token:

int ttype When the nextToken() returns a token, this field can be used to
decide the type of the token.

int TT_EOF This field is used to know the end of file is reached.
int TT_EOL This field is used to know the end of line is reached.
int TT_NUMBER This field is used to decide the token returned by the nextToken()
method is a number or not.

int TT_WORD This field is used to decide the token returned by the nextToken()
method is a word or not.

String sval If the token is a word, this filed contains the word that can be used
in programming.

double nval If the token is a word, this filed contains the number that can be
used in programming.
import
java.io.*;
class stto
{
public static void main(String args[])throws
IOException
{
FileReader r=new
FileReader("D:\\myf1.txt");
StreamTokenizer st=new
StreamTokenizer(r); double sum=0;
int n=0;
while(st.nextToken()!=st.TT_EOF
)
{
if(st.ttype==StreamToke
nizer.TT_NUMBER) sum=sum+st.nval;
else
Q-13) Write a shortif(st.ttype==StreamTokenizer.TT_WO
note on Piped Input and Output Stream
Ans: RD) n++;
}
System.out.println
("Sum:" +sum);
❖ The PipedInputStream and PipedOutputStream classes can be used
to read and write data simultaneously.
❖ Both streams are connected with each other using the connect()
method of the PipedOutputStream class.

import
java.io.*; class
pipe
{
public static void main(String args[])
{
PipedOutputStream out=new
PipedOutputStream(); PipedInputStream in=new
PipedInputStream();
try
{
i
n.connect(out);
out.write(23);
out.write(24);
for(int i=0;i<2;i++)

System.out.println(in.read());
}
catch(IOException e)
Q-14) Write a short note on Bridge
{ Class Ans:
InputStreamReader: System.out.println(e);
}
}❖ An InputStreamReader is a bridge from byte streams to character
} streams: It reads bytes and decodes them into characters using a specified
charset.

import
java.io.*; class
br
{
public static void main(String args[])throws IOException
{
FileInputStream f=new
FileInputStream("D:\\myf3.txt"); InputStreamReader r=new
InputStreamReader(f);
int i;
while((i=r.read())!=-1)
{
System.out.println((char)i);
}
r.close();
}
}
❖ OutputStreamWriter is a which is used to convert character stream to
byte stream, the characters are encoded into byte using a specified
charset. write() method calls the encoding converter which converts
the character into bytes.
import
java.io.*; class
br
{
public static void main(String args[])throws IOException
{
FileOutputStream f=new
FileOutputStream("D:\\myf100.txt");
OutputStreamWriter w=new
OutputStreamWriter(f); w.write("hello world");
w.close();
}
}
}

ObjectInputStream and ObjectOutputStream:

import
java.io.*; class
br
{
public static void main(String args[])throws IOException
{
int i=10;
FileOutputStream f=new
FileOutputStream("d:\\myfile101.txt"); ObjectOutputStream
o=new ObjectOutputStream(f); o.writeInt(i);

FileInputStream f1=new
FileInputStream("d:\\myfile101.txt"); ObjectInputStream o1=new
ObjectInputStream(f1); System.out.println("Integer:" +o1.readInt());
;
f.close();
f1.close();
}

}
❖ The objectinputstream class is mainly used to deserialize the
primitive data and objects which are written by using
ObjectOutputStream.

175
Unit-4

Applet and Layout Managers


Q-1 what is Applet? Explain life cycle of
Applet Ans:
❖ In Java, an applet is a special type of program embedded in the web
page to generate dynamic content.
❖ Applet is a class in java.

❖ Appletviewer is a program that can run applet

❖ In java, non-applet programs are called applications.


❖ The Applet package is the package that is specially designed for
working with applets.
Advantage:
1) It works at client side so less time
2) Secured
3) It can be executed by browsers running under many
platforms, including Linux, Mac OS etc
Applet Life Cycle:
The applet life cycle can be defined as the process of how the object is created, started,
stopped, and destroyed during the entire execution of its application. It basically has five
core methods namely init(), start(), stop(), paint() and destroy().These methods are invoked
by the browser to execute.
❖ Following are the methods that are executed during life cycle of
an applet.

1) init():

❖ It is used to initialize the applet

❖ It is invoked when applet is first loaded

❖ It is invoked only once


2) start():
❖ It is invoked after the init()
❖ It is invoked when the applet is started or restarted
3) paint():

❖ This method is invoked immediately after the start()


❖ It is called anytime when the applet needs to repaint itself in the browser.
4) stop():

❖ It is used to stop the applet

❖ It is invoked when the applet stop or browser is minimized


5) destroy():
❖ It is used to destroy the applet

❖ It is invoked only once

❖ It is invoked when the browser unloads the applet

import
java.applet.*; import
java.awt.*;
/*<applet code="ap" width=200 height=200>
</applet>*/
public class ap extends Applet {
String msg="";
public void init()
{
msg+="init()called";
}
public void start()
import
{
java.applet.*; import
msg+="start() called";
java.awt.*;
}
/*<applet code="par"
public void width=200
paint(Graphics g) height=100>
<param
{ name="Stuname" value="xyz">
<param name="roll" value="12">
g.drawString(msg,30,30);
</applet>*/
}
public void stop()
public
{ class par extends Applet
{msg+="stop() called";
} Strin
publicgvoid
name1;
destroy()
{ String roll;
Font f1; msg+="destroy called";
} public void init()
} {
f1=new
Font("Arial",Font.BOLD,32);
name1=getParameter("Stuname");
Q-2 How to pass parameters in
roll=getParameter("roll");
Applet. Ans: }
public void paint(Graphics g)
❖ To pass the { parameters to the Applet we need to use the param
attribute of <applet> g.setFont(f1);
tag.
g.drawString("Name:"
❖ To retrieve a parameter's
+ name1,50,20); value, we need to
g.drawString("Roll:"
use the +roll,250,20);
getParameter() method of Applet
}
}
class.

Q-3 Write a short note on graphics


class Ans:
❖ Following is the list of graphics class:
o Flow Laoyout
o Border Layout
o Card Layout
o Grid Layout
o GridBag Layout
Flow Layout

❖ The Java FlowLayout class is used to arrange the components in a line,


one after another (in a flow). It is the default layout of the applet or
panel

import
java.applet.*; import
java.awt.*;
/*<applet code="flowl" width=200 height=200>
</applet>*/

public class flowl extends Applet


{
Label
b1,b2,b3; public
void init()
{
setLayout(new
FlowLayout()); b1=new
Label("OK"); b2=new
Label("Open"); b3=new
Label("Close"); add(b1);
add(b2);
add(b3);

}
}
Border Layout:

The BorderLayout is used to arrange the components in five regions: north, south,
east, west, and center. Each region (area) may contain one component only. It is the
default layout of a frame or window. The BorderLayout provides five constants for
each region:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
import
java.applet.*; import
java.awt.*;
/*<applet code="flowl" width=200 height=200>
</applet>*/

public class flowl extends Applet


{
Button
b1,b2,b3,b4,b5; public
void init()
{
setLayout(new
BorderLayout()); b1=new
Button("NORTH"); b2=new
Button("SOUTH"); b3=new
Button("EAST"); b4=new
Button("WEST"); b5=new
Button("CENTER");
add(b1,BorderLayout.NORTH);
add(b2,BorderLayout.SOUTH);
add(b3,BorderLayout.EAST);
Grid Layout:add(b4,BorderLayout.WEST);
add(b5,BorderLayout.CENTER);
The Java Grid Layout class is used to arrange the
}
} components in a rectangular grid. One component is displayed in
each rectangle.
Card Layout:
Example:
❖ The Java CardLayout class manages the components in such a manner
that only one component is visible at a time. It treats each component as
a card that is why it is known as CardLayout.

Example:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

/*<applet code="card" width=200 height=200>


</applet>*/

public class card extends Applet


{
Button
b1,b2,b3; Font f;

public void init()


{
f=new Font("Arial",
Font.BOLD,32); setLayout(new
CardLayout); b1=new Button("OK");
b2=new
Button("Cancel"); b3=new
Button("Close");
b1.setFont(f);
b2.setFont(f);
b3.setFont(f);
add(b1);
add(b2);
add(b3);
}

Grid BagLayout:

The Java GridBagLayout class is used to align components


vertically, horizontally or along their baseline.
The components may not be of the same size. Each
GridBagLayout object maintains a dynamic, rectangular grid of cells.
Unit-5:
Each component
occupies one or more cells known as its display area
GUI using swing and Event Handling

Q-1 what is Awt? What is


Swing? Ans:
Awt:
❖ AWT and Swing are used to
Swing:
develop window-based
applications in Java.
❖ Awt is an abstract window toolkit
that provides various component
classes like Label, Button,
TextField, etc., to show window
components on the screen. All
these classes are part of the
Java.awt package.

❖ On the other hand, Swing is the


part of JFC (Java Foundation
Classes) built on the top of AWT
and written entirely in Java. The
javax.swing API provides all the
component classes like JButton,
JTextField, JCheckbox, JMenu,
etc.
❖ The components of Swing are
platform-independent, i.e., swing
doesn't depend on the operating
system to show the components.
Also, the Swing's components are
lightweight

Q-2 Differentiate Awt and Swing


Components Ans:
Difference between Awt and Swing Components:
Awt Components Swing Components
1) Awt components classes are 1) Swing components are provided by
provided by jawa.awt package javax.swing package
2) The Components used in AWT are The Components used in Swing are
mainly dependent on the operating not dependent on the operating
system. system. It is completely scripted in
Java.
3) The AWT is heavyweight since it 3) The Swing is mostly lightweight
uses the resources of the operating since it doesn't need any Operating
system.
system object for processing. The
Swing Components are built on the top
of AWT.

4) The Appearance of AWT 4) The Swing Components are


Components is mainly not configurable and mainly support
configurable. It generally depends on pluggable look and feel
the operating system's look and feels.
5) The Java AWT provides a smaller 5) Java Swing provides a greater
number of components in comparison number of components than AWT,
to Swing. such as list, scroll panes, tables, color
choosers, etc.
6) Java AWT has 21 peers There is one 6) Java Swing has only one peer in the
peer for each control Peers are form of OS's window object, which
provided by the operating system in provides the drawing surface used to
the form of widgets themselves. draw the Swing's widgets
7) Java AWT needs a higher amount 7) Java Swing needs less memory
of memory for the execution. space as compared to Java AWT.

8) Java AWT is slower than swing in 8) Java Swing is faster than the AWT.
terms of performance.

Q-3 Write a short note on Swing Components:


Ans:

1) Image Icon:

❖ The ImageIcon component creates an icon sized-image from an


image residing at the source URL.
Example:

ImageIco
n homeIcon = new
ImageIcon(“src/images/home.jpg”);
❖ This returns an icon of a home button. The string parameter is the path
at which the source image is present.

2) JButton:

❖ JButton class is used to create a push-button on the UI.


❖ The button can contain some display text or image.
❖ It generates an event when clicked and double-clicked.
❖ A JButton can be implemented in the application by calling one of
its constructors.

Example:
JButton okBtn = new JButton(“Ok”);
❖ This constructor returns a button with text Ok on it.

JButton homeBtn = new JButton(homeIcon);


❖ It returns a button with a homeIcon on it.
JButton btn2 = new JButton(homeIcon, “Home”);
3) JLabel:

❖ JLabel class is used to render a read-only text label or images on the


UI. It does not generate any event.
Example:
JLabel textLbl = new JLabel(“This is a text label.”);
❖ This constructor returns a label with text.
JLabel imgLabel = new JLabel(homeIcon);

❖ It returns a label with a home icon.

4) JTextField:

❖ JTextField renders an editable single-line text box.

❖ A user can input non-formatted text in the box.

❖ To initialize the text field, call its constructor and pass an optional integer
parameter to it. This parameter sets the width of the box measured by the
number of columns.
❖ It does not limit the number of characters that can be input in the box.
Example:
JTextField txtBox = new JTextField(20);
It renders a text box of 20 column width.
5) JTextArea:
❖ JTextArea class renders a multi-line text box. Similar to the JTextField,
a user can input non-formatted text in the field.
❖ The constructor for JTextArea also expects two integer parameters
which define the height and width of the text-area in columns.
❖ It does not restrict the number of characters that the user can input in
the text-area.
Example:
JTextArea txtArea = new JTextArea(“This text is default text for text area.”, 5,
20);
❖ The above code renders a multi-line text-area of height 5 rows and
width 20 columns, with default text initialized in the text-area.

6) JPasswordField:
JPasswordField is a subclass of JTextField class. It renders a text-box that masks
the user input text with bullet points. This is used for inserting passwords into the
application.
Example:
JPasswordField pwdField = new JPasswordField(15);
var pwdValue = pwdField.getPassword();
❖ It returns a password field of 15 column width. The getPassword
method gets the value entered by the user.

7) JCheckBox:
❖ JCheckBox renders a check-box with a label. The check-box has two
states – on/off. When selected, the state is on and a small tick is
displayed in the box.
Example:
CheckBox chkBox = new JCheckBox(“Show Help”, true);
It returns a checkbox with the label Show Help. The second
parameter in the constructor. It is a boolean value that indicates the
default state of the check-box. True means the check-box is
defaulted to on state.

8) JRadioButton:

❖ JRadioButton is used to render a group of radio buttons in the UI. A


user can select one choice from the group.
Example:
ButtonGroup radioGroup = new ButtonGroup();
JRadioButton rb1 = new JRadioButton(“Easy”, true);
JRadioButton rb2 = new JRadioButton(“Medium”);
JRadioButton rb3 = new JRadioButton(“Hard”);
radioGroup.add(rb1);
radioGroup.add(rb2);
radioGroup.add(rb3);

❖ The above code creates a button group and three radio button elements.
All three elements are then added to the group. This ensures that only
one option out of the available options in the group can be selected at a
time.

9) JList:

❖ JList component renders a scrollable list of elements. A user can select


a value or multiple values from the list. This select behavior is defined
in the code by the developer.
Example:
DefaultListItem cityList = new DefaultListItem();
cityList.addElement(“Mumbai”):
cityList.addElement(“London”):
cityList.addElement(“New York”):
cityList.addElement(“Sydney”):
cityList.addElement(“Tokyo”):
JList cities = new
JList(cityList);
cities.setSelectionModel(ListSelectionModel.SINGLE_SELECTION);
❖ The above code renders a list of cities with 5 items in the list
❖ . The selection restriction is set to SINGLE_SELECTION. If
multiple selections is to be allowed, set the behaviour to
MULTIPLE_INTERVAL_SELECTION.

10) JComboBox:

❖ JComboBox class is used to render a dropdown of the list of options.


Example:
String[] cityStrings = { "Mumbai", "London", "New York", "Sydney",
"Tokyo" };
JComboBox cities = new JComboBox(cityList);
cities.setSelectedIndex(3);

❖ The default selected option can be specified through the


setSelectedIndex method. The above code sets Sydney as the default
selected option.

11) JFileChooser

❖ JFileChooser class renders a file selection utility. This component lets


a user select a file from the local system.
Example:
JFileChooser fileChooser = new JFileChooser();
JButton fileDialogBtn = new JButton(“Select File”);
fileDialogBtn.AddEventListner(new ActionListner(){
fileChooser.showOpenDialog();
})
var selectedFile = fileChooser.getSelectedFile();

❖ The above code creates a file chooser dialog and attaches it to the button.

❖ The button click would open the file chooser dialog.


❖ The selected file is returned through the getSelectedFile method.

12) JTabbedPane:
JTabbedPane is another very useful component that lets the user switch between tabs in an
application. This is a highly useful utility as it lets the user browse more content without
navigating to different pages.
Example:
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab(“Tab 1”, new JPanel());
tabbedPane.addTab(“Tab 2”, new JPanel());

❖ The above code creates a two tabbed panel with headings Tab 1 and
Tab

13) JSlider:

❖ JSlider component displays a slider which the user can drag to change
its value. The constructor takes three arguments – minimum value,
maximum value, and initial value.
Example:
JSlider volumeSlider = new JSlider(0, 100, 50);
var volumeLevel = volumeSlider.getValue();
Q-3 Write a short note on Event Delegation Model
Ans:
❖ It defines a standard and compatible mechanism to generate and process
events. In this model, a source generates an event and forwards it to one or
more listeners. The listener waits until it receives an event.
❖ Once it receives the event, it is processed by the listener and returns it. The
UI elements are able to delegate the processing of an event to a separate
function.
❖ The key advantage of the Delegation Event Model is that the application
logic is completely separated from the interface logic.
❖ In this model, the listener must be connected with a source to receive the
event notifications. Thus, the events will only be received by the listeners
who wish to receive them.
❖ Basically, an Event Model is based on the following three components:
o Events

o Events Sources
o Events Listeners
Events

❖ The Events are the objects that define state change in a source.
❖ An event can be generated as a reaction of a user while interacting with
GUI elements. Some of the event generation activities are moving the
mouse pointer, clicking on a button, pressing the keyboard key etc

Event Sources

❖ A source is an object that causes and generates an event. It generates an


event when the internal state of the object is changed. The sources are
allowed to generate several different types of events.

Event Listeners
❖ An event listener is an object that is invoked when an event
triggers. The listeners require two things; first, it must be registered with
a source;
however, it can be registered with several resources to receive notification about
the events. Second, it must implement the methods to receive and

Example:
import javax.swing.*;
import
java.awt.event.*;
public class ac1 implements
ActionListener
{
JTextField t;
ac1()
{
JFrame
JButton b1=new
JButton("Submit");
b1.setBounds(80,
200,80,30); t=new JTextField();
t.setBounds(80,250,80,30);
f.add(b1);
f.add(t);
b1.addActionListener(this);
f.setLayout(null);
f.setSize(300,300);
f.setVisible(true);
}
public void
actionPerformed(ActionEvent e)
{
t.setText("Hello
World");
}
public static void main(String args[])
{
ac1 a=new ac1();
Q-3 Write a short note on Event packages OR
Write a short note on Awt and swing Event Package
Ans:

❖ The java.awt.event package defines classes and interfaces used for


event handling in the AWT and Swing. The members of this package
fall into three categories:

Event Class:
❖ The classes with names ending in "Event" represent specific types
of events, generated by the AWT or by one of the AWT or Swing
components.

Listeners:

❖ The interfaces in this package are all event listeners; their names end with
"Listener". These interfaces define the methods that must be implemented
by any object that wants to be notified when a particular event occurs.
❖ There is a listener interface for each Event Class.

Adapters:

❖ Java adapter classes provide the default implementation of


listener interfaces. If you inherit the adapter class, you will not be forced
to provide the implementation of all the methods of listener interfaces. So
it saves code.
Java Event classes and Listener interfaces
3) Action Event:
❖ The ActionEvent is generated when button is clicked or the item of a
list is double clicked.
❖ It is notified against ActionEvent.

❖ The ActionListener interface is found in java.awt.event package.


❖ It has only one method: actionPerformed().

actionPerformed():

❖ The actionPerformed() method is invoked automatically whenever you


click on the registered component.
4) Item Event:

The Java ItemListener is notified whenever you click on the


checkbox. It is notified against ItemEvent.
The ItemListener interface is found in java.awt.event package.

It has
import only one method: itemStateChanged().
javax.swing.*;
import
java.awt.event.*;
itemStateChanged():

Theclass
public itemStateChanged() method is invoked automatically whenever you
check implements ItemListener
{
click or unclick on the registered checkbox component.
JFrame f;
JCheckBox
c1,c2; JLabel l;
check()
{
f=new
JFrame();
l=new JLabel();
l.setBounds(50,100,50,50);
c1=new JCheckBox("C#");
c1.setBounds(100,150,50,50);
c2=new JCheckBox("Java");
c2.setBounds(100,250,50,50);
c1.addItemListener(this);
c2.addItemListener(this);
f.add(c1);
f.add(c2);
f.add(l);
f.setLayout(null);
f.setSize(300,300);
f.setVisible(true);
}
public void itemStateChanged(ItemEvent e)
{
if(e.getSource()==c1)
l.setText("Checkbox 1 checked");
else
l.setText("Checkbox 2 checked");
}

public static void main(String args[])


{ 2 01

check e=new check();


}
}

5) Focus Event:
❖ A low-level event which indicates that a component has gained or
lost the input focus
❖ The ItemListener interface is found in java.awt.event package.

❖ It has only two methods: foucsGained() and focusLost()

foucsGained():

❖ This method is invoked automatically whenever any component gains


the focus.

focusLost()

❖ This method is invoked automatically when window is closed. The


focus is lost when the window is closed.
6) Adjustment Event:
❖ The adjustment event emitted by Adjustable objects like
Scrollbar and Scroll Pane.
❖ When the user changes the value of the scrolling component, it
receives an instance of Adjustment Event.
❖ It has only one method: adjustmentValueChanged()

adjustmentValueChanged():
7) Window Event:
❖ A low-level event that indicates that a window has changed its status.
❖ This low-level event is generated by a Window object when it is opened,
closed, activated, deactivated, iconified, or deiconified, or when focus 2is
transfered into or out of the Window.
❖ It has only following methods:

windowOpened():
❖ This method is executed only the first time a window is made visible.

windowClosed():
❖ This method is executed when the window has been closed

WindowActivated():
❖ This event is delivered when the Window becomes the active window

WindowDeactivated():
❖ This event is delivered when the Window is no longer active window.

WindowClosing():
❖ This event is delivered when the user attempts to close the window
from the window's system menu

WindowIconified():
❖ This event is delivered when the window has been changed from
a normal to a minimized state

WindowDeiconified():

❖ This event is delivered when the window has been changed from
a minimized to a normal state.

Example:
Entered():

❖ This method is executed when the mouse cursor enters into


specific component.

mouseExited():
❖ This method is executed when the cursor leaves the specific component

mousePressed(): This event is executed when the mouse is being pressed in the
component area
mouseReleased():
❖ This event is executed when the mouse is released from the
component area.

mouseClicked():
❖ This event is delivered when the mouse is clicked in the component area.
9) MouseWheel Event:

❖ An event which indicates that the mouse wheel was rotated in


a component.
❖ A wheel mouse is a mouse which has a wheel in place of the
middle button.
❖ This wheel can be rotated towards or away from the user.
❖ It has only one method: mouseWheelMoved()

mouseWheelMoved(): This method is executed when mouse wheel is rotated


or moved in the component.

❖ An event which indicates that an object’s text changed.


❖ It is generated by an object when its text changes.
❖ The event is passed to every Text Listener object which registered
to receive such events using the component's addTextListener
method.
❖ It has only one method: textValueChanged()

textValueChanged(): This method is executed when object’s text changes.

import javax.swing.*;
import java.awt.event.*;

public class w1 implements TextListener


{
JFrame f;
JTextField t;
w1(){
f
=new JFrame();
t=new JTextField();
t.setBounds(
80,150,80,30);
t.addTextListener(this);
f.add(t);
f.set
Layout(null);
f.setSize(300,300);
f.setVisible(true);
}
public void textValueChanged(TextEvent e)
{
t.setText(“Text Changed”);
}

public static void main(String args[])


{
w1 e=new w1();
}
}

Q-4 Write a short note on Adapter Class Ans:


❖ Java adapter classes provide the default implementation
of listener interfaces
❖ If you inherit the adapter class, you will not be forced to provide the
implementation of all the methods of listener interfaces. So it saves
code.

Pros of using Adapter classes:


o It assists the unrelated classes to work combined.
o It provides ways to use classes in different ways.
o It increases the transparency of classes.
o It provides a way to include related patterns in the class.
o It provides a pluggable kit for developing an application.
o It increases the reusability of the class.

❖ The adapter classes are found in java.awt.event, java.awt.dnd and


javax.swing.event pacakges.
❖ Mouse Adapter:
❖ An abstract adapter class for receiving keyboard focus events.
import javax.swing.*; import
java.awt.event.*;

public class key1 extends MouseAdapter


{
JFrame f; JTextArea ta,ta1;
key1()
{
f=new JFrame(); ta=new JTextArea();
ta1=new JTextArea();
ta.setBounds(80,150,80,70);
ta.addKeyListener(this);
ta1.setBounds(80,250,80,70);
ta1.addMouseListener(this); f.add(ta);
f.add(ta1); f.setLayout(null);
f.setSize(300,300); f.setVisible(true);
}
public void mouseDragged(MouseEvent e)
{
ta1.setText("Dragged");
}
public static void main(String args[])
{
key1 k=new key1();
}
}
1) Box Layout:
❖ The BoxLayout class is used to arrange the components either vertically
(along Y-axis) or horizontally (along X-axis).

In BoxLayout class, the components are put either in a single row or a single
column
2) Group Layout:
❖ GroupLayout groups its components and places them in a Container
hierarchically. The grouping is done by instances of the Group class.
❖ Group is an abstract class, and two concrete classes which implement
this Group class are SequentialGroup and ParallelGroup.
❖ SequentialGroup positions its child sequentially one after another
whereas ParallelGroup aligns its child on top of each other.
❖ The GroupLayout class provides methods such as
createParallelGroup() and createSequentialGroup() to create groups.
❖ GroupLayout treats each axis independently. That is, there is a group
representing the horizontal axis, and a group representing the vertical
axis. Each component must exist in both a horizontal and vertical group,
otherwise an IllegalStateException is thrown during layout or when the
minimum, preferred, or maximum size is requested.
3) Spring Layout:
❖ A SpringLayout arranges the children of its associated
container according to a set of constraints.
❖ Constraints are nothing but horizontal and vertical distance between
two- component edges.
❖ Every constraint is represented by a SpringLayout.Constraint object.
❖ Each child of a SpringLayout container, as well as the container itself,
has exactly one set of constraints associated with them.
❖ Each edge position is dependent on the position of the other edge. If
a constraint is added to create a new edge, than the previous binding
is discarded. SpringLayout doesn't automatically set the location of
the components it manag
1) Write a program to demonstrate use of arithmetic operator

import java.util.*;
class arithmetic
{
public static void main(String args[])
{
int a,b;
Scanner sc=new Scanner(System.in);
System.out.println(“Enter a”);
a=sc.nextInt(); System.out.println(“Enter
b”); b=sc.nextInt();
System.out.println(“Addition=” +(a+b));
System.out.println(“Sub is” +(a-b));
System.out.println(“Mul is” +(a*b));
System.out.println(“Div is”+(a/b));
System.out.println(“Modulas is” +(a%b));
}
}

Output:
Enter a 10
Enter b 5
Addition=15
Sub is 5
Mul is 50
Div is 2
2) Write a program to demonstrate use of relational operator
import java.util.*;
class arithmetic
{
public static void main(String args[])
{
int a,b;
Scanner sc=new Scanner(System.in);
System.out.println(“Enter a”);
a=sc.nextInt();
System.out.println(“Enter b”);
b=sc.nextInt();
System.out.println(“> than” +(a>b));
System.out.println(“< than” +(a<b));
System.out.println(“>= is” +(a>=b));
System.out.println(“<=”+(a<=b));
System.out.println(“== is” +(a==b));
System.out.println(“!= is” +(a!=b));
}
}
Output:
Enter a 10
Enter b 5
1
0
1
0
0
1

3) Write a program to demonstrate use of logical operator


import java.util.*;
class arithmetic
{
public static void main(String args[])
{
int a,b,c;
Scanner sc=new Scanner(System.in);
System.out.println(“Enter a”);
a=sc.nextInt();
System.out.println(“Enter b”);
b=sc.nextInt();
System.out.println(“Enter c”);
c=sc.nextInt();
if(a>b && a>c)
System.out.println(“a is max”);
else if(b>c && b>a)
System.out.println(“b is max”);
else
System.out.println(“c is max”);
}
}

Output:
Enter a 10
Enter b 5
Enter c 2
a is
max
4) Write a program to demonstrate use of decision control
structure (switch case)
import java.util.*;
class dc
{
public static void main(String args[])
{
int a,b,ch;
Scanner sc=new Scanner(System.in);
System.out.println(“Enter a”);
a=sc.nextInt();
System.out.println(“Enter b”);
b=sc.nextInt();
System.out.println(“Enter 1.add 2.sub 3.mul 4.div”);
ch=sc.nextInt();
switch(ch)
{
case 1:
System.out.println(a+b);
break;

case 2:
System.out.println(a-b);
break;

case 3:
System.out.println(a*b);
break;

case 4:
System.out.println(a/b);
break;
default:
System.out.println(“Invalid”);
break;
Output: }
Enter a 10
} Enter b 11
} Enter 1.add 2.sub 3.mul
4.div 3 110
5) Write a program to demonstrate use of for loop

class loop
{
public static void main(String args[])
{
int i;
for(i=1;i<=5;i++)
{
System.out.println(i);
}
Output:
1
2
3
4
5
Write a program to demonstrate use of while loop

class loop
{
public static void main(String args[])
{
int i=1;
while(i<=5)
{
System.out.println(i);
i++;
}
}
Output:
1
2
3
4
5
6) Write a program to demonstrate use of jumping statements (break)

class jm
{
public static void main(String args[])
{
int i;
for(i=1;i<=5;i++)
{
if(i==3)
break;
System.out.println(i);
}
}
Output:
1
2

7) Write a program to demonstrate use of jumping statements


(continue)

class jm
{
public static void main(String args[])
{
int i;
for(i=1;i<=5;i++)
{
if(i==3)
continue;
System.out.println(i);
}
}
Output:
1
2
4
5

8) Write a program to demonstrate use of type casting

class exp1
{
public static void main(String args[])
{
int x;
double f=2.5;
x=(int)f;
System.out.println(x);
}
}

class exp1
{
public static void main(String args[])
{
int i;
int a[]=new int[5];
a[0]=10;
a[1]=11;
a[2]=12;
a[3]=13;
a[4]=14;
for(i=0;i<a.length;
i++) System.out.println(a[i]);
}
Output:
10
11
12
13
14
17) Write a program to demonstrate use of 1 dimensional
array (inputting the values from the user)

import java.util.*;
class arr
{
public static void main(String args[])
{
int i;
int a[]=new int[5];
Scanner sc=new Scanner(System.in);
for(i=0;i<5;i++)
{
System.out.println("Enter array elements");
a[i]=sc.nextInt();
}
for(i=0;i<5;i++)
{
System.out.println("Array ele" +a[i]);
}
}
Output:
}
Enter array elements Array ele
10 10
11 11
12 12
13 13
14 14

18) Write a program to print hello using command line arguments

class cmd1
{
public static void main(String args[])
{
System.out.println(args[0]);
}
}
Output:
hello
19) Write a program to print value using command line arguments

class cmd1
{
public static void main(String args[])
{
int i;
for(i=0;i<args.length;i++)
{
System.out.println(args[i]);
}
}
}
Output:
10

20) Write a program to demonstrate use of class and object

class student
{
int roll;
String name;
}
class sample
{
public static void main(String args[])
{
student s=new student();
s.roll=1;
s.name="xyz";
System.out.println(s.roll);
System.out.println(s.name);
}
}
Output
:1
xy
21) Write a program to demonstrate use of multi level inheritance
class Animal
{
void eat()
{
System.out.println("Eating");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("Barking");
}
}
class BabyDog extends Dog
{
void sleep()
{
System.out.println(“Sleeping”);
}
}
class single
{
public static void main(String args[])
{
Output:
BabyDog bd=new BabyDog();
Eating d.bark();
Barking d.eat();
Sleeping
d.sleep();
}
}
22) Write a program to demonstrate use of hierarchical inheritance
class Animal
{
void eat()
{
System.out.println("Eating");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("Barking");
}
}
class cat extends Animal
{
void sleep()
{
System.out.println(“Sleeping”);
}
}
class single
{
Output:
public static void main(String args[])
Eating
Barking {
Eating cat c=new cat();
Sleeping c.eat();
c.sleep();
23) Write a program to demonstrate use of default constructor

class A
{
A()
{
System.out.println("Default constructor");
}
}

class inhe
{
public static void main(String args[])
{
A a1=new A();
}
Output: Default constructor
}
24) Write a program to demonstrate use of constructor overloading

class Aint roll;


A(int r)
{
roll=r;
}
void display()
{
System.out.println(roll);
}
}

class inhe
{
public static void main(String args[])
{
A a1=new A(10);
a1.display();
Output: }
}
10
25) Write a program to demonstrate use of constructor overloading
class cons
{
int roll;
String name;
cons()
{
System.out.println("Hello");
}
cons(int r)
{
roll=r;
}
cons(int r,String n)
{
roll=r;
name=n;
}
void display()
{
System.out.println(roll);
System.out.println(name);
}
}
class consoverload
{
public static void main(String args[])
{
cons c=new cons();
cons c1=new cons(10);
Output: cons c2=new cons(10,"xyz");
c1.display();
Hell c2.display();
0 10 }
}
10,xyz
26) Write a program to demonstrate use of static and non-static
data members

class test
{
static int a=20; void
display()
{

a++;
System.out.println(a);
}

}
class sample
{
public static void main(String args[])
{
test t1=new test(); test t2=new
test(); test t3=new test();
t1.display(); Output: 21,22,23
t2.display();
t3.display();
Non-static
}
class test
}
{
int a=20; void
display()
{

a++;
System.out.println(a);
}

}
class sample
{
public static void main(String args[])
{
test t1=new test();
test t2=new test();
test t3=new test();
t1.display(); Output: 21,21,21
27) Write a program to demonstrate use of vargs

class varg
{
static void display(int...values)
{
System.out.println("hello");

for(int i:values)
System.out.println(i);
}
public static void main(String args[])
{
display();
display(1,2,3,4);
display(12,22);
}
28) }Write a program to demonstrate use of private access specifier

class A
{
private int data=40;
private void msg()
{
System.out.println("Hello
java");
}
.class Simple
{
. public static void main(String args[])
{
. A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}

Output:
Error
29) Write a program to demonstrate use of default access specifier

//Save this with A.java (Package 1)

package pack;
class A
{
void display()
{
System.out.println(“Hello”);
}
}

//Save this with B.java (Package 2)

package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj=new A();
obj.display();
}
}

Output:
Cannot be accessed outside the package
Write a program to demonstrate use of protected access specifier
//Save this with A.java (Package 1)

package pack;
public class A
{
protected void display()
{
System.out.println(“Hello”);
}
}

30) Write a program to demonstrate use of public access specifier

//Save this with A.java (Package 1)

package pack;
public class A
{
public void display()
{
System.out.println(“Hello”);
}
}
31) Write a program to demonstrate use of constructor in single
level inheritance

Output:
parent class constructor
child class constructor
class parent
{
parent()
{
System.out.println("Parent class constructor");
}
}
class child extends parent
{
child()
{
System.out.println("Child class constructor");
}
}
class child1 extends child
{

child1()
{
System.out.println("Child1 constructor");
}
}
class sample
{
public static void main(String args[])
child1 class constructor
{
child1 c=new child1();
}
}
32) Write a program to demonstrate use of interface

interface draw
{
void print();
}

class rectangle implements draw


{
public void print()
{
System.out.println("draw rectangle");
}
}
class circle implements draw
{
public void print()
{
System.out.println("draw circle");
}
}
class test
{
public static void main(String args[])
{
circle
c1=new circle();
c1.print();
rectangle r=new
rectangle(); r.print();

Output:
draw circle
draw rectangl
33) Write a program to demonstrate use of non-static nested class

class outer
{
int
x=10; class
inner
{
int y=4;
}
}

class nested
{
public static void main(String args[])
{
outer o=new
outer(); outer.inner i=o.new
inner(); System.out.println(i.y);
System.out.println(o.x);
}
Output
:}4
10
34) Write a program to demonstrate use of static nested class

class outer
{
int x=10;
static class inner
{
int y=4;
}
}

class nested
{
public static void main(String args[])
{
outer.inner i=new
outer.inner(); System.out.println(i.y);
System.out.println(i.x);//will generate error
}
}
Output:
4
will generate error

Write a program to demonstrate use of abstract class

abstract class bike


{
abstract void
run(); void display()
{
System.out.println("hello");
}
}

class honda extends bike


{
public void run()
{

System.out.println("hi");
}
}

class sampe
{
public static void main(String args[])
{
honda
h=new honda(); h.run();
h.display();
Output }
: }hello
hi
35) Write a program to demonstrate use of final keyword
Output:

final class bike


{

class ja extends bike


{
void display()
{
System.out.println("hi");
}
public static void main(String args[])
{
bike b=new bike();
Compile time error b.display(); //Compile time error
}
Write a program to demonstrate use of normal import
}

Output:
5
4
36) Write a program to demonstrate use of static import :

import static java.lang.Math.*;

class ke
{
public static void main(String args[])
{
System.out.println(sqrt(25));
System.out.println(pow(2,2));
}
}
Output
:5
4
37) Write a program to demonstrate use of String class (java.lang)

class stringfunctions
{
public static void main(String args[])
{
String s="hello";
String s1="hello";
String s3="karishma";
String s4="rupani";
String s5="hi";
String s6="Hi";
System.out.println("Charat" +s.charAt(1));
System.out.println("length" +s.length());
System.out.println("substring" +s.substring(1));
System.out.println("substring" +s.substring(1,3));
System.out.println("index" +s.contains("el"));
System.out.println("Equality" +s.equals(s1));
System.out.println("Empty" +s.isEmpty());
System.out.println("Concate"+s3.concat(s4));
System.out.println("replace"+s.replace('l','k'));
System.out.println("Uppercase" +s3.toUpperCase());
System.out.println("Lowercase" +s3.toLowerCase());
System.out.println("IndexOf" +s.indexOf('o'));
System.out.println("ignorecase" +s5.equalsIgnoreCase(s6));

}
}
Output
:e
5
ello
ell 1
1
0
karishmrupani
hekko
KARISHMA
Karishma
4
1
38) Write a program to demonstrate use of StringBuffer class (java.lang)

class stringfunctions
{
public static void main(String args[])
{
StringBuffer s=new StringBuffer("hello");
System.out.println("Length" +s.length());
System.out.println("Specified" +s.insert(2,"hi"));
System.out.println("Replace" +s.replace(1,3,"ee"));
System.out.println("Deleting" +s.delete(1,3));
System.out.println("Reversing" +s.reverse());
System.out.println("Capacity" +s.capacity());
System.out.println("Charat" +s.charAt(2));
System.out.println("Substring" +s.substring(1));
39) Write a program to demonstrate use of random class
}
import java.util.*;
class randomn
{
public static void main(String args[])
{
Random r=new Random();
System.out.println("Integer val" +r.nextInt());
System.out.println("Next decimal" +r.nextDouble());
}
}
40) Write a program to demonstrate use of Date class
import java.util.*;

public class main1


{
public static void main(String[] args)
{
Date d=new Date();
Date d1=new Date(21-
11-2010); Date d2=new Date(25-
6-2022);
// Creating date
System.out.println("Current date: " +d);
System.out.println("Checking"+d1.before(
d)); System.out.println("after" +d.after(d2));
System.out.println("Clone object" +d.clone());
System.out.println("Compare" +d.compareTo(d1));
System.out.println("Equlas" +d.equals(d1));
System.out.println("Time" +d.getTime());
System.out.println("Hashcode" +d.hashCode());
}
}
41) Write a program to demonstrate use of Collection class

import java.util.*;
class greg
{
public static void main(String args[])
{
Vector<Integer>ve=new Vector<Integer>(5);
ve.add(10);
ve.add(20);
ve.add(30);
ve.addElement(40);
System.out.println("Elements of vector" +ve);
System.out.println("Clone" +ve.clone());
System.out.println("Capacity" +ve.capacity());
System.out.println("Size" +ve.size());
System.out.println("Firstelement" +ve.firstElement());
System.out.println("Firstelement" +ve.lastElement());
System.out.println("Index" +ve.indexOf(20));
System.out.println("Contains" +ve.contains(10));
ve.remove(0);
System.out.println("Elements after removal" +ve);
}
}
42) Write a program to demonstrate use of Hashtable class
import java.util.*;
class hash1
{
public static void main(String args[])
{
Hashtable<Integer,String> h=new Hashtable<Integer,String>();
h.put(1,"abc");
h.put(2,"xyz");
System.out.println("Mapping" +h);
h.put(2,"ddd");
System.out.println("Mapping" +h);
h.remove(2);
System.out.println("Mapping" +h);
System.out.println("Check key:" +h.containsKey(1));
System.out.println("Check value: "+h.containsValue("abc"));
}
}
43) Write a program to demonstrate use of linked list class
import java.util.*;
class linked
{
public static void main(String args[])
{
LinkedList<String>s=new LinkedList<String>();
s.add("A");
s.add("B");
s.add("C");
s.addLast("D");
s.addFirst("E");
System.out.println(s);
s.remove("C");
s.removeFirst();
s.removeLast();
System.out.println(s);
}
44)} Write a program to demonstrate use of Stack class

import java.util.*;
class stack
{
public static void main(String args[])
{
Stack<Integer> s=new Stack<Integer>();
s.push(10);
s.push(11);
s.push(12);
s.push(13);
s.push(14);
System.out.println(s);
s.pop();
System.out.println(s);
System.out.println("Stack empty :"+s.empty());
System.out.println("Search :"+s.search(11));
System.out.println("Peek: "+s.peek());
}
}
45) Write a program to demonstrate use of Queue class

import java.util.*;
class que
{
public static void main(String args[])
{
PriorityQueue<String> p=new PriorityQueue<String>();
p.add("abc");
p.add("xyz");
p.add("aaa");

System.out.println("Queue ele: "+p);


p.remove();
System.out.println("After removal: "+p);
System.out.println("Poll: "+p.poll());
System.out.println("After poll:" +p);
System.out.println("Peek: "+p.peek());
}
}

46) Write a program to demonstrate use of exception handling

class exc
{
public static void main(String args[])
{
try
{
int a=5/0;
}catch(ArithmeticException e)
{
System.out.println(e);
}
finally
{
System.out.println("hi");
}
Output
: hi }
}
47) Write a program to demonstrate use of Thread Class using
Runnable interface

class m extends implements Runnable


{
public void run()
{
System.out.println(“Runnin
g”);
}
public static void main(String args[])
{
m m1=new m();
Thread t1=new
Thread(m1); t1.start();
Output:
}
Running
}
48) Write a program to demonstrate use of Thread Class properties

class th
{

public static void main(String args[])


{
Thread t1=new Thread("First Thread");
System.out.println("Thread Priority: "+t1.getPriority());
t1.setPriority(6);
t1.start();
t1.setName("My Thread");
System.out.println("Thread Name: "+t1.getName());
System.out.println("Thread Priority:
"+t1.getPriority()); System.out.println("Daemon Thread:
"+t1.isDaemon());
}
}
Output:
Thread Name: My Thread
Thread Priority: 6
Daemon Thread: 0
49) Write a program to demonstrate use of Thread Synchronization

class mythread2 extends Thread


{
table t;
mythread2(table t)
{
this.t=t;
}
public void run()
{
t.printtable(5);
}
}

class synch
{
public static void main(String args[])
{
table o=new table();
mythread1 t1=new
mythread1(o); mythread2 t2=new
mythread2(o); t1.start();
t2.start();
}
50)} Write a program to demonstrate use of File Class
import java.io.*;
class filedemo
{
public static void main(String args[])
{
File f=new
File("d:\\th123.java"); if(f.isFile())
System.out.println("\n File
Exists");
else
System.out.println("\n File
does not exists");
}
51) Write a program to demonstrate use of new file creation

import java.io.*;
import java.io.IOException;
class crf
{
public static void main(String args[])
{
try
{
File f=new
File("D:\\hel.txt");
if(f.createNewFile())
System.out.println("Created");
else
System.out.println("Not Created");
}
catch(IOException e)
{
52) Write a program to demonstrate System.out.println(e);
use of file information

}
}
import java.io.*;
import java.io.IOException;

class crf
{
public static void main(String args[])
{

File f=new
File("D:\\hel.txt"); if(f.exists())
{
System.out.println("Name of file:
"+f.getName()); System.out.println("Path of file:
"+f.getAbsolutePath());
System.out.println("Path of file:
"+f.length());
}
else
{
System.out.println("Does not
exists");
}
}

}
53) Write a program to demonstrate writing into file

import java.io.*;
import java.io.IOException;

class crf
{
public static void main(String args[])
{
try
{
FileWriter w=new
FileWriter("d:\\hel.txt"); w.write("Hello");
w.close();
}
catch(IOException e)
{
System.out.println(e);
}

}
54) } Write a program to demonstrate reading from file
import java.io.*;
import java.io.FileNotFoundException;
import java.util.*;

class crf
{
public static void main(String args[])
{
try
{
File f=new
File("D:\\hel.txt"); Scanner s=new
Scanner(f); while(s.hasNextLine())
{
String
fd=s.nextLine();
System.out.println(fd);
}
s.close();
}
catch(FileNotFoundException e)
{
System.out.println(e);
}
}
}
55) Write a program to demonstrate deleting from file

import java.io.*;

class del
{
public static void main(String args[])
{
File f=new
File("D:\\hel.txt"); if(f.delete())
System.out.println("Deleted")
;
else
System.out.println("Not
Deleted");
56) Write a program to demonstrate use of random access file
}
}
import java.io.*;
class Random1
{
public static void main(String args[])
{
try
{
RandomAccessFile f=new
RandomAccessFile("test1.txt","rw");
f.writeChar(‘k’);
f.writeInt(10);
f.writeDouble(10.2);
f.seek(0);

System.out.println(f.readChar()
); System.out.println(f.readInt());
System.out.println(f.readDouble());
f.seek(2);
System.out.println(f.readInt());
f.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
57) Write a program to demonstrate use of Character Stream
Class (FileReader Class)

import java.io.*;
import java.io.IOException;

class ch1
{
public static void main(String args[])
{
try
{
FileReader f=new
FileReader("D:\\myf.txt"); int i;
while((i=
f.read())!=-1)
System.out.println((char)i);
f.close();

}
catch(IOException e)
{
System.out.println(e);
}
}
58) Write a program to demonstrate use of Character Stream
} Class (FileWriter Class)
import java.io.*;
import java.io.IOException;

class ch1
{
public static void main(String args[])
{
try
{
FileWriter f=new
FileWriter("D:\\myf6.txt"); f.write("Hello");
f.close();

}
catch(IOException e)
{
System.out.println(e);
}
}
}
59) Write a program to demonstrate use of Buffered Writer Class

import java.io.*;
import java.io.IOException;

class ch1
{
public static void main(String args[])
{
try
{
FileWriter f=new
FileWriter("D:\\myf7.txt"); BufferedWriter b=new
BufferedWriter(f); f.write("Hello");
f.close();

}
catch(IOException e)
{
System.out.println(e);
60) Write a program to demonstrate
} use of Buffered Reader Class
}
}
import java.io.*;
import java.io.IOException;

class ch1
{
public static void main(String args[])
{
try
{
FileReader f=new
FileReader("D:\\myf7.txt"); BufferedReader
b=new BufferedReader(f);
in
t i;
while(i=f.read())!=-1)
{
System.out.println((
char)i);
}
b.close();

}
catch(IOException e)
{
System.out.println(e);
}
}
61) Write a program to demonstrate use of FileOutputStream and
File InputStream Class

import java.io.*;

class inp
{
public static void main(String args[])
{
try
{
FileOutputStream f=new
FileOutputStream("D:\\myf9.txt"); f.write(10);
FileInputStream f1=new
FileInputStream("D:\\myf9.txt"); int i;
while((i=f1.read())!=-1)
{
System.out.println(i);
}
}
catch(IOException e)
{
System.out.println(e);
}
62) Write a program to demonstrate use of DataOutputStream and
Data InputStream
} Class
import java.io.*;
class da
{
public static void main(String args[])throws IOException
{
FileOutputStream f=new
FileOutputStream("D:\\myf10.txt"); DataOutputStream
f1=new DataOutputStream(f); f1.write(10);
FileInputStream f2=new
FileInputStream("D:\\myf10.txt"); DataInputStream f3=new
DataInputStream(f2);
int i;
while((i=f3.read())!=-1)
{
System.out.println(i);
}

f1.close();
f3.close();
}
}
63) Write a program to copy the data of one file into another file

import java.io.*;
class cop
{
public static void main(String args[])throws IOException
{
FileInputStream f=new
FileInputStream("D:\\myf1.txt"); FileOutputStream
f1=new
FileOutputStream("D:\\copy.txt");
int i;
while((i=f.read())!=-1)
{
f1.write((char)i);
}
f.close();
f1.close();
64) Write a program
} to demonstrate use of StreamTokenizer class
}

import java.io.*;

class stto
{
public static void main(String args[])throws IOException
{
FileReader r=new
FileReader("D:\\myf1.txt"); StreamTokenizer
st=new StreamTokenizer(r); double sum=0;
int n=0;
while(st.nextToken()!=st.TT_EOF)
{
if(st.ttype==StreamTokenizer.TT_NUM
BER) sum=sum+st.nval;
else
if(st.ttype==StreamTokenizer.TT_WORD) n++;
}
System.out.println("Sum:"
+sum); System.out.println("Total
Words: "+n);
}
}
84) Write a program to demonstrate use of pipedInputStream
and PipedOutputStream
import java.io.*;

class pipe
{
public static void main(String args[])
{
PipedOutputStream out=new
PipedOutputStream(); PipedInputStream in=new
PipedInputStream();
try
{
i
n.connect(out);
out.write(23);
out.write(24);
for(int i=0;i<2;i++)

System.out.println(in.read());
}
catch(IOException e)
{
85) Write a program to demonstrate use of Bridge
System.out.println(e);
Class (InputStreamReader class)
}
}
import java.io.*;
class} br
{
public static void main(String args[])throws
IOException
{
FileInputStream f=new
FileInputStream("D:\\myf3.txt");
InputStreamReader r=new
InputStreamReader(f); int i;
while((i=r.read())!=-1)
{
System.out.println((char)i);
}
r.close();
}
}
86) Write a program to demonstrate use of Bridge
Class (OutputStreamWriter class)

import java.io.*;
class br
{
public static void main(String args[])throws
IOException
{
FileOutputStream f=new
FileOutputStream("D:\\myf100.txt");
OutputStreamWriter w=new
OutputStreamWriter(f);
w.write("hello
world"); w.close();
}
}
87) Write a program to demonstrate use of Bridge
Class (ObjectInputStream and ObjectOutputStream
class)

import java.io.*;
class br
{
public static void main(String args[])throws IOException
{
int i=10;
FileOutputStream f=new
FileOutputStream("d:\\myfile101.txt");
ObjectOutputStream o=new
ObjectOutputStream(f); o.writeInt(i);

FileInputStream f1=new
FileInputStream("d:\\myfile101.txt"); ObjectInputStream
o1=new ObjectInputStream(f1); System.out.println("Integer:"
+o1.readInt());
;
f.close();
f1.close();
}
}
Write a program which demonstrate life cycle of thread

import java.applet.*;
import java.awt.*;
/*<applet code="ap" width=200 height=200>
</applet>*/
public class ap extends Applet {
String msg="";
public void init()
{
msg+="init()called";
}
public void start()
{
msg+="start() called";
}
public void paint(Graphics g)
{
g.drawString(msg,30,30);
}
public void stop()
{
msg+="stop() called";
}
public void destroy()
{
msg+="destroy called";
}
88) Write a program that demonstrate use of flow layout

import java.applet.*;
import java.awt.*;
/*<applet code="flowl" width=200 height=200>
</applet>*/

public class flowl extends Applet


{
Label b1,b2,b3;
public void init()
{
setLayout(new FlowLayout());
b1=new Label("OK"); b2=new
Label("Open"); b3=new
Label("Close"); add(b1);
add(b2);
add(b3);
}
}

89) Write a program that demonstrate use of Border layout


import java.applet.*;
import java.awt.*;
/*<applet code="flowl" width=200 height=200>
</applet>*/

public class flowl extends Applet


{
Button b1,b2,b3,b4,b5;
public void init()
{
setLayout(new BorderLayout());
b1=new Button("NORTH");
b2=new Button("SOUTH");
b3=new Button("EAST");
b4=new Button("WEST");
b5=new Button("CENTER");
add(b1,BorderLayout.NORTH);
add(b2,BorderLayout.SOUTH);
add(b3,BorderLayout.EAST);
add(b4,BorderLayout.WEST);
add(b5,BorderLayout.CENTER);
}
}
90) Write a program that demonstrate use of Grid layout

import java.applet.*;
import java.awt.*;

/*<applet code="gri" width=200 height=200>


</applet>*/

public class gri extends Applet


{
Button b1,b2,b3,b4,b5;
Font f;
public void init()
{
setLayout(new GridLayout(3,3));
f=new Font("Arial",Font.BOLD,32);
b1=new Button("1");
b2=new Button("2");
b3=new Button("3");
b4=new Button("4");
b5=new Button("5");
b1.setFont(f);
b2.setFont(f);
b3.setFont(f);
b4.setFont(f);
b5.setFont(f);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
}
}
91) Write a program that demonstrate use of Grid Bag layout

import java.applet.*;
import java.awt.*;

/*<applet code="gri" width=200 height=200>


</applet>*/

publ
ic class gri extends Applet
{
Button b1,b2;
public void init()
{
setLayout(new GridBagLayout());
Button b1=new Button("Ok");
Button b2=new Button("Cancel");
Button b3=new Button("Close");
Button b4=new Button("Hi");
GridBagConstraints gc=new GridBagConstraints();
gc.fill=GridBagConstraints.HORIZONTAL;
gc.gridx=0;
gc.gridy=0;
this.add(b1,gc);
gc.gridx=0;
gc.gridy=1;
this.add(b2,gc);
gc.gridx=1;
gc.gridy=0;
this.add(b3,gc);
gc.gridx=2;
gc.gridy=2;
gc.gridwidth=2;
this.add(b4,gc);
}
}
92) Write a program which demonstrate use of Mouse Motion Adapter

import javax.swing.*;
import java.awt.event.*;

public class key1 extends MouseAdapter


{
JFrame f;
JTextArea ta,ta1;
key1()
{
f=new JFrame();
ta=new JTextArea();
ta1=new JTextArea();
ta.setBounds(80,150,80,70);
ta.addKeyListener(this);
ta1.setBounds(80,250,80,70);
ta1.addMouseListener(this);
f.add(ta);
f.add(ta1);
f.setLayout(null);
f.setSize(300,300);
f.setVisible(true);
}
public void mouseDragged(MouseEvent e)
{
ta1.setText("Dragged");
}
public static void main(String args[])
{
key1 k=new key1();
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy