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

Java Final Book (1)

The document provides an overview of Java programming, including a message from the Managing Director of ICIT Education Pvt. Ltd., outlining the institute's core purpose and values. It details the types of Java applications, the various Java platforms, and compares Java with C++. Additionally, it includes a structured table of contents for a Java programming course, covering topics such as variables, object-oriented programming, and exception handling.

Uploaded by

jamesbond.1870dc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Java Final Book (1)

The document provides an overview of Java programming, including a message from the Managing Director of ICIT Education Pvt. Ltd., outlining the institute's core purpose and values. It details the types of Java applications, the various Java platforms, and compares Java with C++. Additionally, it includes a structured table of contents for a Java programming course, covering topics such as variables, object-oriented programming, and exception handling.

Uploaded by

jamesbond.1870dc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

JAVA PROGRAMMING

Java Programming

Java
Programming
Language
WWW.ICIT.IN 1
JAVA PROGRAMMING

Message

Mr. Santosh Khadtare


(Managing Director)
(ICIT Education Pvt. Ltd.)

Message from Managing Director Desk

Dear Students and Parents,


Welcome with warmest greetings and thank you for trusting ICIT Computer Institute. We are optimistic
that the information provided in this institute can assist you in your academic or career plans. We are
honored to have your interest in us.
I take this opportunity to thank our valued students, whose continued patronage and confidence in our
courses inspires us to extend the best of services and enables us to provide value for their money.

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,

With Best Regards,

WWW.ICIT.IN 2
JAVA PROGRAMMING

NOTICE OF RIGHTS

No part of this publication may be reproduced, transcribed, stored in a retrieval system,


or translated in to any language or computer language, in any form or by any means,
electronic, mechanical, magnetic, optical, chemical, manual, or otherwise, without the
prior written permission of Author.

TRADEMARK NOTICE

Java Programming Language is trademarks of respective owners. Throughout this


courseware title, trademarks names are used. Rather than just put a trademark symbol
in each occurrence of a trademarked name, we state we are using the name only in an
editorial fashion and to the benefit of the trademark owner with no intention of the
trademark.

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

1.1 What is Java?

Java is a programming language and a platform.


Java is a high level, robust, object-oriented and secure programming language.

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:

Desktop Applications such as acrobat reader, media player, antivirus etc.


Web Applications such as irctc.co.in etc.
Enterprise Applications such as banking applications, Mobile, Embedded System, Smart Card,
Robotics, Games etc.

Types of Java Applications


There are mainly 4 types of applications that can be created using Java programming:

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

1.2 Java Platforms / Editions

There are 4 platforms or editions of Java:

1) Java SE (Java Standard Edition)

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.

2) Java EE (Java Enterprise Edition)

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.

3) Java ME (Java Micro Edition)

It is a micro platform which is mainly used to develop mobile applications.

4) JavaFX

It is used to develop rich internet applications. It uses a light-weight user interface API.

Difference between C++ vs Java

Comparison Index C++ Java

Platform-independent C++ is platform-dependent. Java is platform-independent.


Mainly used for C++ is mainly used for system Java is mainly used for application programming. It
programming. is widely used in window, web-based, enterprise
and mobile applications.
Design Goal C++ was designed for systems and Java was designed and created as an interpreter for
applications programming. It was an printing systems but later extended as a support
extension of C programming language. network computing. It was designed with a goal of
being easy to use and accessible to a broader
audience.
Goto C++ supports the goto statement. Java doesn't support the goto statement.

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.

Installation and configuration Steps for Neat beans IDE

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

1.3 Simple Program in java using Neat Beans

Step 1- file ->new file-> java ->java application

Step 2: Click next->project name->hello->finish

Assignment No: 1

Save with Hello.java


package hello;

public class Hello {

public static void main(String[] args) {

System.out.println("Hello Java");

Output
Hello Java

Summary In this chapter, you have learned about:

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

MCQ’s Practice: Unsolved Multiple Choice Question’s


Q1. Which component is used to compile, debug Q6. Which of the below is invalid identifier with
and execute java program? the main method?
a) JVM a) public
b) JDK b) static
c) JIT c) private
d) JRE d) final

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

Fill in the blanks


1. Java__________________ are java programs, which are specially made to run in java, enabled in a java,
enabled web browser.
2. The Java system has embedded ____________________ which eliminates the hassle of memory
management.
3. Java byte code is binary and is ______________________.
4. The byte code file created by the java compiler has a _________________ extension.
5. The ____________________ consists of number of executable, which are command line driven.
6. __________________________ used to debug java programs.

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.

2.2 Types of Variables

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.

A local variable cannot be defined with "static" keyword.

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

*/

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

int a=10;

float f=a;

System.out.println(a);

System.out.println(f);

Output
10

10.0

2.3 Data Types in Java


Data types specify the different sizes and values that can be stored in the variable.

There are two types of data types in Java

1. Primitive data types: The primitive data types include


Boolean, char, byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays

WWW.ICIT.IN 18
JAVA PROGRAMMING

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 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

2.4 Operators in Java

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

Summary In this chapter, you have learned about:

• 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

MCQ’s Practice: Unsolved Multiple Choice Question’s

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

3.1 OOPs (Object-Oriented Programming System)

Object means a real-world entity such as a pen, chair, table,


computer, watch, etc.

Object-Oriented Programming is a methodology or paradigm to


design a program using classes and objects.

It simplifies the software development and maintenance by


providing some concepts:

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.

Characteristics of Object Different ways to create an object in Java

Class

3.2 What is a class in Java?


A class is a group of objects which have common properties. It is a template or blueprint from which objects are
created. It is a logical entity. It can't be physical.

Syntax to declare a 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

//Defining a Student class.


class Student{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student ();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}
Output
0
Null

3.3 Object and Class Example: Initialization through Reference

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

3.4 Object and Class Example: Initialization through method

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.

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.

WWW.ICIT.IN 25
JAVA PROGRAMMING

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.

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.

Java Inheritance Example

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

Types of inheritance in java

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.

In Java, we use method overloading and method


overriding to achieve polymorphism.
Another example can be to speak something; for
example, a cat speaks meow, dog barks woof, etc.

3.6.1 Java Runtime Polymorphism Example: Bank

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

public static void main(String args[]){


Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
}
}

Output

SBI Rate of Interest: 8.4


ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7

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.

Abstract class in Java

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.

Points to Remember (Rules for java abstract class)

Assignment No: 11

abstract class Shape{


abstract void draw();
}
//In real scenario, implementation is provided by others i.e.
unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}

WWW.ICIT.IN 28
JAVA PROGRAMMING

//In real scenario, method is called by programmer or user


class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape() method
s.draw();
}
}
Output
drawing circle

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

Demonstrates how to achieve Encapsulation

EncapTest.java

public class EncapTest {


private String name;
private String idNum;
private int age;
public int getAge() {
return age;
}
public String getName() {
return name;
}
public String getIdNum() {
return idNum;
}
public void setAge( int newAge) {
age = newAge;
}
public void setName(String newName) {
name = newName;
}
public void setIdNum( String newId) {
idNum = newId;
}

WWW.ICIT.IN 29
JAVA PROGRAMMING

RunEncap.java

public class RunEncap {


public static void main(String args[]) {
EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("\nName : " + encap.getName() + " \nAge : " + encap.getAge());
}
}
Output:
Name: James Age: 20

3.9 Constructors in Java


Constructors are used to initialize the object’s state. Like methods, a constructor also contains collection
of statements (i.e. instructions) that are executed at time of Object creation.

When is a Constructor called?


Each time an object is created using new () keyword at least one constructor (it could be default
constructor) is invoked to assign initial values to the data members of the same class.

Rules for creating Java constructor


There are two rules defined for the constructor.
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors

WWW.ICIT.IN 30
JAVA PROGRAMMING

1. Default Constructor

A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:

<class_name>(){}

Assignment No: 13

//Java Program to create and call a default constructor


class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Output
Bike is created

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

3.10 Constructor Overloading


In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods.

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);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output:
111 Karan 0
222 Aryan 25

Summary In this chapter, you have learned about:

• What is object-oriented programming structure.


• Characteristics of object
• Different ways to create object in java
• What is class
• Creation of class
• Inheritance concept
• Polymorphism in java
• Abstract class in java
• Rules for abstract class
• Encapsulation
• Constructor in java
• Types of java Constructor

MCQ’s Practice: Unsolved Multiple Choice Question’s

1) Which of the following is not OOPS c) Polymorphism


concept in Java? d) Compilation
a) Inheritance 2) Which of the following is a type of
b) Encapsulation polymorphism in Java?

WWW.ICIT.IN 33
JAVA PROGRAMMING

a) Compile time polymorphism 6) Which concept of Java is achieved by


b) Execution time polymorphism combining methods and attribute into a
c) Multiple polymorphism class?
d) Multilevel polymorphism a) Encapsulation
3) When does method overloading is b) Inheritance
determined? c) Polymorphism
a) At run time d) Abstraction
b) At compile time
c) At coding time 7) What is it called if an object has its own
d) At execution time lifecycle and there is no owner?
a) Aggregation
4) When Overloading does not occur? b) Composition
a) More than one method with same c) Encapsulation
name but different method signature and d) Association
different number or type of parameters
b) More than one method with same 8) What is it called where child object gets
name, same signature but different killed if parent object is killed?
number of signature a) Aggregation
c) More than one method with same b) Composition
name, same signature, same number of c) Encapsulation
parameters but different type d) Association
d) More than one method with same 9) What is it called where object has its
name, same number of parameters and own lifecycle and child object cannot
type but different signature belong to another parent object?
a) Aggregation
5) Which concept of Java is a way of b) Composition
converting real world objects in terms of c) Encapsulation
class? d) Association
a) Polymorphism
b) Encapsulation 10) Method overriding is combination of
c) Abstraction inheritance and polymorphism?
d) Inheritance a) True
b) false

Fill in the blank

1. _____________________ is a way to develop applications by using objects as building blocks.


2. Classes are used to instantiate ____________________ which are directly used in programs.
3. A class is made up of two components a set of attributes called _______________ and their behavior
called __________________.
4. The ability of class to inherit attributes and methods from more than one superclass is called
__________________inheritance.
5. The methods used to instantiate the object from class is called _________________methods.

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

4.1 Static Class in Java


The static keyword in Java is used for memory management mainly.

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.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class

Example of static variable

Java Program to demonstrate the use of static variable

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

4.2 Java static method


If you apply static keyword with any method, it is known as static
method.

o A static method belongs to the class rather than the object of


a class.
o A static method can be invoked without the need for creating
an instance of a class.
o A static method can access static data member and can
change the value of it.

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

4.3 Java static block


o Is used to initialize the static data member.
o It is executed before the main method at the time of classloading.

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.

Summary In this chapter, you have learned about:

• What is static class in java


• We learned what is static variable, class and methods in java.
• We learned this and super keyword and its usage.

WWW.ICIT.IN 38
JAVA PROGRAMMING

MCQ’s Practice: Unsolved Multiple Choice Question’s

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

{ String obj = "I LIKE JAVA";


switch (k) System.out.println(obj.charAt(3));
{ }
case i: System.out.print(" 0 "); }
case i-1: System.out.print(" 1 "); a)I
case i-2: System.out.print(" 2 "); b)L
} c)K
} d) E
} Q9.Super keyword in java is used to
} Refer immediate parent class instance variables.
Invoke immediate parent class methods.
210100 Invoke immediate parent class constructor.
012122 All
212012 Q10. False statement about static method in
012 java
Compilation error Belongs to class not object of the class
Q8. What is the output of this program? Can be called without any object creation of a
class string_class class
{ Can access non static and static variables both.
public static void main(String args[]) All are correct.
{

Fill in the blank

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.

3.______________ keyword is used to refer current object of a class in Java.

4. Java ____________________ variable is used to refer common properties to all objects.

5. The ___________________ in Java is used for memory management mainly.



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

5.1 Interface in Java


An interface in java is a blueprint of a class. It has static constants and abstract methods.

• The interface in Java is a mechanism to achieve abstraction.


• There can be only abstract methods in the Java interface, not method body.
• It is used to achieve abstraction and multiple inheritances in Java.
• In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.
• Java Interface also represents the IS-A relationship.
• It cannot be instantiated just like the abstract class.
• Since Java 8, we can have default and static methods in an interface.
• Since Java 9, we can have private methods in an interface.

The relationship between classes and interfaces

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

5.2 Multiple Inheritance in Java by Interface

If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as


multiple inheritances.

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

5.3 Java Package


• A java package is a group of similar types of classes,
interfaces and sub-packages.
• Package in java can be categorized in two form, built-
in package and user-defined package.
• There are many built-in packages such as java, lang,
awt, javax, swing, net, io, util, sql etc.
• Here, we will have the detailed learning of creating
and using user-defined packages.

WWW.ICIT.IN 43
JAVA PROGRAMMING

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

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

How to access package from another package?


There are three ways to access the package from outside the 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.

Example of package that import the packagename. *

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

Example of package by import package. classname


//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;

class B {
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output
Hello

3) Using fully qualified name


If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to
import. But you need to use fully qualified name every time when you are accessing the class or interface.

It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date
class.

Example of package by import fully qualified name

Assignment No: 26

//save by A.java
package pack;
public class A{

WWW.ICIT.IN 45
JAVA PROGRAMMING

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


}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output
Hello
Note: If you import a package, subpackages will not be imported.

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

How to send the class file to another directory or drive?


There is a scenario, I want to put the class file of A.java source file in classes
folder of c: drive. For example:

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

public class PackageInfo {


public static void main(String args[]){
Package p=Package.getPackage("java.lang");
System.out.println("package name: "+p.getName());
System.out.println("Specification Title: "+p.getSpecificationTitle()); System.out.println("Specification
Vendor: "+p.getSpecificationVendor());
System.out.println("Specification Version: "+p.getSpecificationVersion());
System.out.println("Implementaion Title: "+p.getImplementationTitle());
System.out.println("Implementation Vendor: "+p.getImplementationVendor());
System.out.println("Implementation Version: "+p.getImplementationVersion());
System.out.println("Is sealed: "+p.isSealed());
}
}
Output
package name: java. Lang

Specification Title: Java Platform API Specification


Specification Vendor: Sun Microsystems, Inc.
Specification Version: 1.6
Implementation Title: Java Runtime Environment
Implementation Vendor: Sun Microsystems, Inc.
Implementation Version: 1.6.0_30
IS sealed: false

Summary In this chapter, you have learned about:

• 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

• By import packagename. classname


• By fully qualified name
• Subpackage
• The way of Sending class to another file
• Package class

MCQ’s Practice: Multiple Choice Question’s

1. State whether the following statements C) iii only


about the advantages of organizing classes into D) None of the above
packages are True or False.
i) Two classes in two different packages cannot 5. A package is a collection of
have the same name. A) Classes
ii) The classes contained in the packages of B) interfaces
other programs can be easily reused. C) editing tools
A) True, False D) classes and interfaces
B) False, True
C) True, True 6 Which of the following classes in Java.io
D) False, False package defines a method to delete a file.
A)Stack
2. …………………. package in java contents B)File
language utility classes such as vectors, hash C)String
tables, random numbers date etc. D) Vector
A) java. util
B) java. Awt 7. Which keyword is used to declare an
C) java.net interface in java?
D) java. Lang A) class
B) interface
3. State whether the following statements are C) implements
True or False. D) abstract
i) When present, package must be the first
non-comment statement in the file. 8. A java interface can contain ————
ii) When we implement an interface method, it A) public static Final Variables only
should be declared as public. B) public Abstract methods
A) True, False C) Abstract methods(unimplemented) and
B) False, True implemented methods both
C) True, True D) public static Final Variables and abstract
D) False, False methods both

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

D) None is correct B) We can define a method in an interface


C) Private and protected access modifiers can
10. which of the following is true about also be used to declare methods in interface
methods in an interface in java? D) None
A) An interface can contain only abstract
method.

Fill in the blank’s

1. A ----------is a group of similar types of classes, interfaces and sub-packages.


2. ---------------access specifies can be used for an interface
3. The Date class includes within ………………….. Package.
4. An …………………. is an incomplete class that requires further specification.
5. A class can be declared as ………………………. if you do not want the class to be sub-classed.
6. If a class that implements an interface does not implement all the methods of the interface,
then the class becomes a/an …………………….. Class.



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

6.1 Java Array


Normally, an array is a collection of similar type of elements that have a contiguous memory location.
Java array is an object which contains elements of a similar data type.

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.

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

Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To solve
this problem, collection framework is used in Java which grows automatically.

6.2 Types of Array in java


There are two types of array.

Single Dimensional Array


Multidimensional Array

1) Single Dimensional Array in Java


Syntax to Declare an Array in Java

dataType[] arr; (or)


dataType []arr; (or)
dataType arr[];

Instantiation of an Array in Java

arrayRefVar=new datatype[size];

Assignment No: 30

Example of Java Array


Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse an
array.

//Java Program to illustrate how to declare, instantiate, initialize

WWW.ICIT.IN 51
JAVA PROGRAMMING

//and traverse the Java array.


class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output
10
20
70
40
50

Declaration, Instantiation and Initialization of Java Array


We can declare, instantiate and initialize the java array together by:

int a[]={33,3,4,5};//declaration, instantiation and initialization

Assignment No: 31

Let's see the simple example to print this array.

//Java Program to illustrate the use of declaration, instantiation


//and initialization of Java array in a single line
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:
33
3
4
5

WWW.ICIT.IN 52
JAVA PROGRAMMING

Multidimensional Array in Java


In such case, data is stored in row and column-based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java

dataType[][] arrayRefVar; (or)


dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java

int [][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in Java

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.

//Java Program to illustrate the use of multidimensional array


class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
Output:
123
245
445

WWW.ICIT.IN 53
JAVA PROGRAMMING

2) Jagged Array in Java

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

//Java Program to illustrate the jagged array

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++;

//printing the data of a jagged array


for (int i=0; i<arr.length; i++){
for (int j=0; j<arr[i].length; j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();//new line
}
}
}
Output:
012345678

6.3 Java String


In Java, string is basically an object that represents sequence of char values. An array of characters works same as
Java string. For example:

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.

6.4 Char Sequence Interface


The CharSequence interface is used to represent the sequence of characters. String, StringBuffer and StringBuilder
classes implement it. It means, we can create strings in java by using these three classes.

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.

1) What is String in java?

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.

2) How to create a string object?

There are two ways to create String object:

By string literal

Java String literal is created by using double quotes. For Example:

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";

String s2="Welcome";//It doesn't create a new instance

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

3) Why Java uses the concept of String literal?

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

public class StringExample{


public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Output
java
strings
example

WWW.ICIT.IN 56
JAVA PROGRAMMING

6.5 Java String class methods

The java.lang.String class provides many useful methods to perform operations on sequence of char values.

No. Method Description


1 char charAt(int index) returns char value for the particular index
2 int length() returns string length
3 static String format(String format, Object... returns a formatted string.
args)
4 static String format(Locale l, String format, returns formatted string with given locale.
Object... args)
5 String substring(int beginIndex) returns substring for given begin index.
6 String substring(int beginIndex, int endIndex) returns substring for given begin index and end
index.
7 boolean contains(CharSequence s) returns true or false after matching the sequence
of char value.
8 static String join(CharSequence delimiter, returns a joined string.
CharSequence... elements)
9 static String join(CharSequence delimiter, returns a joined string.
Iterable<? extends CharSequence> elements)
10 boolean equals(Object another) checks the equality of string with the given object.

Summary In this chapter, you have learned about:

• What is Array in java


• Advantage and Disadvantage
• Example on Declaration and initialization of array
• Example on single Dimensional Array
• Declaration, instantiation and initialization of java array
• Example on Two-Dimensional Array
• What is jagged Array
• Example on how to implement jagged Array
• Java String
• How to create String
• Example on creation of string
• Java string class methods

WWW.ICIT.IN 57
JAVA PROGRAMMING

Summary In this chapter, you have learned about:

1. Which of these operators is used to allocate array_variable[i] = i;


memory to array variable in Java? System.out.print(array_variable[i] + "
a) malloc ");
b) alloc i++;
c) new }
d) new malloc }
}
2. Which of these is an incorrect array a) 0 2 4 6 8
declaration? b) 1 3 5 7 9
a) int arr[] = new int[5]. c) 0 1 2 3 4 5 6 7 8 9
b) int [] arr = new int[5]. d) 1 2 3 4 5 6 7 8 9 10
c) int arr[] = new int[5].
d) int arr[] = int [5] new 7.Which of these class is superclass of String
and StringBuffer class?
3. What will this code print?
java.util
int arr[] = new int [5];
System.out.print(arr);
java.lang
a)0 ArrayList
b)arr[0] None of the mentioned
c)00000
d) Class name@ hashcode in hexadecimal form 8. Which of these operators can be used to
4. Which of these is an incorrect Statement? concatenate two or more String objects?
a) It is necessary to use new operator to initialize +
an array +=
b) Array can be initialized using comma separated &
expressions surrounded by curly braces ||
c) Array can be initialized when they are declared
d) None of the mentioned
9.Which of these method of class String is used
5. Which of these is necessary to specify at time to obtain length of String object?
of array initialization? get()
a) Row Sizeof()
b) Column lengthof()
c) Both Row and Column length()
d) None of the mentioned

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

Fill in the blank

1. In Java all arrays are -------------------allocated.


2. The elements in the array allocated by new will automatically be initialized to ----------------------
3. String objects are stored in a special memory area known as the---------------
4. ----------------is an object which contains elements of a similar data type.
5. Strings are usually ASCII characters terminated with a ---------character.
6. Java String Array is an object that holds a fixed number of -----------values.



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

7.1 What is Thread in Java?

A thread is a lightweight sub process, the smallest unit of processing.

It is a separate path of execution


Threads are independent.
If there occurs exception in one thread, it doesn't affect other threads.
It uses a shared memory area.

As shown in the above figure, a thread is executed inside the process.


There is context-switching between the threads. There can be multiple processes inside the OS, and one
process can have multiple threads.

Note: At a time one thread is executed only.

7.2 Java Thread class

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.

7.3 Java Thread Methods

S.N. Modifier and Type Method Description

1) void start() It is used to start the execution of the thread.


2) void run() It is used to do an action for a thread.
3) static void sleep() It sleeps a thread for the specified amount of time.
4) static Thread currentThread() It returns a reference to the currently executing
thread object.
5) void join() It waits for a thread to die.
6) int getPriority() It returns the priority of the thread.
7) void setPriority() It changes the priority of the thread.
8) String getName() It returns the name of the thread.
9) void setName() It changes the name of the thread.
10) long getId() It returns the id of the thread.
11) boolean isAlive() It tests if the thread is alive.
12) static void yield() It causes the currently executing thread object to
pause and allow other threads to execute
temporarily.

WWW.ICIT.IN 61
JAVA PROGRAMMING

13) void suspend() It is used to suspend the thread.


14) void resume() It is used to resume the suspended thread.
15) void stop() It is used to stop the thread.
16) void destroy() It is used to destroy the thread group and all of its
subgroups.
17) boolean isDaemon() It tests if the thread is a daemon thread.
18) void setDaemon() It marks the thread as daemon or user thread.
19) void interrupt() It interrupts the thread.
20) boolean isinterrupted() It tests whether the thread has been interrupted.

7.4 Multithreading in Java


Multithreading in java is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are
used to achieve multitasking.

Advantages of Java Multithreading


1) It doesn't block the user because threads are independent and you can perform multiple operations at the
same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.

7.5 Life cycle of a Thread


A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in java new,
runnable, non-runnable and terminated. There is no running state.

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

The thread is in new state if you create an instance of Thread


class but before the invocation of start() method.

Runnable

The thread is in runnable state after invocation of start()


method, but the thread scheduler has not selected it to be the
running thread.

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

A thread is in terminated or dead state when its run() method exits.

7.6 How to create thread


There are two ways to create a thread:

By extending Thread class


By implementing Runnable interface.

Assignment No 35

1) Java Thread Example by extending Thread class

class Multi extends Thread{


public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Output
thread is running...

2) Java Thread Example by implementing Runnable interface

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.

Why use Synchronization


The synchronization is mainly used to

To prevent thread interference.


To prevent consistency problem.

Assignment No.37

//example of java synchronized method


class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread {
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}

WWW.ICIT.IN 64
JAVA PROGRAMMING

public class TestSynchronization3{


public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2. start();
}
}
Output
5
10
15
20
25
100
200
300
400
500

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.

1) System.out: standard output stream


2) System.in: standard input stream
3) System.err: standard error stream

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

Java FileOutputStream Example 1: write byte


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);}
}
}

Output
Success...

WWW.ICIT.IN 66
JAVA PROGRAMMING

Java FileOutputStream Example 2: write string


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 Java.”;
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);}
}
}
Output
Success...
The content of a text file testout.txt is set with the data Welcome to java.
testout.txt
Welcome to Java.

Summary In this chapter, you have learned about:

• 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
• Example on how to create thread in java
• Synchronization in java
• Example in java using synchronization method
• Types of Synchronization
• Example on synchronization methods
• Stream in java
• Stream classes
• Example on input stream and output stream

WWW.ICIT.IN 67
JAVA PROGRAMMING

MCQ’s Practice: Unsolved Multiple Choice Question’s

1. What is multithreaded programming? 6. Which of these method of FileReader class is


a) It’s a process in which two different processes used to read characters from a file?
run simultaneously a) read()
b) It’s a process in which two or more parts of b) scanf()
same process run simultaneously c) get()
c) It’s a process in which many different process d) getInteger()
are able to access same information
7. Which of these class can be used to implement
d) It’s a process in which a single process can
the input stream that uses a character array as
access information from many sources
the source?
2. Which of these are types of multitasking? a) Buffered Reader
a) Process based b) FileReader
b) Thread based c) CharArrayReader
c) Process and Thread based d) FileArrayReader
d) None of the mentioned
8. Which of these classes can return more than
3. Thread priority in Java is? one character to be returned to input stream?
a) Integer a) Buffered Reader
b) Float b) Buffered writer
c) double c) PushbachReader
d) long d) CharArrayReader

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

Fill in the blank

1. The ---------------------contains two classes --------------and --------------------.


2. A --------------- is actually a lightweight process.
3. Java Thread by Implementing ---------------
4. Java application uses an --------------- to read data from a source
5. --------------In java is the capability to control the access of multiple threads to any ----------------- resource.

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

8.1 Exception Handling in Java


The Exception Handling in Java is one of the powerful mechanisms to
handle the runtime errors so that normal flow of the application can
be maintained.

What is Exception in Java?


In Java, an exception is an event that disrupts the normal flow of the
program. It is an object which is thrown at runtime.

Exception Handling is a mechanism to handle runtime errors such as


ClassNotFoundException, IOException, SQLException,
RemoteException, etc.

Hierarchy of Java Exception classes


The java. lang. Throwable class is the root class of Java Exception hierarchy which is inherited by two subclasses:
Exception and Error.

A hierarchy of Java Exception classes is given below:

Types of Java Exceptions

Difference between Checked and Unchecked Exceptions


1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are known as checked
exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at compile-time.

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.

Java Exception Keywords


There are 5 keywords which are used in handling exceptions in Java.

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.

Java Exception Handling Example

Assignment No: 39

public class JavaException {


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

WWW.ICIT.IN 71
JAVA PROGRAMMING

8.2 Try Catch Block

Java provides an inbuilt exceptional handling.


• The normal code goes into a TRY block.
• The exception handling code goes into the CATCH block

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.

Syntax for using try & catch


try {
statement(s)
}
catch (exceptiontype name){
statement(s)
}

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

8.3 The Finally Block

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 (ExceptionType1 e1) {

// Catch block

} catch (ExceptionType2 e2) {

// Catch block

} catch (ExceptionType3 e3) {

// Catch block

} finally {

// The finally block always executes.

Assignment No: 41

public class JavaException {


public static void main(String args[]) {
int a[] = new int[2];
try {
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}finally {
a[0] = 6;

WWW.ICIT.IN 73
JAVA PROGRAMMING

System.out.println("First element value: " + a[0]);


System.out.println("The finally statement is executed");
}
}
}
Output
Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed

Summary In this chapter, you have learned about:

• What is Exception Handling


• Advantages of Exception Handling
• Hierarchy of Exception classes
• Types of Exception
• Example on how Exception is occurred
• Try-catch block
• Example on how try-catch block is used
• Finally block
• Example on How finally keyword is used

MCQ’s Practice: Unsolved Multiple Choice Question’s

1. When does Exceptions in Java arises in code c) throw


sequence? d) catch
a) Run Time
4. Which of these keywords must be used to
b) Compilation Time
handle the exception thrown by try block in
c) Can Occur Any Time
some rational manner?
d) None of the mentioned
a) try
2. Which of these keywords is not a part of b) finally
exception handling? c) throw
a) try d) catch
b) finally
5. Which of these keywords is used to manually
c) thrown
throw an exception?
d) catch
a) try
3. Which of these keywords must be used to b) finally
monitor for exceptions? c) throw
a) try d) catch
b) finally
6.What is the output of this program?

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

Fill in the blank

1. Exception Handling is a mechanism to handle ----------------such as ClassNotFoundException, IOException,


SQLException, RemoteException, etc.
2. The -------------Throwable class is the root class of Java Exception hierarchy
3. Java ------- block is used to enclose the code that might throw an exception.
4. Java ------------- block is used to handle the Exception by declaring the type of exception within the parameter.
5. In Java, an ---------is an event that disrupts the normal flow of the program.


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.1 Collections in Java


The Collection in Java is a framework that provides architecture to store and manipulate the group of objects
Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion,
manipulation and deletion.
Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set, List,
Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

9.3 What is Collection in Java


A Collection represents a single unit of objects, i.e., a group.

What is Collection Framework?


The Collection framework represents a unified architecture for storing and manipulating a group of objects. It has:
Interfaces and its implementations, i.e., classes
Algorithm

Hierarchy of Collection Framework


The java.util package contains all the classes and interfaces for the Collection framework.

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();

// Add elements to the tree set


ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");
System.out.println(ts);
}
}
Output
[A, B, C, D, E, F]

WWW.ICIT.IN 81
JAVA PROGRAMMING

9.9 Hash Map

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

Summary In this chapter, you have learned about:

• Java Collection Framework


• Hierarchy of collection Framework
• Collection Interface
• Array List
• Example on how to Array List is used
• Linked List
• Example on how Linked List is used
• Stack
• Example on how stack is used
• Hash Set
• Example on how hash set is used
• Tree Set
• Example on how Tree Set is used
• Hash Map
• Example on how mapping is done in collection

MCQ’s Practice: Unsolved Multiple Choice Question’s

1. Which of these packages contain all the c) delete()


collection classes? d) refresh()
a) java. Lang
5. What is Collection in Java?
b) java. util
a) A group of objects
c) java.net
b) A group of classes
d) java. Awt
c) A group of interfaces
2. Which of these classes is not part of Java’s d) None of the mentioned
collection framework?
6. What is the output of this program?
a) Maps
b) Array import java.util.*;
c) Stack class Array
d) Queue {
public static void main(String args[])
3. Which of this interface is not a part of Java’s
{
collection framework?
int array[] = new int [5];
a) List
for (int i = 5; i > 0; i--)
b) Set
array[5-i] = i;
c) SortedMap
Arrays.fill(array, 1, 4, 8);
d) SortedList
for (int i = 0; i < 5 ; i++)
4. Which of these methods deletes all the elements System.out.print(array[i]);
from invoking collection? }
a) clear() }
b) reset() a) 12885
b) 12845

WWW.ICIT.IN 83
JAVA PROGRAMMING

c) 58881 8. Which of these return type of hasNext() method


d) 5488 of an iterator?
7. What is the output of this program? a) Integer
b) Double
import java.util.*;
c) Boolean
class Bitset
d) Collections Object
{
public static void main(String args[]) 9. Which of these methods is used to obtain an
{ iterator to the start of collection?
BitSet obj = new BitSet(5); a) start()
for (int i = 0; i < 5; ++i) b) begin()
obj.set(i); c) iteratorSet()
obj.clear(2); d) iterator()
System.out.print(obj);
10. Which of these methods can be used to move to
}
next element in a collection?
}
a) next()
a) {0, 1, 3, 4}
b) move()
b) {0, 1, 2, 4}
c) shuffle()
c) {0, 1, 2, 3, 4}
d) hasNext()
d) {0, 0, 0, 3, 4}

Fill in the blank

1. The ------------- in Java is a framework that provides architecture to store and manipulate the group of
objects.

2. A Collection represents -----of objects

3. The ------------package contains all the classes and interfaces for the Collection framework.

4. The -----------class implements the List interface.

5. HashSet class implements ------------- Interface.



WWW.ICIT.IN 84

You might also like