Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
38 views

Java Lab Programs

The document provides examples of Java programs that demonstrate various Java concepts like conditional statements, arrays, methods, inheritance, abstraction, interfaces, packages, exception handling, and multithreading. Conditional statements like if-else, switch-case and ternary operator are shown. Examples include creating and accessing arrays, method overloading and overriding. Inheritance concepts like single, multilevel and method overriding are demonstrated. Interfaces and abstract classes are also included. The document also covers packages, exception handling, and multithreading concepts like threads, runnable interface, synchronization.

Uploaded by

eshwari0706
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

Java Lab Programs

The document provides examples of Java programs that demonstrate various Java concepts like conditional statements, arrays, methods, inheritance, abstraction, interfaces, packages, exception handling, and multithreading. Conditional statements like if-else, switch-case and ternary operator are shown. Examples include creating and accessing arrays, method overloading and overriding. Inheritance concepts like single, multilevel and method overriding are demonstrated. Interfaces and abstract classes are also included. The document also covers packages, exception handling, and multithreading concepts like threads, runnable interface, synchronization.

Uploaded by

eshwari0706
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Java Lab programs

CONDITIONAL STATEMENTS
1)IF STATEMENT
class age{
public static void main(String args[])
{
int age=19;
if(age>=18){
System.out.println("Eligible to vote!!");
}
}
}

2)IF-ELSE STATEMENT
class EvenOdd {
public static void main(String[] args) {
int num=20;
if(num % 2 == 0)
System.out.println(num + " is even");
else
System.out.println(num + " is odd");
}
}

3)NESTED IF STATEMENT
class Blood{
public static void main(String args[]){
int age=20,weight=55;
if(age>=18){
if(weight>50)
{
System.out.println("Eligible to donate Blood!!");
}
}
}
}
4)SWITCH CASE
class Swtch{
public static void main(String args[]){
int num=90;
switch(num){
case 10:
System.out.println("10");
break;
case 20:
System.out.println("20");
break;
default:
System.out.println("Not in 10/20");
}
}
}

5)TERNARY OPERATOR
class number
{
public static void main(String args[]){
int n=20;
String result=(n%2==0)?"Even":"Odd";
System.out.println(n+" is "+result);
}
}

6)FOR LOOP
class Strg{
public static void main(String args[])
{
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
ARRAY
1)CREATING AN ARRAY
class Arrayexample{
public static void main(String args[]){
int a[]=new int[5];
a[0]=10;
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;
for(int i=0;i<a.length;i++){
System.out.println(a[i]);
}
}
}

2)MULTIPLICATION OF TWO MATRICES


class Mularr{
public static void main(String args[]){
int a[][]= {{1,2,3},{1,2,3},{1,2,3}};
int b[][]= {{3,2,1},{3,2,1},{3,2,1}};
int c[][]= new int[3][3];
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}}
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.println(c[i][j]);
}}
}
}

METHOD OVERLOADING
1)BY CHANGING NUMBER OF ARGUMENTS
class Adder{
static int add(int a,int b){
return a+b;
}
static int add(int a,int b,int c){
return a+b+c;
}
}
class Test{
public static void main(String args[]){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(10,10,10));
}
}

2)BY CHANGING THE DATA TYPE


class Adder{
static int add(int a,int b){
return a+b;
}
static double add(int a,int b){
return a+b;
}
}
class Test{
public static void main(String args[]){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(10,10));
}
}

CONSTRUCTOR
1)NO ARGUMENTS CONSTRUCTOR
class Bike{
Bike(){
System.out.println("Bike is Created");
}
public static void main(String args[]){
Bike b=new Bike();
}
}

2)PARAMETERISED CONSTRUCTOR
class Student{
int id;
String name;
Student(int i,String S)
{
id=i;
name=S;
}
void display(){
System.out.println(id+" "+name);
}
public static void main(String args[]){
Student S1=new Student(012,"ABC");
S1.display();
}
}

3)CONSTRUCTOR OVERLOADING
class Student{
int id,age;
String name;
Student(int i,String S)
{
id=i;
name=S;
}
Student(int i,String S,int a)
{
id=i;
name=S;
age=a;
}
void display(){
System.out.println(id+" "+name+" "+age);
}
public static void main(String args[]){
Student S1=new Student(01,"ABC");
Student S2=new Student(02,"XYZ",18);
S1.display();
S2.display();
}
}
INHERITANCE-SINGLE AND MULTILEVEL
SINGLE LEVEL INHERITANCE
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...

MULTILEVEL INHERITANCE
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
METHOD OVERRIDING
class Bank
{
int getRateofInterest()
{
return 0;
}
}
class SBI extends Bank
{
int getRateofInterest()
{
return 8;
}
}
class ICICI extends Bank
{
int getRateofInterest()
{
return 10;
}
}
class Axis extends Bank
{
int getRateofInterest()
{
return 12;
}
}
class Test
{
public static void main(String args[])
{
Bank b;
SBI s = new SBI();
System.out.println("SBI rate of interest is : "+s.getRateofInterest());
ICICI i = new ICICI();
System.out.println("ICICI rate of interest is : "+i.getRateofInterest());
Axis a = new Axis();
System.out.println("Axis rate of interest is : "+a.getRateofInterest());
}
}

DYNAMIC POLYMORPHISM
class Sample
{
public void display()
{
System.out.println("Over ridden Method");
}
}
public class Demo extends Sample
{
public void display()
{
System.out.println("Over-riding Method");
}
public static void main(String args[])
{
Sample obj = new Demo();
obj.display();
}
}

ABSTRACT CLASS
abstract class A{
abstract void m();}
class B extends A{
void m(){
System.out.println("Hello");
}
}
class Demo{
public static void main(String args[])
{
A obj=new B();
obj.m();
}
}
MULTIPLE INHERITANCE USING INTERFACES
interface A
{
void add(double x , double y);
void sub(double x , double y);
}
interface B
{
void mul(double x , double y);
void div(double x , double y);
}
class Multi implements A , B
{
public void add(double x , double y);
{
System.out.println("Sum is : "+(x + y));
}
public void sub(double x , double y);
{
System.out.println("Subtraction is : "+(x - y));
}
public void mul(double x , double y);
{
System.out.println("Multiplication is : "+(x * y));
}
public void div(double x , double y);
{
System.out.println("Division is : "+(x / y));
}
public static void main(String args[])
{
Multi obj = new Multi();
obj.add(2.5,2.5);
obj.sub(2.5,2.5);
obj.mul(2.5,2.5);
obj.div(2.5,2.5);
}
}

PACKAGES
1)ACCESSING PACKAGE USING PACKAGENAME.*
//save by A.java

package pack;

public class A{

public void msg(){System.out.println("Hello");}

//save by B.java

package mypack;

import pack.*;

class B{

public static void main(String args[]){

A obj = new A();

obj.msg();

Output:
Hello

2)ACCESSING PACKAGE USING PACKAGENAME.CLASSNAME


//save by A.java

package pack;

public class A{

public void msg(){System.out.println("Hello");}

//save by B.java
package mypack;

import pack.A;

class B{

public static void main(String args[]){

A obj = new A();

obj.msg();

Output:
Hello

3)ACCESSING PACKAGE USING FULLY QUALIFIED CLASS


//save by A.java

package pack;

public class A{

public void msg(){System.out.println("Hello");}

//save by B.java

package mypack;

class B{

public static void main(String args[]){

pack.A obj = new pack.A();//using fully qualified name

obj.msg();

}
}

Output:
Hello

EXCEPTION HANDLING
1)TRY-CATCH BLOCK
class Try{
public static void main(String args[]){
try{
int data =50/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("Rest of the code");
}
}

2)MULTIPLE CATCH BLOCK


public class Multiplecatch{
public static void main(String args[]){
try{
int a[]=new int[5];
System.out.println(a[10]);
}
catch(ArithmeticException e){
System.out.println("Arithmetic exception occurs");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Array Index Out Of Bound Exception occurs");
}
catch(Exception e){
System.out.println("Parent exception occurs");
}
System.out.println("Rest of the code");
}
}

3)THROW BLOCK
public class TestThrow
{
public static void validate(int age){
if(age<18)
{
try{
throw newArithmeticException();
}
catch(ArithmeticException e){
System.out.println("Not Eligible to vote");
}
else
{
System.out.println("Eligible to vote");
}}
public static void main(String args[])
{
validate(13);
System.out.println("Rest of the code");
}
}

MULTI THREADING

1. To implement the concept of threading using thread class

class Multi extends Thread{

public void run(){

System.out.println("thread is running...");

public static void main(String args[]){

Multi t1=new Multi();


t1.start();

Output : thread is running...

2. To implement the concept of threading using Runnable interface

class Multi3 implements Runnable{

public void run(){

System.out.println("thread is running...");

public static void main(String args[]){

Multi3 m1=new Multi3();

Thread t1 =new Thread(m1);

t1.start();

Output : thread is running...

3. A program to demonstrate concept of Thread Synchronization by


using thread synchronized method

class Table{

Synchronized void printTable(int n){

for(int i=1;i<=5;i++){

System.out.println(n*i);

try{
Thread.sleep(400);

}catch(Exception 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(100);

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

Table obj = new Table();

MyThread1 t1=new MyThread1(obj);

MyThread2 t2=new MyThread2(obj);

t1.start();

t2.start();

Output :

10

15

20

25

100

200

300

400

500

4. A program to demonstrate concept of Thread Synchronization by


using static synchronization
Program:
class Table
{
synchronized static void printTable(int n){
for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Tabe t)
{
this.t = t;
}
public void run(){
Table.printTable(1);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Tabe t)
{
this.t = t;
}
public void run(){
Table.printTable(10);
}
}
class MyThread3 extends Thread{
Table t;
MyThread3(Tabe t)
{
this.t = t;
}
public void run(){
Table.printTable(100);
}
}
class MyThread4 extends Thread{
Table t;
MyThread4(Tabe t)
{
this.t = t;
}
public void run(){
Table.printTable(1000);
}
}
class TestSynchronization{
public static void main(String t[]){
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
MyThread3 t3=new MyThread3();
MyThread4 t4=new MyThread4();
t1.start();
t2.start();
t3.start();
t4.start();
}
}

Output :

10
10

20

30

40

50

60

70

80

90

100

100

200

300

400

500

600

700

800

900

1000

1000

2000

3000

4000
5000

6000

7000

8000

9000

10000
AWT

1. Program to create Frame by extending frame class


import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);
add(b);
setSize(300,300);
setLayout(null);//no layout manager
setVisible(true);
}
public static void main(String args[]){
First f=new First();
}}
Output :

2. Program to implement a Label


import java.awt.*;
class LabelExample{
public static void main(String args[]){
Frame f= new Frame("Label Example");
Label l1,l2;
l1=new Label("First Label.");
l1.setBounds(50,100, 100,30);
l2=new Label("Second Label.");
l2.setBounds(50,150, 100,30);
f.add(l1); f.add(l2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output :

3. Program to implement Text Field


import java.awt.*;
class TextFieldExample{
public static void main(String args[]){
Frame f= new Frame("TextField Example");
TextField t1,t2;
t1=new TextField("Welcome to Java");
t1.setBounds(50,100, 200,30);
t2=new TextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output :

4. Program to implement Checkbox


import java.awt.*;
public class CheckboxExample
{
CheckboxExample(){
Frame f= new Frame("Checkbox Example");
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100,100, 50,50);
Checkbox checkbox2 = new Checkbox("Java", true);
checkbox2.setBounds(100,150, 50,50);
f.add(checkbox1);
f.add(checkbox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxExample();
}
}
Output :

5.Write a program to create a login page.

import java.awt.*;

class Login

public static void main(String args[])

Frame f = new Frame();


f.setVisible(true);

f.setSize(400,400);

f.setLayout(new FlowLayout());

f.setTitle("Login Page");

Label l1=new Label("Username");

TextField t1=new TextField(20);

Label l2=new Label("Password");

TextField t2=new TextField(20);

t2.setEchoChar('*');

Button b =new Button("Submit");

f.add(l1);

f.add(t1);

f.add(l2);

f.add(t2);

f.add(b);

AWT EXCEPTION HANDLING


MOUSE EVENTS

1. Java actionListener Interface


import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);

//register listener
b.addActionListener(this);//passing current instance

//add components and set size, layout and visibility


add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}
Output:
2. WAP to perform Login Validation using actionPerformed
import java.awt.*;
import java.awt.event.*;
class LoginPage1 extends Frame implements ActionListener
{
String status=" ";
TextField t1,t2;
Label l1,l2;
Button b;
LoginPage1()
{
setSize(600,600);
setLayout(new FlowLayout());
setVisible(true);
setTitle("Login Page");
//create components
l1=new Label("Username");
l2=new Label("Password");
t1=new TextField(10);
t2=new TextField(10);
b=new Button("Submit");
//add components
add(l1);
add(t1);
add(l2);
add(t2);
add(b);
//register listener
b.addActionListener(this);//passing current instance
}
public void actionPerformed(ActionEvent e)
{
String username= t1.getText();
String password= t2.getText();
if(username.equals("mona") && password.equals("singh"))
status="Login Success";
else
status= "Login Failed";
repaint();
}
public void paint(Graphics g)
{
g.drawString(status,120,150);
}
public static void main(String args[])
{
new LoginPage1();
}
}
Output:

3. MouseListener Example 1 :
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}
Output:

4. MouseListener Example 2 :
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample2 extends Frame implements MouseListener{
MouseListenerExample2(){
addMouseListener(this);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public static void main(String[] args) {
new MouseListenerExample2();
}
}
Output:

5. Java MouseMotionListener Example


import java.awt.*;
import java.awt.event.*;
public class MouseMotionListenerExample extends Frame implements
MouseMotionListener{
MouseMotionListenerExample(){
addMouseMotionListener(this);

setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseDragged(MouseEvent e) {
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e) {}
public static void main(String[] args) {
new MouseMotionListenerExample();
}
}
Output:

SWINGS

1. To design a simple calculator using swings.


import java.awt.*;
import java.awt.event.*;
public class TextFieldExample extends Frame implements ActionListener{
TextField tf1,tf2,tf3;
Button b1,b2;
TextFieldExample(){
tf1=new TextField();
tf1.setBounds(50,50,150,20);
tf2=new TextField();
tf2.setBounds(50,100,150,20);
tf3=new TextField();
tf3.setBounds(50,150,150,20);
tf3.setEditable(false);
b1=new Button("+");
b1.setBounds(50,200,50,50);
b2=new Button("-");
b2.setBounds(120,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
add(tf1);add(tf2);add(tf3);add(b1);add(b2);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s1=tf1.getText();
String s2=tf2.getText();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()==b1) // getSource() Returns the object on which the event
occurred
{
c=a+b;
}else if(e.getSource()==b2){
c=a-b;
}
String result=String.valueOf(c); // Converts different types of values into String
tf3.setText(result);
}
public static void main(String[] args) {
new TextFieldExample();
}
}
Output :

KEYBOARD EVENTS
1. Java KeyListener Example
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements KeyListener{
Label l;
TextArea area;
KeyListenerExample(){

l=new Label();
l.setBounds(20,50,100,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);

add(l);add(area);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void keyPressed(KeyEvent e) {
l.setText("Key Pressed");
}
public void keyReleased(KeyEvent e) {
l.setText("Key Released");
}
public void keyTyped(KeyEvent e) {
l.setText("Key Typed");
}

public static void main(String[] args) {


new KeyListenerExample();
}
}
Output:

2. Java KeyListener Example 2: Count Words & Characters


import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements KeyListener{
Label l;
TextArea area;
KeyListenerExample(){

l=new Label();
l.setBounds(20,50,200,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);

add(l);add(area);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) {
String text=area.getText();
String words[]=text.split("\\s");
l.setText("Words: "+words.length+" Characters:"+text.length());
}
public void keyTyped(KeyEvent e) {}

public static void main(String[] args) {


new KeyListenerExample();
}
}

Output:
SERIALIZATION

1. To implement the concept of Serialization

import java.io.*;

class Employee implements java.io.Serializable {

public String name;

public String address;

public int number;

public transient int SSN;

public class SerializeDemo {

public static void main(String [] args) {

Employee e = new Employee();

e.name = "Mona Singh";

e.address = "Abids, Chapel Road";

e.number = 101;
e.SSN = 112233;

try {

FileOutputStream fileOut =

new FileOutputStream("employee.ser");

ObjectOutputStream out = new ObjectOutputStream(fileOut);

out.writeObject(e);

out.close();

fileOut.close();

System.out.printf("Serialized data is saved in employee.ser");

} catch (IOException i) {

i.printStackTrace();

Output :

Serialized data is saved in employee.ser

DESERIALIZATION

1. To implement the concept of Deserialization

import java.io.*;

public class DeserializeDemo {

public static void main(String [] args) {

Employee e = null;

try {

FileInputStream fileIn = new


FileInputStream("C:/Users/system/Desktop/java/employee.ser");

ObjectInputStream in = new ObjectInputStream(fileIn);

e = (Employee) in.readObject();

in.close();

fileIn.close();

} catch (IOException i) {

i.printStackTrace();return;

} catch (ClassNotFoundException c) {

System.out.println("Employee class not found");

c.printStackTrace();

return;

System.out.println("Deserialized Employee...");

System.out.println("Name: " + e.name);

System.out.println("Address: " + e.address);

System.out.println("SSN: " + e.SSN);

System.out.println("Number: " + e.number);

Output :

Deserialized Employee...

Name: Mona Singh

Address: Abids, Chapel Road

SSN: 0
Number: 101

COLLECTIONS

1. To implemention collections using array list

import java.util.*;
public class ArrayListExample1{
public static void main(String
args[]){
ArrayList<String> list=new ArrayList<String>();//Creating
arraylist list.add(“Mango”);//Adding object in arraylist
list.add(“Apple”);
list.add(“Banana”);
list.add(“Grapes”);

//Printing the arraylist object

System.out.println(list);

Output :

[Mango, Apple, Banana, Grapes]

LINKED LIST

1. To implement collections using linked list

import java.util.* ;

class LinkTest

{
public static void main(String[]
args)

LinkedList< String>ll = new LinkedList<


String>(); ll.add(“a”);
ll.add(“b”);
ll.add(“c”);
ll.addLast(“z”);
ll.addFirst(“A”);

System.out.println(ll);

Output:

[A, a, b, c, z]

TREE MAP

1. To implement collections using tree map

import java.util.*;
class TreeMap1{
public static void main(String
args[]){
TreeMap<Integer,String> map=new TreeMap<Integer,String>();
map.put(100,”Amit”);

map.put(102,”Ravi”);
map.put(101,”Vijay”);
map.put(103,”Rahul”);
for(Map.Entry m:map.entrySet()){

System.out.println(m.getKey()+ “ ”+m.getValue());

Output :

100 Amit

101 Vijay

102 Ravi
103 Rahul

HASH MAP

1. To implement collections using hash map

import java.util.*;

class HashMapDemo

{ public static void main(String


args[])

HashMap<String,Integer>hm = new
HashMap<String,Integer>();
hm.put(“a”,new Integer(100));
hm.put(“b”,new Integer(200));
hm.put(“c”,new Integer(300));
hm.put(“d”,new Integer(400));

Set<Map.Entry<String,Integer>>st = hm.entrySet();

//returns Set view


for(Map.Entry<String,Integer>me:st)

System.out.print(me.getKey()+”:”);

System.out.println(me.getValue());

Output:

A:100

B:200
C:300

D:400

ITERATION OVER COLLECTION

1. To implement iteration over collection using iterator interface

import java.io.*;
import java.util.*;
public class JavaIteratorExample {
public static void
main(String[] args)

ArrayList<String> cityNames = new ArrayList<String>();

cityNames.add(“Delhi”);
cityNames.add(“Mumbai”);
cityNames.add(“Kolkata”);
cityNames.add(“Chandigarh”);
cityNames.add(“Noida”);

// Iterator to iterate the cityNames

Iterator iterator = cityNames.iterator();

System.out.println(“CityNames elements : “);

while (iterator.hasNext())

System.out.print(iterator.next() + “ “);

System.out.println();

Output:

CityNames elements:

Delhi Mumbai Kolkata Chandigarh Noida


LISTITERATOR INTERFACE

1. To implement iteration over collection by using ListIterator interface

import java.util.ArrayList;

public class ArrayListListIteratorExample1

arrayList<String> arrlist = new


ArrayList<String>(); arrlist.add(“d”);
arrlist.add(“dd”);
arrlist.add(“ddd”);
arrlist.add(“dddd”);
arrlist.add(“ddddd”);
System.out.println(arrlist); // [d, dd, ddd, dddd,
ddddd] ListIterator<String> iterator =
arrlist.listIterator(2); while (iterator.hasNext())

String i = iterator.next();

System.out.println(i);

Output :

[d, dd, ddd, dddd, ddddd]

ddd

dddd
ddddd

FILES

1. Program to copy data from one file to another.

import java.io.File;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.io.IOException;

public class CopyExample {

public static void main(String[] args) {

FileInputStream ins = null;

FileOutputStream outs = null;

try {

File infile =new File("d:\\java\a.txt");

File outfile =new File("d:\\java\b.txt");

ins = new FileInputStream(infile);

outs = new FileOutputStream(outfile);

byte[] buffer = new byte[1024];

int length;

while ((length = ins.read(buffer)) > 0) {

outs.write(buffer, 0, length);

} ins.close(); outs.close();

System.out.println("File copied successfully!!");

} catch(IOException ioe) {

ioe.printStackTrace(); } }}

Output :

File copied successfully!!

2. To read a file name from the user, and display information about
whether the file exists, whether the file is readable, whether the file is
writable, the type of file and the length of the file in bytes.

import java.io.*;
public class FileInfoExample {

public static void main(String[] args) {

// Reading file name from the user

BufferedReader reader = new BufferedReader(new


InputStreamReader(System.in));

System.out.print("Enter the file name: ");

try {

String fileName = reader.readLine();

// Creating File object

File file = new File(fileName);

// Displaying file information

if (file.exists()) {

System.out.println("File exists.");

System.out.println("Is readable: " + file.canRead());

System.out.println("Is writable: " + file.canWrite());

System.out.println("File type: " + getFileType(file));

System.out.println("File length (bytes): " + file.length());

} else {

System.out.println("File does not exist.");

} catch (IOException e) {

e.printStackTrace();

}
// Method to get file type

private static String getFileType(File file) {

if (file.isDirectory()) {

return "Directory";

} else if (file.isFile()) {

return "File";

} else {

return "Unknown";

Output :

Enter the file name: Details.txt

File exists.

Is readable: true

Is writable: true

File type: File

File length (bytes): 79

You might also like