0% found this document useful (0 votes)
9 views

java lab manual (1)

The document outlines the curriculum for the 22CST302 Programming in Java Laboratory course for the academic year 2023-2024, detailing the program educational objectives, outcomes, and specific experiments to be conducted. It emphasizes the importance of object-oriented programming concepts, inheritance, interfaces, exception handling, and file I/O in Java. The document also includes a list of experiments, expected outcomes, and required equipment for students.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

java lab manual (1)

The document outlines the curriculum for the 22CST302 Programming in Java Laboratory course for the academic year 2023-2024, detailing the program educational objectives, outcomes, and specific experiments to be conducted. It emphasizes the importance of object-oriented programming concepts, inheritance, interfaces, exception handling, and file I/O in Java. The document also includes a list of experiments, expected outcomes, and required equipment for students.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Department of Cyber Security

22CST302– PROGRAMMING IN JAVA


LABORATORY

Academic Year 2023-2024


(2022 Regulation)

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING

INSTITUTE VISION & MISSION


DEPARTMENT VISION & MISSION

PROGRAM EDUCATIONAL OBJECTIVES (PEOs):


PEO Statements M1 M2 M3
Our graduates to pursue higher education and research, or have a successful 2 3 3
career in industries associated with Computer Science and Engineering, or as
entrepreneurs.
Our graduates will have the ability and attitude to adapt to emerging 3 3 2
technological changes.
Our graduates shall adapt to the changing career opportunities, assimilate new 2 3 3
technologies and work in multi-disciplinary areas with strong focus on
innovation and entrepreneurship.
3- High; 2-
Medium; 1-Low
POs PROGRAM OUTCOMES
PO1 Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals and an engineering specialization to the solution of complex engineering problems.
PO2 Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
PO3 Design/development of solutions: Design solutions for complex engineering problems and desig
system components or processes that meet the specified needs with appropriate consideration fo
the public health and safety, and the cultural, societal, and environmental considerations.
PO4 Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of
the information to provide valid conclusions.
PO5 Modern tool usage: Create, select, and apply appropriate techniques, resources, and moder
engineering and IT tools including prediction and modeling to complex engineering activities wit
an understanding of the limitations.
PO6 The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
PO7 Environment and sustainability: Understand the impact of the professional engineering solution
in societal and environmental contexts, and demonstrate the knowledge of, and need fo
sustainable
development.
PO8 Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice.
PO9 Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
PO10 Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.
PO11 Project management and finance: Demonstrate knowledge and understanding of the engineerin
and management principles and apply these to one’s own work, as a member and leader in a team
to manage projects and in multidisciplinary environments.
PO12 Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.

PROGRAM SPECIFIC OUTCOMES:

PSO1 To apply software engineering principles and practices for developing quality software for
scientific and business applications.
PSO2 To adapt to emerging Information and Communication Technologies (ICT) to innovate ideas
and solutions to existing/novel problems.
OBJECTIVES:
• To understand Object Oriented Programming concepts and basics of Java programming

language

• To know the principles of inheritance and interfaces

• To develop a java application packages and exception handling

• To develop the ability of handling string and generics.

• To learn how to use files using I/O streams


LIST OF EXPERIMENTS

1. Programs using sequential and branching stuctures.

2. Experiment the use of looping, arrays and strings.

3. Demonstrate basic Object-Oriented programming elements.

4. Experiment the use of inheritance, polymorphism and abstract classes.

5. Designing packages and demonstrate exception handling.

6. Demonstrate the use of IO streams, file handling and serialization.

7. Program to discover application of collectios.

TOTAL: 45 HOURS

OUTCOMES:
Upon Completion of the course, the students will be able to:
CO1:Apply the concepts of classes and objects to solve simple problems
CO2: Develop programs using inheritance and interfaces
CO3:Make use of exception handling mechanisms and packages to solve real
world problems
CO4:Build Java applications with string classes, Collections and generics concepts
CO5:Develop java program using I/O packages,
LIST OF EQUIPMENT FOR A BATCH OF 30
STUDENTS:

SOFTWARE: Eclipse,JDK .
HARDWARE: Standalone desktops – 30 Nos. (or) Server supporting 30 terminals or
more.

INDEX

EX.NO EXPERIMENT NAME

Programs using sequential and branching structures.


1. • Program to check if the number entered by user is even or odd

b)Java Program to check Leap Year

c) Java Program to check Vowel or Consonant using Switch Case

d) Java Program to Calculate Compound Interest

Experiment the use of looping, arrays and strings.


2. • Program to reverse every word in a String using methods

b) Java program to find the occurrence of a character in a string

c) Java program to print number of elements in an array

d) Java program to sum the elements of an array

e) Java Program to Sort an Array in Ascending Order

Demonstrate basic Object-Oriented programming elements.


a)Object and class.
3. b) Object and Class Example: Initialization through method
c) Object and Class Example: Initialization through a constructor
Experiment the use of inheritance, polymorphism and abstract classes.
4. a)inheritance
b)polymorphism

5. Designing packages and demonstrate exception handling.


a)Package
b)Exception handling
6.
Demonstrate the use of IO streams, file handling and serialization.

a)write the content into the file.


b)write the string into the file.
c)read the content from the file.

7. Program to discover application of collectios.

Expriment1- Programs using sequential and branching structures.


a)Program to check if the number entered by user is even or odd.

Procedure:

In this program, we have an int variable num. We are using Scanner class to get the

number entered by the user.

Once the entered number is stored in the variable num, we are using if..else statement to

check if the number is perfectly divisible by 2 or not. Based on the outcome, it is

executing if block (if condition true) or else block (if condition is false).
Program:
import java.util.Scanner;
public class JavaExample
{
public static void main(String args[])
{
int num;
System.out.print("Enter an Integer number: ");

//The input provided by user is stored in num


Scanner input = new Scanner(System.in);
num = input.nextInt();

// If number is divisible by 2 then it's an even number


//else it is an odd number
if ( num % 2 == 0 )
System.out.println(num+" is an even number.");
else
System.out.println(num+" is an odd number.");
}
}
Output 1:
Output 2:

• Java Program to check Leap Year

Procedure:

Here we will write a java program to check whether the input year is a leap year or not.
Before we see the program, lets see how to determine whether a year is a leap year
mathematically:
To determine whether a year is a leap year, follow these steps:
1. If the year is evenly divisible by 4, go to step 2. Otherwise, go to step 5.
2. If the year is evenly divisible by 100, go to step 3. Otherwise, go to step 4.
3. If the year is evenly divisible by 400, go to step 4. Otherwise, go to step 5.
4. The year is a leap year (it has 366 days).
5. The year is not a leap year (it has 365 days). Source of these steps.

Program:

import java.util.Scanner;
public class Demo {

public static void main(String[] args) {

int year;
Scanner scan = new Scanner(System.in);
System.out.println("Enter any Year:");
year = scan.nextInt();
scan.close();
boolean isLeap = false;

if(year % 4 == 0)
{
if( year % 100 == 0)
{
if ( year % 400 == 0)
isLeap = true;
else
isLeap = false;
}
else
isLeap = true;
}
else {
isLeap = false;
}
if(isLeap==true)
System.out.println(year + " is a Leap Year.");
else
System.out.println(year + " is not a Leap Year.");
}
}
Output:

Enter any Year:


2001
2001 is not a Leap Year.

• Java Program to check Vowel or Consonant using Switch Case.

Procedure:

The alphabets A, E, I, O and U (smallcase and uppercase) are known as Vowels and rest of
the alphabets are known as consonants. Here we will write a java program that checks
whether the input character is vowel or Consonant using Switch Case in Java.

import java.util.Scanner;
class JavaExample
{
public static void main(String[ ] arg)
{
boolean isVowel=false;;
Scanner scanner=new Scanner(System.in);
System.out.println("Enter a character : ");
char ch=scanner.next().charAt(0);
scanner.close();
switch(ch)
{
case 'a' :
case 'e' :
case 'i' :
case 'o' :
case 'u' :
case 'A' :
case 'E' :
case 'I' :
case 'O' :
case 'U' : isVowel = true;
}
if(isVowel == true) {
System.out.println(ch+" is a Vowel");
}
else {
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
System.out.println(ch+" is a Consonant");
else
System.out.println("Input is not an alphabet");
}
}
}
Output 1:

Enter a character :
A
A is a Vowel
Output 2:

Enter a character :
P
P is a Consonant
Output 3:

Enter a character :
9
Input is not an alphabet
d) Java Program to Calculate Compound Interest

Procedure:

Compound interest is calculated using the following formula:

P (1 + R/n) (nt) - P
Here P is principal amount.
R is the annual interest rate.
t is the time the money is invested or borrowed for.
n is the number of times that interest is compounded per unit t, for example if interest is
compounded monthly and t is in years then the value of n would be 12. If interest is compounded
quarterly and t is in years then the value of n would be 4.

public class JavaExample {

public void calculate(int p, int t, double r, int n) {


double amount = p * Math.pow(1 + (r / n), n * t);
double cinterest = amount - p;
System.out.println("Compound Interest after " + t + "
years: "+cinterest);
System.out.println("Amount after " + t + " years:
"+amount);
}
public static void main(String args[]) {
JavaExample obj = new JavaExample();
obj.calculate(2000, 5, .08, 12);
}
}
Output:
Compound Interest after 5 years: 979.6914166032102
Amount after 5 years: 2979.69141660321

Experiment 2. Experiment the use of looping, arrays and strings.

• Program to reverse every word in a String using methods

Procedure:

This program reverses every word of a string and display the reversed string as an output. For
example, if we input a string as “Reverse the word of this string” then the output of the program
would be: “esrever eht drow fo siht gnirts”.

To understand this program you should have the knowledge of following Java
Programming topics:

• For loop in Java


• Java String split() method
• Java String charAt() method
Program:
public class Example
{
public void reverseWordInMyString(String str)
{
/* The split() method of String class splits
* a string in several strings based on the
* delimiter passed as an argument to it
*/
String[] words = str.split(" ");
String reversedString = "";
for (int i = 0; i < words.length; i++)
{
String word = words[i];
String reverseWord = "";
for (int j = word.length()-1; j >= 0; j--)
{
/* The charAt() function returns the character
* at the given position in a string
*/
reverseWord = reverseWord + word.charAt(j);
}
reversedString = reversedString + reverseWord + " ";
}
System.out.println(str);
System.out.println(reversedString);
}
public static void main(String[] args)
{
Example obj = new Example();
obj.reverseWordInMyString("Welcome to BeginnersBook");
obj.reverseWordInMyString("This is an easy Java Program");
}
}
Output:

Welcome to BeginnersBook
emocleW ot kooBsrennigeB
This is an easy Java Program
sihT si na ysae avaJ margorP
b) Java program to find the occurrence of a character in a string

procedure:
In this program we are finding the occurrence of each character in a String. To do this we are
first creating an array of size 256 (ASCII upper range), the idea here is to store the occurrence
count against the ASCII value of that character. For example, the occurrence of ‘A’ would be
stored in counter[65] because ASCII value of A is 65, similarly occurrences of other chars are
stored in against their ASCII index values.

We are then creating an another array array to hold the characters of the given String, then we are
comparing them with the characters in the String and when a match is found the count of that
particular char is displayed using counter array.

Program:

class JavaExample {

static void countEachChar(String str)


{
//ASCII values ranges upto 256
int counter[] = new int[256];

//String length
int len = str.length();

/* This array holds the occurrence of each char, For


example
* ASCII value of A is 65 so if A is found twice then
* counter[65] would have the value 2, here 65 is the
ASCII value
* of A
*/
for (int i = 0; i < len; i++)
counter[str.charAt(i)]++;

// We are creating another array with the size of String


char array[] = new char[str.length()];
for (int i = 0; i < len; i++) {
array[i] = str.charAt(i);
int flag = 0;
for (int j = 0; j <= i; j++) {

/* If a char is found in String then set the flag


* so that we can print the occurrence
*/
if (str.charAt(i) == array[j])
flag++;
}

if (flag == 1)
System.out.println("Occurrence of char " +
str.charAt(i)
+ " in the String is:" + counter[str.charAt(i)]);
}
}
public static void main(String[] args)
{
String str = "beginnersbook";
countEachChar(str);
}
}
Output:

c) Java program to print number of elements in an array

Procedure:
In this example, we have two arrays. We are finding the count of the elements in both the arrays.
The steps to count the number of elements is same in any type of array, you can simply
use .length property of the array to quickly find the size of the array.

public class JavaExample {


public static void main(String[] args) {
//Initializing an int array
int [] numbers = new int [] {2, 4, 6, 8, 10, 12};
// We can use length property of array to find the count of
elements
System.out.println("Number of elements in the given int
array: " + numbers.length);

//Initializing a String array


String [] names = new String [] {"Rick", "Luna", "Steve",
"John"};
System.out.println("Number of elements in the given String
array: " + names.length);
}
}
Output:

Number of elements in the given int array: 6


Number of elements in the given String array: 4
• Java program to sum the elements of an array
Program:
import java.util.Scanner;
class SumDemo{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
int[] array = new int[10];
int sum = 0;
System.out.println("Enter the elements:");
for (int i=0; i<10; i++)
{
array[i] = scanner.nextInt();
}
for( int num : array) {
sum = sum+num;
}
System.out.println("Sum of array elements is:"+sum);
}
}
Output:

Enter the elements:


1
2
3
4
5
6
7
8
9
10
Sum of array elements is:55
• Java Program to Sort an Array in Ascending Order
Procedure:
In this program, user is asked to enter the number of elements that he wish to enter. Based
on the input we have declared an int array and then we are accepting all the numbers
input by user and storing them in the array.
Program:

import java.util.Scanner;
public class JavaExample
{
public static void main(String[] args)
{
int count, temp;

//User inputs the array size


Scanner scan = new Scanner(System.in);
System.out.print("Enter number of elements you want in
the array: ");
count = scan.nextInt();

int num[] = new int[count];


System.out.println("Enter array elements:");
for (int i = 0; i < count; i++)
{
num[i] = scan.nextInt();
}
scan.close();
for (int i = 0; i < count; i++)
{
for (int j = i + 1; j < count; j++) {
if (num[i] > num[j])
{
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
}
System.out.print("Array Elements in Ascending Order: ");
for (int i = 0; i < count - 1; i++)
{
System.out.print(num[i] + ", ");
}
System.out.print(num[count - 1]);
}
}
Output:

Experiment 3 Demonstrate basic Object-Oriented programming elements.


a)Object and class.
1) Object and Class Example: Initialization through reference
Initializing an object means storing data into the object. Let's see a simple example where we are
going to initialize the object through a reference variable.

Program1:
class Student{
int id;
String name;
}
class TestStudent3{
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name="Sonoo";
s2.id=102;
s2.name="Amit";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
}
2) Object and Class Example: Initialization through method
In this example, we are creating the two objects of Student class and
initializing the value to these objects by invoking the insertRecord method.
Here, we are displaying the state (data) of the objects by invoking the
displayInformation() method.
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
c) Object and Class Example: Initialization through a constructor
We will learn about constructors in Java later.

Object and Class Example: Employee


Let's see an example where we are maintaining records of employees
class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}
Experiment4: Experiment the use of inheritance, polymorphism and abstract classes.

a)Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).
The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in java

• For Method Overriding (so runtime polymorphism can be achieved).

• For Code Reusability.

Terms used in Inheritance

• Class: A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created.

• Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called
a derived class, extended class, or child class.

• Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.

• 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.

The syntax of Java Inheritance


• class Subclass-name extends Superclass-name
• {
• //methods and fields
• }
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
Simple inheritance:
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
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();
}}
Heirarchical inheritance:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}

b) Polymorphism
Method overloading:
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 TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Method overriding:
class Bank{
int getRateOfInterest(){return 0;}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}

class ICICI extends Bank{


int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
//Test class to create objects and call the methods
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}

Experiment5: Designing packages and demonstrate exception handling.


a)Package
//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
Exception Handling:
Program1:
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
Program2:
public class TestThrow1 {
//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}
Output:

Program3:

User defined Exception:


// class representing custom exception
class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}

// class that uses custom exception InvalidAgeException


public class TestCustomException1
{

// method to check the age


static void validate (int age) throws InvalidAgeException{
if(age < 18){

// throw an object of user defined exception


throw new InvalidAgeException("age is not valid to vote");
}
else {
System.out.println("welcome to vote");
}
}

// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");

// printing the message from InvalidAgeException object


System.out.println("Exception occured: " + ex);
}

System.out.println("rest of the code...");


}
}
Output:

Demonstrate the use of IO streams, file handling and serialization.


a)write the content into the file.
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
b)write the string into the file.
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}

c)read the content from the file.


package com.javatpoint;

import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Expriment7: Program to discover application of collectios.
Program1:
import java.util.*;
public class ArrayListExample4{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Mango");
al.add("Apple");
al.add("Banana");
al.add("Grapes");
//accessing the element
System.out.println("Returning element: "+al.get(1));//it will return the 2n
d element, because index starts from 0
//changing the element
al.set(1,"Dates");
//Traversing list
for(String fruit:al)
System.out.println(fruit);

}
}
Program2:
import java.util.*;
class ArrayList7{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
System.out.println("Initial list of elements: "+al);
//Adding elements to the end of the list
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
System.out.println("After invoking add(E e) method: "+al);
//Adding an element at the specific position
al.add(1, "Gaurav");
System.out.println("After invoking add(int index, E element) metho
d: "+al);
ArrayList<String> al2=new ArrayList<String>();
al2.add("Sonoo");
al2.add("Hanumat");
//Adding second list elements to the first list
al.addAll(al2);
System.out.println("After invoking addAll(Collection<? extends E>
c) method: "+al);
ArrayList<String> al3=new ArrayList<String>();
al3.add("John");
al3.add("Rahul");
//Adding second list elements to the first list at specific position
al.addAll(1, al3);
System.out.println("After invoking addAll(int index, Collection<? ex
tends E> c) method: "+al);

}
}

You might also like