42510_java_with_program (1)
42510_java_with_program (1)
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
4) Object-Oriented:
1) Object
2) Class
3) Inheritance
4) Polymorphism
5) Abstraction
6) Encapsulation
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:
7) Object
8) Class
9) Inheritance
10) Polymorphism
11) Abstraction
12) Encapsulation
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.
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.
● 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).
JRE:
Process of converting Byte Code into Machine Code
Byte Code Java Interpreter Machine Code
Virtual Machine
JDK:
Components:-
1) Applet viewer :- it used to view the java applets without using the browser.
Steps:
Step 1: Save the program with .java extension (Note: Name of the program
must be same as the name of the class)
Netbeans:
Eclipse:
java Ans:
Integer
Floating-Point Types
Character
❖ The data type used to store characters is char.
Boolean:
tokens Ans:
❖ 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
java Ans:
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:
Example:
a=a+5 a+=5
a=a-4 a-=4
a=a*2 a*=2
5) Conditional Operators:
Syntax:
Condition? True part: false part
Example:
(a>b) ? “a is max” : “b is max”
6) Instance of Operator:
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:
Syntax:
sizeof(variable name);
Example:
int a;
sizeof(a)=4
bytes
8) Bitwise Operator:
9) Increment/Decrement Operator:
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
}
structures Ans:
◆ 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();
}
}
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
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:
* for loop:
Syntax:
{
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:
}
Example:
class loop
{
public static void main(String args[])
{
i
nt i=1;
do
{
Syste
m.out.println(i); i++;
}while(i<=5);
}
java Ans:
1) break statement:
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:
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);
}
}
typecasting Ans:
❖ 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:
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):
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
}
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:
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]);
}
}
}
❖ 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;
{
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);
}
}
Ans:
❖ Provide public setter and getter methods to modify and view the
variables values.
❖ 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();
}
}
Ans:
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:
Types of Inheritance:
Note: Multiple inheritance is not supported in Java through class.
1) 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 single
{
public static void main(String args[])
{
BabyDog
bd=new BabyDog(); d.bark();
d.eat();
d.sleep();
}
}
3) Hierarchical Inheritance :
4) Multiple Inheritance :
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?
}
}
Example:
class Animal
{
void eat()
{
System.out.println("Eating");
}
}
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:
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:
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();
}
}
Constructor. Ans:
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();
}
}
overloading Ans:
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:
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();
}
}
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:
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);
}
}
java Ans:
nt
System.out.println(
}
{ age=1
}
IIB
class im
{
public static void
main(String args[])
{
i
Unit-2:- Inheritance and java packages
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.
package pack;
public class A
{
protected void display()
{
System.out.println(“Hello”);
}
}
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B
obj=new B();
obj.display();
}
}
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();
}
}
Syntax:
interface interfacename
{
returntype methodname();
}
Example:
interface draw
{
void print();
}
class multiple
{
public static void main(String args[])
{
sam
s=new sam();
s.display();
s.display1();
}
}
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();
}
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:
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
}
}
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:
class ke
{
public static void main(String args[])
{
System.out.println(Math.sqrt(25));
System.out.println(Math.pow(2,2));
}
}
static import:
class ke
{
public static void main(String args[])
{
System.out.pri
ntln(sqrt(25));
System.out.println(pow(2,2));
}
}
Built-in Packages:
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.
Example:
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));
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:
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.*;
import java.util.*;
}
}
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());
}
❖ 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.
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.
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.
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
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:
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.
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?
class userdefinedexception
{
public static void main(String args[])
{
try
{
throw new myexception(400);
}
catch(myexception e)
{
System.out.println(e);
}
}
}
❖ 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:
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:
class th
{
}
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);
}
}
}
}
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();
}
}
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();
}
}
Non-Daemon Thread:
❖ Non-Damon thread in java is a thread that does not run in the background.
❖ Based on the data they handle there are two types of streams −
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);
}
}
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");
}
❖ 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");
}
}
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.
❖ 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
}
}
}
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:
FileInputStreamClass
FileOutputStreamClass
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);
}
}
}
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.
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();
}
}
}
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
1) init():
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.
import
java.applet.*; import
java.awt.*;
/*<applet code="flowl" width=200 height=200>
</applet>*/
}
}
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:
Example:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
Grid BagLayout:
8) Java AWT is slower than swing in 8) Java Swing is faster than the AWT.
terms of performance.
1) Image Icon:
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:
Example:
JButton okBtn = new JButton(“Ok”);
❖ This constructor returns a button with text Ok on it.
4) JTextField:
❖ 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:
❖ 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:
10) JComboBox:
11) JFileChooser
❖ The above code creates a file chooser dialog and attaches it to the button.
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
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:
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:
actionPerformed():
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");
}
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.
foucsGained():
focusLost()
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():
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:
import javax.swing.*;
import java.awt.event.*;
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
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
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
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
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
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 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
package pack;
class A
{
void display()
{
System.out.println(“Hello”);
}
}
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”);
}
}
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();
}
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
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:
Output:
5
4
36) Write a program to demonstrate use of static import :
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.*;
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");
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 th
{
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>*/
import java.applet.*;
import java.awt.*;
import java.applet.*;
import java.awt.*;
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.*;