Java Final Book (1)
Java Final Book (1)
Java Programming
Java
Programming
Language
WWW.ICIT.IN 1
JAVA PROGRAMMING
Message
CORE PURPOSE:
“To bring about a meaningful transformation in the Lives of Individuals through an Array of Educational
Program thereby empowering them to envision a great future.”
CORE VALUES:
Providing customer value for money.
Continuous Improvement as a way of Life
Empowering student with new ideas
Honesty and Integrity
Affordable Quality & Reliability
Today’s world demands for computer education. It is my vision and mission to impart International
Quality IT Education at best Indian Prices as to create World Class Computer professionals on the Indian
Ground.
ICIT shares endeavor’s to educate students to acquire a broader global mindset of the new upcoming IT
World. The concept of industrial skills and experience put our students in a commanding position when
they exit as graduates to begin their careers. We hope to create best IT Professionals for the current
world.
I sincerely show gratitude towards my Academic Team who shows continuous efforts in brining
improvements in our study materials, Assignments, Projects, Soft Skills, Audio & Video Trainings, E-
Learning. The books have been created by keeping in mind the requirements of the SME’s and
corporates. The books have great assignments which will give prospectus to our students in the
corporate world.
Thanking You,
WWW.ICIT.IN 2
JAVA PROGRAMMING
NOTICE OF RIGHTS
TRADEMARK NOTICE
NOTICE LIABILITY
The information in this courseware title is distributed on ‘as is’ basis, without warranty.
While very precaution has been taken in the preparation of the course, not to the
authors shall have any library to my person or entity with respect to any loss or damage
caused or alleged to be caused directly or indirectly by the instruction contained in this
book or by computer software & hardware products described in it.
DISCLAIMER
We make a sincere effort to ensure the accuracy of the material described here in
however, makes no warranty, expressed or implied, with respect of the quality,
correctness, reliability, accuracy, of freedom from error of this document or the products
it describes. Data used in Example’s & sample data files are intended to be fictional.
Any resemblance to real persons or companies is entirely coincidental.
WWW.ICIT.IN 3
JAVA PROGRAMMING
WWW.ICIT.IN 4
JAVA PROGRAMMING
Table of Contents
Chapter 1 ...................................................................................................................................................... 8
1. Introduction of Java programming ................................................................................................... 8
1.1 What is Java?....................................................................................................................................... 9
1.2 Java Platforms / Editions ................................................................................................................... 10
1.3 Simple Program in java using Neat Beans......................................................................................... 14
Assignment No: 1 .................................................................................................................................... 14
Summary ................................................................................................................................................. 14
MCQ’s...................................................................................................................................................... 15
Fill in the blanks ...................................................................................................................................... 15
Chapter 2 .................................................................................................................................................... 16
2. Java Variables .................................................................................................................................. 16
2.1 Variable ............................................................................................................................................. 17
2.2 Types of Variables ............................................................................................................................. 17
Assignment No: 2 .................................................................................................................................... 18
2.3 Data Types in Java ............................................................................................................................. 18
Assignment No: 3 .................................................................................................................................... 19
2.4 Operators in Java .............................................................................................................................. 19
Assignment No: 4 .................................................................................................................................... 20
Assignment No: 5 .................................................................................................................................... 20
Summary ................................................................................................................................................. 21
MCQ’s...................................................................................................................................................... 21
Fill in the blanks ...................................................................................................................................... 21
3. Object Oriented Programming System ........................................................................................... 22
3.1 OOPs (Object-Oriented Programming System) ................................................................................ 23
3.2 What is a class in Java? ..................................................................................................................... 23
Assignment No: 6 .................................................................................................................................... 24
3.3 Object and Class Example: Initialization through Reference ............................................................ 24
Assignment No: 7 .................................................................................................................................... 24
3.4 Object and Class Example: Initialization through method ................................................................ 25
Assignment No: 8 .................................................................................................................................... 25
3.5 Inheritance ........................................................................................................................................ 25
Assignment No: 9 .................................................................................................................................... 26
3.6 Polymorphism ................................................................................................................................... 27
3.6.1 Java Runtime Polymorphism Example: Bank ................................................................................. 27
Assignment No 10 ................................................................................................................................... 27
3.7 Abstraction ........................................................................................................................................ 28
Assignment No: 11 .................................................................................................................................. 28
3.8 Encapsulation .................................................................................................................................... 29
Assignment No: 12 .................................................................................................................................. 29
3.9 Constructors in Java .......................................................................................................................... 30
1. Default Constructor ........................................................................................................................ 31
Assignment No: 13 .................................................................................................................................. 31
Assignment No: 14 .................................................................................................................................. 32
2. Parameterized Constructor............................................................................................................. 32
3.10 Constructor Overloading ................................................................................................................. 32
Assignment No: 15 .................................................................................................................................. 32
WWW.ICIT.IN 5
JAVA PROGRAMMING
Summary ................................................................................................................................................. 33
MCQ’s...................................................................................................................................................... 33
Fill in the blank ........................................................................................................................................ 34
Chapter 4 .................................................................................................................................................... 35
4. Static Class in Java ........................................................................................................................... 35
4.1 Static Class in Java ............................................................................................................................. 36
Assignment No: 16 .................................................................................................................................. 36
4.2 Java static method ............................................................................................................................ 37
Assignment No: 17 .................................................................................................................................. 37
4.3 Java static block ................................................................................................................................ 38
Assignment No: 18 .................................................................................................................................. 38
Summary ................................................................................................................................................. 38
MCQ’s...................................................................................................................................................... 39
Chapter 5 .................................................................................................................................................... 41
5. Interface and Package in Java ......................................................................................................... 41
5.1 Interface in Java ................................................................................................................................ 42
Assignment No: 21 .................................................................................................................................. 42
5.2 Multiple Inheritance in Java by Interface ......................................................................................... 43
Assignment No: 22 .................................................................................................................................. 43
5.3 Java Package ..................................................................................................................................... 43
Assignment No: 23 .................................................................................................................................. 44
Assignment No: 24 .................................................................................................................................. 44
Assignment No: 25 .................................................................................................................................. 45
Assignment No: 26 .................................................................................................................................. 45
Assignment No: 27 .................................................................................................................................. 46
Assignment No: 28 .................................................................................................................................. 46
Assignment No: 29 .................................................................................................................................. 47
Summary ................................................................................................................................................. 47
MCQ’s...................................................................................................................................................... 48
Fill in the blank’s ..................................................................................................................................... 49
Chapter 6 .................................................................................................................................................... 50
6. Array and String in Java................................................................................................................... 50
6.1 Java Array .......................................................................................................................................... 51
6.2 Types of Array in java ........................................................................................................................ 51
Assignment No: 30 .................................................................................................................................. 51
Assignment No: 31 .................................................................................................................................. 52
Assignment No: 32 .................................................................................................................................. 53
3) Jagged Array in Java ........................................................................................................................ 54
Assignment No: 33 .................................................................................................................................. 54
6.3 Java String ......................................................................................................................................... 54
6.4 Char Sequence Interface ................................................................................................................... 55
1) What is String in java? ..................................................................................................................... 55
2) How to create a string object? ........................................................................................................ 55
3) Why Java uses the concept of String literal? .................................................................................. 56
Assignment No: 34 .................................................................................................................................. 56
6.5 Java String class methods ................................................................................................................. 57
Summary ................................................................................................................................................. 57
WWW.ICIT.IN 6
JAVA PROGRAMMING
Summary ................................................................................................................................................. 58
Chapter 7 .................................................................................................................................................... 60
7. Threading and Stream classes in Java ............................................................................................. 60
7.1 What is Thread in Java? .................................................................................................................... 61
7.2 Java Thread class ............................................................................................................................... 61
7.3 Java Thread Methods ........................................................................................................................ 61
7.4 Multithreading in Java ...................................................................................................................... 62
7.5 Life cycle of a Thread ........................................................................................................................ 62
7.6 How to create thread ........................................................................................................................ 63
Assignment No 35 ................................................................................................................................... 63
Assignment No.36 ................................................................................................................................... 63
Assignment No.37 ................................................................................................................................... 64
7.7 Stream ............................................................................................................................................... 65
Assignment No 38 ................................................................................................................................... 66
Summary ................................................................................................................................................. 67
MCQ’s...................................................................................................................................................... 68
Chapter 8 .................................................................................................................................................... 69
8. Exception Handling in Java.............................................................................................................. 69
8.1 Exception Handling in Java................................................................................................................ 70
Assignment No: 39 .................................................................................................................................. 71
8.2 Try Catch Block .................................................................................................................................. 72
Assignment No: 40 .................................................................................................................................. 72
8.3 The Finally Block................................................................................................................................ 73
Assignment No: 41 .................................................................................................................................. 73
Summary ................................................................................................................................................. 74
MCQ’s...................................................................................................................................................... 74
Chapter 9 .................................................................................................................................................... 77
9. Collection in Java............................................................................................................................. 77
9.1 Collections in Java ............................................................................................................................. 78
9.3 What is Collection in Java ................................................................................................................. 78
9.4 ArrayList ............................................................................................................................................ 78
Assignment No: 42 .................................................................................................................................. 78
9.5 LinkedList .......................................................................................................................................... 79
Assignment No: 43 .................................................................................................................................. 79
9.6 Stack .................................................................................................................................................. 80
Assignment No: 44 .................................................................................................................................. 80
9.7 HashSet ............................................................................................................................................. 80
Assignment No 45 ................................................................................................................................... 80
9.8 TreeSet .............................................................................................................................................. 81
Assignment No 46 ................................................................................................................................... 81
9.9 Hash Map .......................................................................................................................................... 82
Assignment No 47 ................................................................................................................................... 82
Summary ................................................................................................................................................. 83
MCQ’s...................................................................................................................................................... 83
WWW.ICIT.IN 7
JAVA PROGRAMMING
Chapter 1
1. Introduction of Java programming
In this Chapter:
▪ History of java
▪ Types of Java Application
▪ Java Platforms
▪ Installation and configuration for Neat
bean software
▪ Difference between C++ and Java
▪ Assignment No: 1
WWW.ICIT.IN 8
JAVA PROGRAMMING
Platform: Any hardware or software environment in which a program runs, is known as a platform.
Since Java has a runtime environment (JRE) and API, it is called a platform.
Application
According to Sun, 3 billion devices run Java. There are many devices where Java is currently used. Some
of them are as follows:
1) Standalone Application
Standalone applications are also known as desktop applications or window-based applications. These
are traditional software that we need to install on every machine. Examples of standalone application
are Media player, antivirus, etc. AWT and Swing are used in Java for creating standalone applications.
2) Web Application
An application that runs on the server side and creates a dynamic page is called a web application.
Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for creating web
applications in Java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is called enterprise
application. It has advantages of the high-level security, load balancing, and clustering. In Java, EJB is
used for creating enterprise applications.
4) Mobile Application
An application which is created for mobile devices is called a mobile application. Currently, Android and
Java ME are used for creating mobile applications.
WWW.ICIT.IN 9
JAVA PROGRAMMING
It is a Java programming platform. It includes Java programming APIs such as java.lang, java.io, java.net,
java.util, java.sql, java.math etc. It includes core topics like OOPs, String, Regex, Exception, Inner classes,
Multithreading, I/O Stream, Networking, AWT, Swing, Reflection, Collection, etc.
It is an enterprise platform which is mainly used to develop web and enterprise applications. It is built
on the top of the Java SE platform. It includes topics like Servlet, JSP, Web Services, EJB, JPA, etc.
4) JavaFX
It is used to develop rich internet applications. It uses a light-weight user interface API.
Multiple inheritance C++ supports multiple inheritance. Java doesn't support multiple inheritance through
class. It can be achieved by interfaces in java.
Operator Overloading C++ supports operator overloading. Java doesn't support operator overloading.
Pointers C++ supports pointers. You can write Java supports pointer internally. However, you can't
pointer program in C++. write the pointer program in java. It means java has
restricted pointer support in java.
WWW.ICIT.IN 10
JAVA PROGRAMMING
Compiler and C++ uses compiler only. C++ is Java uses compiler and interpreter both. Java source
Interpreter compiled and run using the compiler code is converted into bytecode at compilation
which converts source code into time. The interpreter executes this bytecode at
machine code so, C++ is platform runtime and produces output. Java is interpreted
dependent. that is why it is platform independent.
Call by Value and Call C++ supports both call by value and Java supports call by value only. There is no call by
by reference call by reference. reference in java.
Structure and Union C++ supports structures and unions. Java doesn't support structures and unions.
Thread Support C++ doesn't have built-in support for Java has built-in thread support.
threads. It relies on third-party
libraries for thread support.
Step 1: As usual, go to Netbeans.org to download Step 2: Double click the Windows exe self-
the latest version of NetBeans. We downloaded extracting file.
the full version that is the full bundled 'package'.
Step 3: The NetBeans IDE installer will be Step 4: Then the NetBeans IDE installer wizard
launched. welcome page displayed. A list of default
packs and runtimes shown in this welcome page.
Click the Customize button.
WWW.ICIT.IN 11
JAVA PROGRAMMING
Step 5: In our case, se select all packs and Step 6: Accept the License Agreement and click
runtimes. Click OK. Next.
Step 7: Choose the installation path. Click Browse if Step 8: As usual, if the following Windows Security
you want to change. The Java JDK properly set Alert displayed, click the Unblock.
to the desired path for this machine. In our case we just
accept the given path. Click Next.
Step 9: Next is the GlassFish web server Step 10: Next, set the Apache Tomcat installation
installation path selection. We just accept the path. We just accept the given path. Change
default path give. Set the GlassFish administrator accordingly if you want to change by clicking the
(admin) password and the default is adminadmin. Browse button. Click Next.
Notice the http, https and GlassFish Administration
ports used. Click Next.
WWW.ICIT.IN 12
JAVA PROGRAMMING
Step 11: Next is the NetBeans IDE installation Step 12: The installation begins. Wait and relax.
summary. If you want to change the previously
selected settings, click Back otherwise click Install.
Step 13: Again, click the Unblock button. Step 14: The installation completed successfully as
shown in the following Figure. Click Finish.
WWW.ICIT.IN 13
JAVA PROGRAMMING
Assignment No: 1
System.out.println("Hello Java");
Output
Hello Java
History of java
Types of java Application
Difference between c++ and java
Procedure for installation and configurations for neatbeans software
How to use this software and hello program implementation
WWW.ICIT.IN 14
JAVA PROGRAMMING
Q2. Which component is responsible for Q7. What is the extension of java code files?
converting bytecode into machine specific code? a) .class
a) JVM b) .java
b) JDK c) .txt
c) JIT d) .js
d) JRE
Q8. What is the extension of compiled java
Q3. Which component is responsible to run java classes?
program? a) .class
a) JVM b) .java
b) JDK c) .txt
c) JIT d) .js
d) JRE
Q9. How can we identify whether a compilation
Q4. Which component is responsible to optimize unit is class or interface from a .class file?
bytecode to machine code? a) Java source file header
a) JVM b) Extension of compilation unit
b) JDK c) We cannot differentiate between class and
c) JIT interface
d) JRE d) The class or interface name should be post
fixed with unit type
Q5. Which statement is true about java?
a) Platform independent programming language Q10. What is use of interpreter?
b) Platform dependent programming language a) They convert bytecode to machine language
c) Code dependent programming language code
d) Sequence dependent programming language b) They read high level code and execute them
c) They are intermediated between JIT and JVM
d) It is a synonym for JIT
WWW.ICIT.IN 15
JAVA PROGRAMMING
Chapter 2
2. Java Variables
In this Chapter:
▪ Meaning of variable
▪ Types of Java Variables
▪ Java Platforms
▪ Assignment No 2.
▪ Data Types in Java
▪ Assignment No 3
▪ Operators in java
▪ Assignment No 4
▪ Assignment No 5
WWW.ICIT.IN 16
JAVA PROGRAMMING
2.1 Variable
• A variable is a container which holds the value while the java program is executed.
• A variable is assigned with a datatype.
• Variable is a name of memory location.
• There are three types of variables in java: local, instance and static.
• There are two types of data types in java: primitive and non-primitive.
• Variable is name of reserved area allocated in memory. In other words, it is a name of memory
location. It is a combination of "vary + able" that means its value can be changed.
1) Local Variable
A variable declared inside the body of the method is called local variable. You
can use this variable only within that method and the other methods in the
class aren't even aware that the variable exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called instance variable. It is
not declared as static.
It is called instance variable because its value is instance specific and is not shared among instances.
3) Static variable
A variable which is declared as static is called static variable. It cannot be local. You can create a single
copy of static variable and share among all the instances of the class. Memory allocation for static
variable happens only once when the class is loaded in the memory.
WWW.ICIT.IN 17
JAVA PROGRAMMING
Assignment No: 2
package javaapplication6;
/**
* @author Admin-PC
*/
int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
Output
10
10.0
WWW.ICIT.IN 18
JAVA PROGRAMMING
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Assignment No: 3
Typecasting
class Simple{
public static void main(String[] args){
float f=10.5f;
//int a=f;//Compile time error
int a=(int)f;
System.out.println(f);
System.out.println(a);
}
}
Output
10.5
10
Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in java which are given below:
o Unary Operator,
o Arithmetic Operator,
WWW.ICIT.IN 19
JAVA PROGRAMMING
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator
Assignment No: 4
Operator Example: ++ and --
class OperatorExample1{
public static void main(String args[]){
int x=10;
System.out.println(x++);
System.out.println(++x);
System.out.println(x--);
System.out.println(--x);
}
}
Output:
10
12
12
10
Assignment No: 5
Arithmetic Operator Example
class OperatorExample1{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);
System.out.println(a-b);
System.out.println(a*b);
System.out.println(a/b);
System.out.println(a%b);
}}
Output
15
5
50
2
WWW.ICIT.IN 20
JAVA PROGRAMMING
• What is variable
• Types of variables
• Program on how to use and declare variables.
• Data Types in Java
• Program on Typecasting
• Which operators are used in java
• Program on arithmetic operation
1. What is the range of data type short in Java? 6. What is the numerical range of a char in Java?
a) -128 to 127 a) -128 to 127
b) -32768 to 32767 b) 0 to 256
c) -2147483648 to 2147483647 c) 0 to 32767
d) None of the mentioned d) 0 to 65535
2. What is the range of data type byte in Java?
a) -128 to 127 7. Which of these coding types is used for data type
b) -32768 to 32767 characters in Java?
c) -2147483648 to 2147483647 a) ASCII
d) None of the mentioned b) ISO-LATIN-1
3. An expression involving byte, int, and literal c) UNICODE
numbers is promoted to which of these? d) None of the mentioned
a) int
b) long 8. Which of these values can a boolean variable
c) byte contain?
d) float a) True & False
4. Which of these literals can be contained in a data b) 0 & 1
type float variable? c) Any integer value.
a) 1.7e-308 d) Both a & b
b) 3.4e-038
c) 1.7e+308 9. Which of these occupy first 0 to 127 in Unicode
d) 3.4e-050 character set used for characters in Java?
5. Which data type value is returned by all a) ASCII
transcendental math functions? b) ISO-LATIN-1
a) int c) None of the mentioned
b) float
c) double 10. Which one is a valid declaration of a boolean?
d) long a) boolean b1 = 1;
b) boolean b2 = ‘false’;
c) boolean b3 = false;
Fill in the blanks d) boolean b4 = ‘true’
1. A variable is a __________________ which holds the value while the java program is executed.
2. Variable is a name of ____________________ location.
3. A variable declared inside the body of the method is called _________________ Variable.
4. A variable declared inside the class but outside the body of the method, is called ____________ variable.
5. A variable which is declared as static is called ___________________ variable.
WWW.ICIT.IN 21
JAVA PROGRAMMING
Chapter 3
3. Object Oriented Programming System
In this Chapter:
▪ Oops concept
▪ Assignment No.6
▪ Assignment No.7
▪ Assignment No.8
▪ Inheritance concept
▪ Assignment No.9
▪ Polymorphism Concept
▪ Assignment No.10
▪ Assignment No.11
▪ Abstraction and Encapsulation
▪ Assignment No.12
▪ Constructor in java
▪ Types of constructor
▪ Constructor Overloading
▪ Assignment No.13
WWW.ICIT.IN 22
JAVA PROGRAMMING
Object
An entity that has state and behavior is known as an object e.g. chair, bike,
marker, pen, table, car etc. It can be physical or logical (tangible and intangible). The example of an intangible
object is the banking system.
Class
class <class_name>{
field;
method; }
Java Program to illustrate how to define a class and fields
WWW.ICIT.IN 23
JAVA PROGRAMMING
Assignment No: 6
Assignment No: 7
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Anjana";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
Output
101 Anjana
WWW.ICIT.IN 24
JAVA PROGRAMMING
Assignment No: 8
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,"Anjana");
s2.insertRecord(222,"Pallavi");
s1.displayInformation();
s2.displayInformation();
}
}
Output
111 Anjana
222 Pallavi
3.5 Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as inheritance.
It provides code reusability. It is used to achieve runtime polymorphism.
WWW.ICIT.IN 25
JAVA PROGRAMMING
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.
In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called
child or subclass.
Assignment No: 9
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);
}
}
Output
Programmer salary is:40000.0
Bonus of programmer is:10000
WWW.ICIT.IN 26
JAVA PROGRAMMING
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only.
3.6 Polymorphism
If one task is performed by different ways, it is
known as polymorphism. For example: to convince
the customer differently, to draw something, for
example, shape, triangle, rectangle, etc.
Assignment No 10
Consider a scenario where Bank is a class that provides a method to get the rate of interest. However, the rate of
interest may differ according to banks. For example, SBI, ICICI, and AXIS banks are providing 8.4%, 7.3%, and 9.7%
rate of interest.
class Bank{
float getRateOfInterest(){return 0;}
}
class SBI extends Bank{
float getRateOfInterest(){return 8.4f;}
}
class ICICI extends Bank{
float getRateOfInterest(){return 7.3f;}
}
class AXIS extends Bank{
float getRateOfInterest(){return 9.7f;}
}
class TestPolymorphism{
WWW.ICIT.IN 27
JAVA PROGRAMMING
Output
3.7 Abstraction
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS
where you type the text and send the message. You don't know the internal processing about the message
delivery.
A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods.
It needs to be extended and its method implemented. It cannot be instantiated.
Assignment No: 11
WWW.ICIT.IN 28
JAVA PROGRAMMING
3.8 Encapsulation
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data
(methods) together as a single unit. In encapsulation, the variables of a class will be hidden from
other classes, and can be accessed only through the methods of their current class. Therefore, it is
also known as data hiding.
Assignment No: 12
EncapTest.java
WWW.ICIT.IN 29
JAVA PROGRAMMING
RunEncap.java
WWW.ICIT.IN 30
JAVA PROGRAMMING
1. Default Constructor
<class_name>(){}
Assignment No: 13
WWW.ICIT.IN 31
JAVA PROGRAMMING
Assignment No: 14
2. Parameterized Constructor
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan
Constructor overloading in Java is a technique of having more than one constructor with different parameter lists.
They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler
by the number of parameters in the list and their types.
Assignment No: 15
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
WWW.ICIT.IN 32
JAVA PROGRAMMING
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
WWW.ICIT.IN 33
JAVA PROGRAMMING
WWW.ICIT.IN 34
JAVA PROGRAMMING
Chapter 4
4. Static Class in Java
In this Chapter:
▪ What is Static class in Java.
▪ Assignment No 16.
▪ Java static methods
▪ Assignment No 17.
▪ Java static block
▪ This keyword and its usage.
▪ Assignment No.19
▪ Super keyword and its usage
▪ Assignment No 20.
WWW.ICIT.IN 35
JAVA PROGRAMMING
We can apply java static keyword with variables, methods, blocks and
nested class.
The static keyword belongs to the class than an instance of the class.
Assignment No: 16
class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class TestStaticVariable2
{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display();
WWW.ICIT.IN 36
JAVA PROGRAMMING
}
}
Output
111 Karan ITS
222 Aryan ITS
Assignment No: 17
class Student{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display(){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
public class TestStaticMethod1{
public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
WWW.ICIT.IN 37
JAVA PROGRAMMING
s3.display();
}
}
Output
111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
Assignment No: 18
class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}
}
Output
static block is invoked
Hello main
This keyword
There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current
object.
WWW.ICIT.IN 38
JAVA PROGRAMMING
Q1. Which of these cannot be declared static? Q6. What will be the output of the following
a) class program?
b) object class W
c) variable {
d) method static int c = 0;
Q2. Which of the following statements are public static void main(String[] args)
incorrect? {
a) static methods can call other static methods W w1 = c();
only W w2 = c(w1);
b) static methods must only access static data W w3 = c(w2);
c) static methods can not refer to this or super W w4 = c(w3);
in any way }
d) when object of class is declared, each object private W()
contains its own copy of static variables {
Q3. Which of these methods must be made System.out.println("c = " + c);
static? }
a) main() static W c()
b) delete() {
c) run() return c++ <= 0 ? new W() : null;
d) finalize() }
Q4.Super keyword in java is used to static W c(W w)
a) Refer immediate parent class instance {
variables. return w.c++ == 1 ? new W() : null;
b) Invoke immediate parent class methods. }
c)Invoke immediate parent class constructor. }
d)All c=1
Q5. What will be the output of the following c=2
program c=1
public class Time { c=2
int a = 50; c=3
int b = 10; c=1
public static void main(String args[]) { c=2
a += b--; c=3
System.out.println(a); c=4
} Compilation Error
} NullPointerException
a)60 Q7. What will be the output of the program?
b)50 class Output
c)59 {
d)49 final static short i = 2;
e) Compilation Error or Runtime Error public static int j = 0;
public static void main(String [] args)
{
for (int k = 0; k < 3; k++)
WWW.ICIT.IN 39
JAVA PROGRAMMING
1. The ______________________ is a reference variable that is used to refer parent class objects.
2. _____________keyword is used to pass as an argument to a method.
WWW.ICIT.IN 40
JAVA PROGRAMMING
Chapter 5
5. Interface and Package in Java
In this Chapter:
• What is interface?
• Relationship between interface and classes
• Assignment No 21
• Multiple inheritance in java by interface
• Assignment No 22
• Java package
• Assignment NO 23
• Accessing package
• Assignment NO 24
• Assignment NO 25
• Assignment NO 26
• Assignment No.27
• Sub package
• Sending class file to another directory
• Assignment No.28
• Package class
• Assignment No29
WWW.ICIT.IN 41
JAVA PROGRAMMING
Assignment No: 21
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
Output
Hello
WWW.ICIT.IN 42
JAVA PROGRAMMING
Assignment No: 22
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}
}
Output
Hello
Welcome
WWW.ICIT.IN 43
JAVA PROGRAMMING
Assignment No: 23
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
Output
Welcome to package
import package.*;
import package.classname;
fully qualified name.
1) Using packagename. *
If you use package. * then all the classes and interfaces of this package will be accessible but not subpackages.
The import keyword is used to make the classes and interface of another package accessible to the current
package.
Assignment No: 24
//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 ();
WWW.ICIT.IN 44
JAVA PROGRAMMING
obj.msg ();
}
}
Output
Hello
2) Using packagename.classname
If you import package. classname then only declared class of this package will be accessible.
Assignment No: 25
class B {
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output
Hello
It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date
class.
Assignment No: 26
//save by A.java
package pack;
public class A{
WWW.ICIT.IN 45
JAVA PROGRAMMING
4) Subpackage in java
Package inside the package is called the Subpackage
It should be created to categorize the package further.
The standard of defining package is domain. company. Package e.g. com. javatpoint.bean or org.sssit.dao.
Assignment No: 27
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
Output
Hello Subpackage
Assignment No: 28
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
Output
Welcome to package
WWW.ICIT.IN 46
JAVA PROGRAMMING
5) Package class
The package class provides methods to get information about the specification and implementation of a
package. It provides methods such as getName (), getImplementationTitle (),
getImplementationVendor(), getImplementationVersion() etc.
Assignment No: 29
• What is interface?
• Relationship between interface and class
• Example for implementation class and interface
• Multiple inheritance in java by interface
• Example on implementation for multiple inheritance by interface
• Java package
• Example of package
• Accessing package
• By import packagename. *
WWW.ICIT.IN 47
JAVA PROGRAMMING
4.Which keyword can protect a class in a 9.Which is the correct way to inherit and
package from accessibility by the classes implement the interface?
outside the package. Consider and example, Interface is IAnimal and
i) private ii) protected iii) final a class is Cat that wants to implement interface.
A) i only A) class Cat implements IAnimal{}
B) ii only B) class Cat extends IAnimal{}
C) class Cat import IAnimal{}
WWW.ICIT.IN 48
JAVA PROGRAMMING
WWW.ICIT.IN 49
JAVA PROGRAMMING
Chapter 6
6. Array and String in Java
In this Chapter:
• Java Array
• Advantage and Disadvantage
• Types of Array
• Assignment No 30
• Assignment No 31
• Declaration, instantiation and initialization
of java array
• Assignment No 32
• Jagged Array
• Assignment No33
• Java string
• How to create string
• Assignment No34
• Java string class methods
WWW.ICIT.IN 50
JAVA PROGRAMMING
It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array.
Array in java is index-based; the first element of the array is stored at the 0 index.
Advantages:
Code Optimization: It makes the code optimized; we can retrieve or sort the data efficiently.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To solve
this problem, collection framework is used in Java which grows automatically.
arrayRefVar=new datatype[size];
Assignment No: 30
WWW.ICIT.IN 51
JAVA PROGRAMMING
Assignment No: 31
WWW.ICIT.IN 52
JAVA PROGRAMMING
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Assignment No: 32
Let's see the simple example to declare instantiate, initialize and print the 2Dimensional array.
WWW.ICIT.IN 53
JAVA PROGRAMMING
If we are creating odd number of columns in a 2D array, it is known as a jagged array. In other words, it is an array
of arrays with different number of columns.
Assignment No: 33
class TestJaggedArray{
public static void main(String[] args){
//declaring a 2D array with odd columns
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
//initializing a jagged array
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
char[] ch={'I','C','I','T','I','N','S','T','I',’T’,’U’,”T’,’E’};
String s=new String(ch);
is same as:
String s="ICITINSTITUTE";
WWW.ICIT.IN 54
JAVA PROGRAMMING
Java String class provides a lot of methods to perform operations on string such as compare(), concat(), equals(),
split(), length(), replace(), compareTo(), intern(), substring() etc.
The java.lang.String class implements Serializable, Comparable and Char Sequence interfaces.
The Java String is immutable which means it cannot be changed. Whenever we change any string, a new instance is
created. For mutable strings, you can use StringBuffer and StringBuilder classes.
We will discuss immutable string later. Let's first understand what is String in Java and how to create the String
object.
Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of
characters. The java.lang.String class is used to create a string object.
By string literal
WWW.ICIT.IN 55
JAVA PROGRAMMING
String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already exists in
the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance
is created and placed in the pool. For example:
String s1="Welcome";
In the above example, only one object will be created. Firstly, JVM will not find any string object with the value
"Welcome" in string constant pool, that is why it will create a new object. After that it will find the string with the
value "Welcome" in the pool, it will not create a new object but will return the reference to the same instance.
Note: String objects are stored in a special memory area known as the "string constant pool".
To make Java more memory efficient (because no new objects are created if it exists already in the string constant
pool).
2) By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal "Welcome" will
be placed in the string constant pool. The variable s will refer to the object in a heap (non-pool).
Assignment No: 34
WWW.ICIT.IN 56
JAVA PROGRAMMING
The java.lang.String class provides many useful methods to perform operations on sequence of char values.
WWW.ICIT.IN 57
JAVA PROGRAMMING
6. What is the output of this program? 10.Which of these method of class String is
class array_output used to extract a single character from a String
{ object?
public static void main(String args[]) CHARAT()
{ charat()
int array_variable [] = new int[10]; charAt()
for (int i = 0; i < 10; ++i) ChatAt()
{
WWW.ICIT.IN 58
JAVA PROGRAMMING
WWW.ICIT.IN 59
JAVA PROGRAMMING
Chapter 7
7. Threading and Stream classes in Java
In this Chapter:
• What is thread in java
• Java Thread class
• Java Thread methods
• Multithreading in java
• Advantages of java multithreading
• Life cycle of thread
• Creation of thread
• Assignment No 35
• Synchronization in java
• Types of Synchronization
• Assignment No 36
• Stream in java
• Stream classes
• Assignment No37
• Assignment No 38
WWW.ICIT.IN 60
JAVA PROGRAMMING
Java provides Thread class to achieve thread programming. Thread class provides constructors and
methods to create and perform operations on a thread. Thread class extends Object class and
implements Runnable interface.
WWW.ICIT.IN 61
JAVA PROGRAMMING
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are
used to achieve multitasking.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
New
Runnable
Running
WWW.ICIT.IN 62
JAVA PROGRAMMING
The thread is in running state if the thread scheduler has selected it.
Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
Terminated
Assignment No 35
Assignment No.36
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...
WWW.ICIT.IN 63
JAVA PROGRAMMING
If you are not extending the Thread class, your class object would not be treated as a thread object. So, you need
to explicitly create Thread class object. We are passing the object of your class that implements Runnable so that
your class run () method may execute.
3) Synchronization in Java
Synchronization in java is the capability to control the access of multiple threads to any shared resource.
Java Synchronization is better option where we want to allow only one thread to access the shared resource.
Assignment No.37
WWW.ICIT.IN 64
JAVA PROGRAMMING
7.7 Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because it is like a
stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with the console.
Stream Classes
1) OutputStream
Java application uses an output stream to write data to a destination; it may be a file, an array, peripheral device
or socket.
2) InputStream
Java application uses an input stream to read data from a source; it may be a file, an array, peripheral device or
socket.
Let's understand the working of Java OutputStream and InputStream by the figure given below.
WWW.ICIT.IN 65
JAVA PROGRAMMING
OutputStream Hierarchy
InputStream Hierarchy
Assignment No 38
Output
Success...
WWW.ICIT.IN 66
JAVA PROGRAMMING
WWW.ICIT.IN 67
JAVA PROGRAMMING
4. What will happen if two thread of the same 9. Which of these method of Thread class is used
priority are called to be processed to find out the priority given to a thread?
simultaneously? a) get()
a) Anyone will be executed first lexographically b) ThreadPriority()
b) Both of them will be executed simultaneously c) getPriority()
c) None of them will be executed d) getThreadPriority()
d) It is dependent on the operating system
10. Which of these method of Thread class is
5. Which of these stream contains the classes used to Suspend a thread for a period of time?
which can work on character stream? a) sleep()
a) InputStream b) terminate()
b) OutputStream c) suspend()
c) Character Stream d) stop()
d) All of the mentioned
WWW.ICIT.IN 68
JAVA PROGRAMMING
Chapter 8
8. Exception Handling in Java
In this Chapter:
• Exception Handling
• Advantages of Exception Handling
• Hierarchy of Exception classes
• Types of Exception
• Assignment No39
• Try-Catch block
• Assignment No 40
• Finally block
• Assignment No 41
WWW.ICIT.IN 69
JAVA PROGRAMMING
WWW.ICIT.IN 70
JAVA PROGRAMMING
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g. ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-
time, but they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Keyword Description
try The "try" keyword is used to specify a block where we should place exception code. The try block
must be followed by either catch or finally. It means, we can't use try block alone.
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 important code of the program. It is executed whether an
exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies that
there may occur an exception in the method. It is always used with method signature.
Assignment No: 39
WWW.ICIT.IN 71
JAVA PROGRAMMING
In our example, TRY block will contain the code to connect to the server.
CATCH block will contain the code to connect to the backup server.
In case the server is up, the code in the CATCH block will be ignored. In case the server is down, an
exception is raised, and the code in catch block will be executed.
Assignment No: 40
class JavaException {
public static void main(String args[]) {
try {
int d = 1;
int n = 20;
int fraction = n / d;
int g[] = {
1
};
g[20] = 100;
}
/*catch(Exception e){
System.out.println("In the catch clock due to Exception = "+e);
}*/
catch (ArithmeticException e) {
System.out.println("In the catch clock due to Exception = " + e);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("In the catch clock due to Exception = " + e);
}
WWW.ICIT.IN 72
JAVA PROGRAMMING
System.out.println("End Of Main");
}
}
Output
In the catch clock due to Exception = java.lang.ArrayIndexOutOfBoundsException: 20
End of Main
The finally block follows a try block or a catch block. A finally block of code always executes, irrespective
of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter
what happens in the protected code.
Syntax
try {
// Protected code
// Catch block
// Catch block
// Catch block
} finally {
Assignment No: 41
WWW.ICIT.IN 73
JAVA PROGRAMMING
WWW.ICIT.IN 74
JAVA PROGRAMMING
class exception_handling }
{ System.out.print(sum);
public static void main(String args[]) }
{ }
try a) 0
{ b) 05
int a, b; c) Compilation Error
b = 0; d) Runtime Error
a = 5 / b; 8. What is the output of this program?
System.out.print("A"); class exception_handling
} {
catch(ArithmeticException e) public static void main(String args[])
{ {
System.out.print("B"); try
} {
finally int a, b;
{ b = 0;
System.out.print("C"); a = 5 / b;
} System.out.print("A");
} }
} catch(ArithmeticException e)
a) A {
b) B System.out.print("B");
c) AC }
d) BC }
7. What is the output of this program? }
class exception_handling a) A
{ b) B
public static void main(String args[]) c) Compilation Error
{ d) Runtime Error
try 9. At runtime, error is recoverable.
{ a) True
int i, sum; b) False
sum = 10;
for (i = -1; i < 3 ;++i) 10.Which of the following should be true of the
sum = (sum / i); object thrown by a thrown statement?
} a) Should be assignable to String type
catch(ArithmeticException e) b) Should be assignable to Exception type
{ c) Should be assignable to Throwable type
System.out.print("0"); d) Should be assignable to Error type
WWW.ICIT.IN 75
JAVA PROGRAMMING
WWW.ICIT.IN 76
JAVA PROGRAMMING
Chapter 9
9. Collection in Java
In this Chapter:
• Java Collection Framework
• Hierarchy of collection Framework
• Collection Interface
• Array List
• Assignment No 42
• Linked List
• Assignment No 43
• Stack
• Assignment No 44
• Hash Set
• Assignment No 45
• Tree Set
• Assignment No 46
• Hash Map
• Assignment No.47
WWW.ICIT.IN 77
JAVA PROGRAMMING
9.4 ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the duplicate element of
different data types. The ArrayList class maintains the insertion order and is non-synchronized. The elements
stored in the ArrayList class can be randomly accessed.
Assignment No: 42
import java.util.*;
class TestJavaCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Anjana");//Adding object in arraylist
list.add("Sanjana");
WWW.ICIT.IN 78
JAVA PROGRAMMING
list.add("Amruta");
list.add("Archana");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output
Anjana
Sanjana
Amruta
Archana
9.5 LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally to store the elements. It can
store the duplicate elements. It maintains the insertion order and is not synchronized. In LinkedList, the
manipulation is fast because no shifting is required.
Assignment No: 43
import java.util.*;
public class TestJavaCollection1{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Archana");
al.add("Anjali");
al.add("Archana");
al.add("Vijaya");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output
Archana
Anjali
Archana
Vijaya
WWW.ICIT.IN 79
JAVA PROGRAMMING
9.6 Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e., Stack. The stack contains
all of the methods of Vector class and also provides its methods like boolean push(), boolean peek(), boolean
push(object o), which defines its properties.
Assignment No: 44
import java.util.*;
public class TestJavaCollection1{
public static void main(String args[]){
Stack<String> stack = new Stack<String>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output
Ayush
Garvit
Amit
Ashish
9.7 HashSet
HashSet class implements Set Interface. It represents the collection that uses a hash table for storage. Hashing is
used to store the elements in the HashSet. It contains unique items.
Assignment No 45
import java.util.*;
public class TestJavaCollection1{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
WWW.ICIT.IN 80
JAVA PROGRAMMING
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output
Vijay
Ravi
Ajay
9.8 TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet, TreeSet also contains
unique elements. However, the access and retrieval time of TreeSet is quite fast. The elements in TreeSet stored in
ascending order.
Assignment No 46
import java.util.*;
public class TreeSetDemo {
public static void main(String args[]) {
// Create a tree set
TreeSet ts = new TreeSet();
WWW.ICIT.IN 81
JAVA PROGRAMMING
The Map interface maps unique keys to values. A key is an object that you use to retrieve a value at a
later date.
Given a key and a value, you can store the value in a Map object. After the value is stored, you can
retrieve it by using its key.
Several methods throw a NoSuchElementException when no items exist in the invoking map.
A ClassCastException is thrown when an object is incompatible with the elements in a map.
A NullPointerException is thrown if an attempt is made to use a null object and null is not allowed in the
map.
An UnsupportedOperationException is thrown when an attempt is made to change an unmodifiable
map.
Assignment No 47
import java.util.*;
public class CollectionsDemo {
public static void main(String[] args) {
Map m1 = new HashMap();
m1.put("Zara", "8");
m1.put("Mahnaz", "31");
m1.put("Ayan", "12");
m1.put("Daisy", "14");
System.out.println();
System.out.println(" Map Elements");
System.out.print("\t" + m1);
}
}
Output
Map Elements
{Daisy=14, Ayan=12, Zara=8, Mahnaz=31}
WWW.ICIT.IN 82
JAVA PROGRAMMING
WWW.ICIT.IN 83
JAVA PROGRAMMING
1. The ------------- in Java is a framework that provides architecture to store and manipulate the group of
objects.
3. The ------------package contains all the classes and interfaces for the Collection framework.
WWW.ICIT.IN 84