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

java lab manual

The document is a laboratory manual for the Java Programming Lab at Methodist College of Engineering and Technology, outlining the course objectives, outcomes, and specific experiments for students in the Computer Science and Engineering department. It emphasizes the importance of ethical and innovative education, aiming to produce socially responsible professionals. Additionally, it includes guidelines for laboratory conduct and a brief history and features of the Java programming language.
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)
2 views

java lab manual

The document is a laboratory manual for the Java Programming Lab at Methodist College of Engineering and Technology, outlining the course objectives, outcomes, and specific experiments for students in the Computer Science and Engineering department. It emphasizes the importance of ethical and innovative education, aiming to produce socially responsible professionals. Additionally, it includes guidelines for laboratory conduct and a brief history and features of the Java programming language.
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/ 100

METHODIST

COLLEGE OF ENGINEERING AND TECHNOLOGY


Estd:2008

(Affiliated to Osmania University & Approved by AICTE, New Delhi)

LABORATORY MANUAL JAVA PROGRAMMING LAB


BE IV Semester (AICTE Model Curriculum): 2022-23

NAME: _____K.KEERTHI________________________________________

ROLLNO:______________________________________________________

BRANCH:______AI&DS______ SEM:_____IV____________________________

DEPARTMENT OF COMPUTER SCIENCE &ENGINEERNG

Empower youth- Architects of Future World


METHODIST

COLLEGE OF ENGINEERING AND TECHNOLOGY


Estd:2008

VISION

To produce ethical, socially conscious and innovative professionals who would


contribute to sustainable technological development of the society.

MISSION

To impart quality engineering education with latest technological developments and


interdisciplinary skills to make students succeed in professional practice.

To encourage research culture among faculty and students by establishing state of art
laboratories and exposing them to modern industrial and organizational practices.

To inculcate humane qualities like environmental consciousness, leadership, social


values, professional ethics and engage in independent and lifelong learning for sustainable
contribution to the society.
METHODIST

COLLEGE OF ENGINEERING AND TECHNOLOGY


Estd:2008

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LABORATORY MANUAL

JAVA PROGRAMMING LAB

PreparedBy
Mrs K KEERTHI
AssistantProfessor.
METHODIST
Estd:2008 COLLEGE OF ENGINEERING AND

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VISION & MISSION

VISION

To become a leader in providing Computer Science & Engineeringeducation with


emphasis on knowledge and innovation.

MISSION

 To offer flexible programs of study with collaborations to suit industryneeds.


 To provide quality education and training through novel pedagogicalpractices.
 To expedite high performance of excellence in teaching, research andinnovations.
 To impart moral, ethical values and education with social responsibility.
METHODIST
Estd:2008 COLLEGE OF ENGINEERING AND

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

PROGRAM EDUCATIONAL OBJECTIVES

After 3-5 years of graduation, the graduates will be able to

PEO1: Apply technical concepts, Analyze, Synthesize data to Design and create novel
products and solutions for the real life problems.

PEO2: Apply the knowledge of Computer Science Engineering to pursue higher education
with due consideration to environment and society.

PEO3: Promote collaborative learning and spirit of team work through multidisciplinary
projects

PEO4: Engage in life-long learning and develop entrepreneurial skills.


METHODIST

COLLEGE OF ENGINEERING AND TECHNOLOGY


Estd:2008

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

PROGRAM OUTCOMES

Engineering graduates will be able to:

PO1: Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.

PO2: Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.

PO3: Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.

PO4: Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis
of the information to provide valid conclusions.

PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modelling to complex engineering
activities with an understanding of the limitations.

PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant
to the professional engineering practice.

PO7: Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.

PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.

PO9: Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.

PO10: Communication: Communicate effectively on complex engineering activities with the


Engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give and
receive clear instructions.
PO11: Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multidisciplinary environments.

PO12: Life-long learning: Recognize the need for, and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change.

PROGRAM SPECIFIC OUTCOMES

At the end of 4 years, Computer Science and Engineering graduates at MCET will beable to:

PSO1: Apply the knowledge of Computer Science and Engineering in various domains like
networking and data mining to manage projects in multidisciplinary environments.

PSO2: Develop software applications with open-ended programming environments.

PSO3: Design and develop solutions by following standard software engineering principles and
implement by using suitable programming languages and platforms
JAVA PROGRAMMING LAB

Semester – IV L T P Credits

Subject code - 1PC456 AD 0 0 4 2

Prerequisite: Programming inC

Course Objectives: Course Outcomes:

 To implement various java concepts. 1. To understand the use of OOPs concepts.


 To write java programs to solve 2. Develop Java program using packages,
mathematics, science and engineering inheritance and interface.
problems. 3. Develop java programs to implement error
 To identify compile time and runtime handling techniques using exception
errors, syntax and logical errors handling.
 To import the essentials of java class 4. Develop graphical user interface using
library and user defined packages. AWT.
 To develop skills in internet 5. Demonstrate event handling mechanism
programming using applets and swings

List of Programs

1. Implement the concept of classes and objects.


2. Implement Arrays to a given application.
3. Use String and String Tokenizer classes and develop a java programs.
4. Develop a java programs Using interfaces and packages.
5. Develop Java Programs using inheritance.
6. Develop Java programs using Method overloading and method overriding.
7. Develop java programs using Exception handling (using try, catch, throw, throws and
finally).
8. Develop java programs using Multithreading (using Thread class and Runnable
interface, synchronization).
9. Develop java programs using collections (using list, set, Map and generics).
10. CASE STUDY: Develop a program to calculate SGPA & CGPA of a student and
display the progress report.
INPUT:
INPUT

HOW MANY SEMESTERS?


ROLL NO NAME
Semester wise : Subject Code, Subject
Name And Marks
OUTPUT:
Progress report of

<NAME>Roll No:
Program(BE/ME)
Branch:
College Code and Name:
Year of joining:
Semester-I Grades Semester-II Grades Semester-III Grades
Subject 1: Subject 1: Subject 1:
Subject 2: Subject 2: Subject 2:
Subject 3: Subject 3: Subject 3:
…. …. ….
SGPA : SGPA : SGPA :
CGPA : CGPA : CGPA :

Note: The above experiments can be implemented using any IDE.


METHODIST

COLLEGE OF ENGINEERING AND TECHNOLOGY


Estd:2008

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Course Outcomes (CO’s):

SUBJECT NAME: JAVA PROGRAMMING LAB CODE: 3PC458 CS


SEMESTER: IV

CO No. Course Outcomes Taxonomy


Level
To understand the concept of Object Oriented
1PC456 AD.1 Understand
Programming Systems and use arrays, string Tokenizer.

1PC456 AD.2 To apply OOPs concepts on packages, inheritance and Apply


interface.

1PC456 AD.3 To implement java programs for exception handling and Apply
error free code.
1PC456 AD.4 To analyze java programs on Method Overloading and Analyze
Method Overriding.
To implement java programs for multithreading and java
1PC456 AD.5 Apply
collection framework.
To understand the concept of Object Oriented
1PC456 AD.1 Understand
Programming Systems and use arrays, string Tokenizer.
METHODIST
Estd:2008 COLLEGE OF ENGINEERING AND
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

GENERAL LABORATORY INSTRUCTIONS

1. Students are advised to come to the laboratory at least 5 minutes before (to
starting time), those who come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to the
lab with the program / experiment details.
3. Student should enter into the laboratory with:

a. Laboratory observation notes with all the details (Problem statement, Aim,
Algorithm, Procedure, Program, Expected Output, etc.,) filled in for the lab
session.
b. Laboratory Record updated up to the last session experiments.
c. Formal dress code and Identity card.

4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer
system allotted to you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab
observation note book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must
maintain the discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems,
which should be utilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during
the lab sessions. Misuse of the equipment, misbehaviours with the staff and systems
etc., will attract severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go out. If
anybody found loitering outside the lab / class without permission during working
hours will be treated seriously and punished appropriately.
10. Students should SHUT DOWN the computer system before he/she leaves the lab after
completing the task (experiment) in all aspects. He/she must ensure the system / seat is
kept properly.

Head of the Department Principal


METHODIST
Estd:2008 COLLEGE OF ENGINEERING AND
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CODE OF CONDUCT FOR THE LABORATORY

 All students must observe the dress code while in the laboratory
 Footwear is NOT allowed
 Foods, drinks and smoking are NOT allowed
 All bags must be left at the indicated place
 The lab timetable must be strictly followed
 Be PUNCTUAL for your laboratory session
 All programs must be completed within the given time
 Noise must be kept to a minimum
 Workspace must be kept clean and tidy at all time
 All students are liable for any damage to system due to their own negligence
 Students are strictly PROHIBITED from taking out any items from the laboratory
 Report immediately to the lab programmer if any damages to equipment

BEFORE LEAVING LAB:

 Arrange all the equipment and chairs properly.


 Turn off / shut down the systems before leaving.
 Please check the laboratory notice board regularly for updates.

Lab In – charge
METHODIST

COLLEGE OF ENGINEERING AND TECHNOLOGY


Estd:2008

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LIST OF EXPERIMENTS

Date of Date of Page Faculty


SI.No. Name of the Experiment
Experiment Submission No Signature
1. Implement the concept of classes
and objects.

2. Implement Arrays to a given


application.

3. Use String and String Tokenizer


classes and develop a java
programs.

4. Develop a java programs Using


interfaces and packages.

5. Develop Java Programs using


inheritance.

6. Develop Java programs using


Method overloading and method
overriding.

7. Develop java
programs using
Exception handling
(using try, catch,
throw, throws and
finally).

8. Develop java
programs using
Multithreading
(using Thread
class and
Runnable
interface,
synchronization
).

9. Develop java programs using


collections (using list, set, Map
and generics).

10 CASE STUDY:
Develop a
program to
calculate SGPA &
CGPA of a
student and
display the
progress report.
ADDITIONAL EXPERIMENTS

Date of Date of Page Faculty


SI.No. Name of the Experiment
Experiment Submission No Signature
1. “this” and “super” keyword usage
Introduction to Java Programming Language

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

Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. James
Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak was already a registered
company, so James Gosling and his team changed the name from Oak to Java.

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.

Java Example

Let's have a quick look at Java programming example. A detailed description of Hello Java example is available in
next page.

Simple.java

class Simple{
public static void main(String args[]){
System.out.println("Hello Java"); }
}
History of Java

The history of Java is very interesting. Java was originally designed for interactive television, but it was too
advanced technology for the digital cable television industry at the time. The history of Java starts with the Green
Team. Java team members (also known as Green Team), initiated this project to develop a language for digital
devices such as set-top boxes, televisions, etc. However, it was best suited for internet programming. Later, Java
technology was incorporated by Netscape.

The principles for creating Java programming were "Simple, Robust, Portable, Platform-independent, Secured,
High Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted, and Dynamic". Java was
developed by James Gosling, who is known as the father of Java, in 1995. James Gosling and his team members
started the project in the early '90s.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc. Following are
given significant points that describe the history of Java.

1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. The
small team of sun engineers called Green Team.

Features of Java

The primary objective of Java programming language creation was to make it portable, simple and secure
programming language. Apart from this, there are also some excellent features which play an important role in the
popularity of this language. The features of Java are also known as Java buzzwords.

A list of the most important features of the Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic

Java Example

Let's have a quick look at Java programming example. A detailed description of Hello Java example is available in
next page.

Simple.java

1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }
Test it Now

Application

According to Sun, 3 billion devices run Java. There are many devices where Java is currently used. Some of them
are as follows:

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


2. Web Applications such as irctc.co.in, javatpoint.com, etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. 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 an enterprise application. It
has advantages like 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.

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 that is mainly used to develop web and enterprise applications. It is built on 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 that is dedicated to mobile applications.

4) JavaFX

It is used to develop rich internet applications. It uses a lightweight user interface API

Java OOPs Concepts

In this page, we will learn about the basics of OOPs. Object-Oriented Programming is a paradigm that provides
many concepts, such as inheritance, data binding, polymorphism, etc.

Simula is considered the first object-oriented programming language. The programming paradigm where
everything is represented as an object is known as a truly object-oriented programming language.

Smalltalk is considered the first truly object-oriented programming language.

The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.

The main aim of object-oriented programming is to implement real-world entities, for example, object, classes,
abstraction, inheritance, polymorphism, etc.

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 software
development and maintenance by providing some concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Apart from these concepts, there are some other terms which are used in Object-Oriented design:
o Coupling
o Cohesion
o Association
o Aggregation
o Composition

Object

Any entity that has state and behavior is known as an object. For example, a chair, pen, table, keyboard, bike, etc.
It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes up some space in
memory. Objects can communicate without knowing the details of each other's data or code. The only necessary
thing is the type of message accepted and the type of response returned by the objects.

Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors like wagging
the tail, barking, eating, etc.

Class

Collection of objects is called class. It is a logical entity.

A class can also be defined as a blueprint from which you can create an individual object. Class doesn't consume
any space.

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.

Polymorphism

If one task is performed in 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.

Abstraction

Hiding internal details and showing functionality is known as abstraction. For example phone call, we don't know
the internal processing.

In Java, we use abstract class and interface to achieve abstraction.


Encapsulation

Binding (or wrapping) code and data together into a single unit are known as encapsulation. For example, a
capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data
members are private here.

Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent
object. It is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When
you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add
new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created.
o 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.
o 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.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and
methods of the existing class when you create a new class. You can use the same fields and methods
already defined in the previous class.

The syntax of Java Inheritance


1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }

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.
PROGRAMS:

1.Aim: Implement the concept of classes and objects.


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.

A class in Java can contain:

o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

Syntax to declare a class:


1. class <class_name>{
2. field;
3. method;
4. }

Object and Class Example: main within the class


In this example, we have created a Student class which has two data members id and name. We are creating the object of
the Student class by new keyword and printing the object's value.

Here, we are creating a main() method inside the class.

1. //Java Program to illustrate how to define a class and fields


2. //Defining a Student class.
3. class Student{
4. //defining fields
5. int id;//field or data member or instance variable
6. String name;
7. //creating main method inside the Student class
8. public static void main(String args[]){
9. //Creating an object or instance
10. Student s1=new Student();//creating an object of Student
11. //Printing values of the object
12. System.out.println(s1.id);//accessing member through reference variable
13. System.out.println(s1.name);
14. }
15. }

Output:

0
null

Object and Class Example: main outside the class


In real time development, we create classes and use it from another class. It is a better approach than previous one. Let's
see a simple example, where we are having main() method in another class.

We can have multiple classes in different Java files or single Java file. If you define multiple classes in a single Java source
file, it is a good idea to save the file name with the class name which has main() method.

1. //Java Program to demonstrate having the main method in


2. //another class
3. //Creating Student class.
4. class Student{
5. int id;
6. String name;
7. }
8. //Creating another class TestStudent1 which contains the main method
9. class TestStudent1{
10. public static void main(String args[]){
11. Student s1=new Student();
12. System.out.println(s1.id);
13. System.out.println(s1.name);
14. }
15. }

Output:

0
null

2.Aim: Implement Arrays to a given application.


Java Arrays

Normally, an array is a collection of similar type of elements which has contiguous memory location.

Java array is an object which contains elements of a similar data type. Additionally, The elements of an array are
stored in a contiguous memory location. 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 0th index, 2nd element is stored on 1st
index and so on.

Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the sizeof
operator.

In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and implements
the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an array in Java. Like
C/C++, we can also create single dimentional or multidimentional arrays in Java.

Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
o Random access: We can get any data located at an index position.

Disadvantages
o 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.

Types of Array in java

There are two types of array.

o Single Dimensional Array


o Multidimensional Array

Single Dimensional Array in Java

Syntax to Declare an Array in Java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];

Instantiation of an Array in Java

1. arrayRefVar=new datatype[size];

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.

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


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

Output:

10
20
70
40
50

Example of Multidimensional Java Array

Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.

1. //Java Program to illustrate the use of multidimensional array


2. class Testarray3{
3. public static void main(String args[]){
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6. //printing 2D array
7. for(int i=0;i<3;i++){
8. for(int j=0;j<3;j++){
9. System.out.print(arr[i][j]+" ");
10. }
11. System.out.println();
12. }
13. }}

Output:

123
245
445
3.Aim: Use String and String Tokenizer classes and develop a java programs
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:

1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);

is same as:
1. String s="javatpoint";

Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(),
split(), length(), replace(), compareTo(), intern(), substring() etc.

Java String Example

StringExample.java

1. public class StringExample{


2. public static void main(String args[]){
3. String s1="java";//creating string by Java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating Java string by new keyword
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10. }}

Output:

java
strings
example
StringTokenizer in Java

The java.util.StringTokenizer class allows you to break a String into tokens. It is simple way to break a String. It
is a legacy class of Java.

It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like StreamTokenizer class.
We will discuss about the StreamTokenizer class in I/O chapter.

In the StringTokenizer class, the delimiters can be provided at the time of creation or one by one to the tokens.
Constructors of the StringTokenizer Class

There are 3 constructors defined in the StringTokenizer class.

deConstructor Description

kenizer(String str) It creates StringTokenizer with specified string.

kenizer(String str, String It creates StringTokenizer with specified string and delimiter.

kenizer(String str, String It creates StringTokenizer with specified string, delimiter and returnValue. If
olean returnValue) return value is true, delimiter characters are considered to be tokens. If it is
false, delimiter characters serve to separate tokens.

Methods of the StringTokenizer Class

The six useful methods of the StringTokenizer class are as follows:


Methods Description

boolean hasMoreTokens() It checks if there is more tokens available.

String nextToken() It returns the next token from the StringTokenizer object.

String nextToken(String delim) It returns the next token based on the delimiter.

boolean hasMoreElements() It is the same as hasMoreTokens() method.

Object nextElement() It is the same as nextToken() but its return type is Object.

int countTokens() It returns the total number of tokens.

Example of StringTokenizer Class

Let's see an example of the StringTokenizer class that tokenizes a string "my name is khan" on the basis of
whitespace.

Simple.java

1. import java.util.StringTokenizer;
2. public class Simple{
3. public static void main(String args[]){
4. StringTokenizer st = new StringTokenizer("my name is khan"," ");
5. while (st.hasMoreTokens()) {
6. System.out.println(st.nextToken());
7. }
8. }
9. }

Output:

my
name
is
khan
4.Aim: Develop a java programs Using interfaces and packages.
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 inheritance 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.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.
How to declare an interface?

An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an
interface are declared with the empty body, and all the fields are public, static and final by default. A class that
implements an interface must implement all the methods declared in the interface.

Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }
Java Interface Example

In this example, the Printable interface has only one method, and its implementation is provided in the A6 class.

1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }

Output:
Hello

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.

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.

Simple example of java package

The package keyword is used to create a package in java.

1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

1. javac -d directory javafilename

For example

1. javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file. You can use any directory name like
/home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package within the same
directory, you can use . (dot).

How to run java package program

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java


To Run: java mypack.Simple
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents the
current folder.

How to access package from another package?

There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. 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.*

1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello

2) Using packagename.classname

If you import package.classname then only declared class of this package will be accessible.

Example of package by import package.classname

1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2. package mypack;
3. import pack.A;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
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

1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A();//using fully qualified name
6. obj.msg();
7. }
8. }
Output:Hello

5.Aim: Develop Java Programs using inheritance.


Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent
object. It is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When
you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add
new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created.
o 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.
o 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.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and
methods of the existing class when you create a new class. You can use the same fields and methods
already defined in the previous class.

The syntax of Java Inheritance


5. class Subclass-name extends Superclass-name
6. {
7. //methods and fields
8. }
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.

Java Inheritance Example

As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship
between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.

1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
Programmer salary is:40000.0
Bonus of programmer is:10000
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. We will learn about
interfaces later.
Note: Multiple inheritance is not supported in Java through class.

When one class inherits multiple classes, it is known as multiple inheritance. For Example:

Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class
inherits the Animal class, so there is the single inheritance.
File: TestInheritance.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}

Output:

barking...
eating...

Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given
below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel
inheritance.

File: TestInheritance2.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}

Output:

weeping...
barking...
eating...
Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given
below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.

File: TestInheritance3.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}

Output:

meowing...
eating...
Q) Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes
have the same method and you call it from child class object, there will be ambiguity to call the method of A or B
class.

Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes.
So whether you have same method or different, there will be compile time error.

1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. public static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }
Compile Time Error
6.Aim: Develop Java programs using Method overloading and method overriding.
Method Overloading in Java

If a class has multiple methods having same name but different in parameters, it is known as Method
Overloading.

If we have to perform only one operation, having same name of the methods increases the readability of
the program.

Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you
write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be
difficult for you as well as other programmers to understand the behavior of the method because its name differs.

So, we perform method overloading to figure out the program quickly.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

In Java, Method Overloading is not possible by changing the return type of the method only.

1) Method Overloading: changing no. of arguments

In this example, we have created two methods, first add() method performs addition of two numbers and second
add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance for calling methods.

1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}
Test it Now
Output:

22
33

2) Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type. The first add method receives two integer
arguments and second add method receives two double arguments.

1. class Adder{
2. static int add(int a, int b){return a+b;}
3. static double add(double a, double b){return a+b;}
4. }
5. class TestOverloading2{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(12.3,12.6));
9. }}

Output:

22
24.9
Method Overriding in Java

If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in
Java.

In other words, If a subclass provides the specific implementation of the method that has been declared by one of
its parent class, it is known as method overriding.

Usage of Java Method Overriding


o Method overriding is used to provide the specific implementation of a method which is already provided
by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Example of method overriding

In this example, we have defined the run method in the subclass as defined in the parent class but it has some
specific implementation. The name and parameter of the method are the same, and there is IS-A relationship
between the classes, so there is method overriding.

1. //Java Program to illustrate the use of Java Method Overriding


2. //Creating a parent class.
3. class Vehicle{
4. //defining a method
5. void run(){System.out.println("Vehicle is running");}
6. }
7. //Creating a child class
8. class Bike2 extends Vehicle{
9. //defining the same method as in the parent class
10. void run(){System.out.println("Bike is running safely");}
11.
12. public static void main(String args[]){
13. Bike2 obj = new Bike2();//creating object
14. obj.run();//calling method
15. }
16. }

Output:

Bike is running safely


7.Aim: Develop java programs using Exception handling (using try, catch, throw, throws andfinally).

What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException,


SQLException, RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application. An exception
normally disrupts the normal flow of the application; that is why we need to handle exceptions. Let's consider a
scenario:

1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;

Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the rest of the code will
not be executed, i.e., statements 6 to 10 will not be executed. However, when we perform exception handling, the
rest of the statements will be executed. That is why we use exception handling in Java.

Hierarchy of Java Exception classes


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

Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked
exception. However, according to Oracle, there are three types of exceptions namely:

1. Checked Exception
2. Unchecked Exception
3. Error

1) Checked Exception

The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked
exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are
not checked at compile-time, but they are checked at runtime.
3) Error

Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError etc.

Java Exception Keywords

Keyword Description

try The "try" keyword is used to specify a block where we should place an exception code. It means we
can't use try block alone. The try block must be followed by either catch or finally.

catch The "catch" block is used to handle the exception. It must be preceded by try block which means we
can't use catch block alone. It can be followed by finally block later.

finally The "finally" block is used to execute the necessary code of the program. It is executed whether an
exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in
the method. It doesn't throw an exception. It is always used with method signature.
Java provides five keywords that are used to handle the exception. The following table describes each.

java Exception Handling Example

Let's see an example of Java Exception Handling in which we are using a try-catch statement to handle the
exception.

JavaExceptionExample.java

1. public class JavaExceptionExample{


2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}
7. //rest code of the program
8. System.out.println("rest of the code...");
9. }
10. }

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero


rest of the code...
Java throw Exception
In Java, exceptions allows us to write good quality codes where the errors are checked at the compile time instead
of runtime and we can create custom exceptions making the code recovery and debugging easier.

Java throw keyword

The Java throw keyword is used to throw an exception explicitly.

We specify the exception object which is to be thrown. The Exception has some message with it that provides the
error description. These exceptions may be related to user inputs, server, etc.

We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used to throw a
custom exception. We will discuss custom exceptions later in this section.

We can also define our own set of conditions and throw an exception explicitly using throw keyword. For
example, we can throw ArithmeticException if we divide a number by another number. Here, we just need to set
the condition and throw exception using throw keyword.

The syntax of the Java throw keyword is given below.

throw Instance i.e.,

1. throw new exception_class("error message");

Let's see the example of throw IOException.

1. throw new IOException("sorry device error");

Where the Instance must be of type Throwable or subclass of Throwable. For example, Exception is the sub class
of Throwable and the user-defined exceptions usually extend the Exception class.

Java throw keyword Example

Example 1: Throwing Unchecked Exception

In this example, we have created a method named validate() that accepts an integer as a parameter. If the age is
less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote.

TestThrow1.java

In this example, we have created the validate method that takes integer value as a parameter. If the age is less than
18, we are throwing the ArithmeticException otherwise print a message welcome to vote.

1. public class TestThrow1 {


2. //function to check if person is eligible to vote or not
3. public static void validate(int age) {
4. if(age<18) {
5. //throw Arithmetic exception if not eligible to vote
6. throw new ArithmeticException("Person is not eligible to vote");
7. }
8. else {
9. System.out.println("Person is eligible to vote!!");
10. }
11. }
12. //main method
13. public static void main(String args[]){
14. //calling the function
15. validate(13);
16. System.out.println("rest of the code...");
17. }
18. }

Output:

The above code throw an unchecked exception. Similarly, we can also throw unchecked and user defined
exceptions.

Java throws keyword

The Java throws keyword is used to declare an exception. It gives an information to the programmer that there
may occur an exception. So, it is better for the programmer to provide the exception handling code so that the
normal flow of the program can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception
such as NullPointerException, it is programmers' fault that he is not checking the code before it being used.

Syntax of Java throws


1. return_type method_name() throws exception_class_name{
2. //method code
3. }

Which exception should be declared?

Ans: Checked exception only, because:

o unchecked exception: under our control so we can correct our code.


o error: beyond our control. For example, we are unable to do anything if there occurs VirtualMachineError
or StackOverflowError.

Advantage of Java throws keyword

Now Checked Exception can be propagated (forwarded in call stack).

It provides information to the caller of the method about the exception.


Java throws Example

Let's see the example of Java throws clause which describes that checked exceptions can be propagated by throws
keyword.

Testthrows1.java

1. import java.io.IOException;
2. class Testthrows1{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{
7. m();
8. }
9. void p(){
10. try{
11. n();
12. }catch(Exception e){System.out.println("exception handled");}
13. }
14. public static void main(String args[]){
15. Testthrows1 obj=new Testthrows1();
16. obj.p();
17. System.out.println("normal flow...");
18. }
19. }

Output:

exception handled
normal flow...
Java finally block

Java finally block is a block used to execute important code such as closing the connection, etc.

Java finally block is always executed whether an exception is handled or not. Therefore, it contains all the
necessary statements that need to be printed regardless of the exception occurs or not.

The finally block follows the try-catch block.

Flowchart of finally block


Note: If you don't handle the exception, before terminating the program, JVM executes finally block (if any).
Why use Java finally block?
o finally block in Java can be used to put "cleanup" code such as closing a file, closing connection, etc.
o The important statements to be printed can be placed in the finally block.

Usage of Java finally

Let's see the different cases where Java finally block can be used.

Case 1: When an exception does not occur

Let's see the below example where the Java program does not throw any exception, and the finally block is
executed after the try block.

TestFinallyBlock.java

1. class TestFinallyBlock {
2. public static void main(String args[]){
3. try{
4. //below code do not throw any exception
5. int data=25/5;
6. System.out.println(data);
7. }
8. //catch won't be executed
9. catch(NullPointerException e){
10. System.out.println(e);
11. }
12. //executed regardless of exception occurred or not
13. finally {
14. System.out.println("finally block is always executed");
15. }
16.
17. System.out.println("rest of phe code...");
18. }
19. }

Output:

Case 2: When an exception occur but not handled by the catch block

Let's see the the fillowing example. Here, the code throws an exception however the catch block cannot handle it.
Despite this, the finally block is executed after the try block and then the program terminates abnormally.

TestFinallyBlock1.java

1. public class TestFinallyBlock1{


2. public static void main(String args[]){
3.
4. try {
5.
6. System.out.println("Inside the try block");
7.
8. //below code throws divide by zero exception
9. int data=25/0;
10. System.out.println(data);
11. }
12. //cannot handle Arithmetic type exception
13. //can only accept Null Pointer type exception
14. catch(NullPointerException e){
15. System.out.println(e);
16. }
17.
18. //executes regardless of exception occured or not
19. finally {
20. System.out.println("finally block is always executed");
21. }
22.
23. System.out.println("rest of the code...");
24. }
25. }
Output:

8.Aim: Develop java programs using Multithreading (using Thread class and Runnableinterface,
synchronization).
Multithreading in Java
1. Multithreading
2. Multitasking
3. Process-based multitasking
4. Thread-based multitasking
5. What is Thread

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.

However, we use multithreading than multiprocessing because threads use a shared memory area. They don't
allocate separate memory area so saves memory, and context-switching between the threads takes less time than
process.

Abstract class in Java | Abstraction in Java

Java Multithreading is mostly used in games, animation, etc.

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.

Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU.
Multitasking can be achieved in two ways:

o Process-based Multitasking (Multiprocessing)


o Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)


o Each process has an address in memory. In other words, each process allocates a separate memory area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for saving and loading registers, memory maps,
updating lists, etc.

2) Thread-based Multitasking (Multithreading)


o Threads share the same address space.
o A thread is lightweight.
o Cost of communication between the thread is low.

Life cycle of a Thread (Thread States)

In Java, a thread always exists in any one of the following states. These states are:

1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated

Explanation of Different Thread States

New: Whenever a new thread is created, it is always in the new state. For a thread in the new state, the code has
not been run yet and thus has not begun its execution.

Active: When a thread invokes the start() method, it moves from the new state to the active state. The active state
contains two states within it: one is runnable, and the other is running.

Abstract class in Java | Abstraction in Java


o Runnable: A thread, that is ready to run is then moved to the runnable state. In the runnable state, the
thread may be running or may be ready to run at any given instant of time. It is the duty of the thread
scheduler to provide the thread time to run, i.e., moving the thread the running state.
A program implementing multithreading acquires a fixed slice of time to each individual thread. Each and
every thread runs for a short span of time and when that allocated time slice is over, the thread voluntarily
gives up the CPU to the other thread, so that the other threads can also run for their slice of time. Whenever
such a scenario occurs, all those threads that are willing to run, waiting for their turn to run, lie in the
runnable state. In the runnable state, there is a queue where the threads lie.
o Running: When the thread gets the CPU, it moves from the runnable to the running state. Generally, the
most common change in the state of a thread is from runnable to running and again back to runnable.

Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then, either the thread is
in the blocked state or is in the waiting state.
For example, a thread (let's say its name is A) may want to print some data from the printer. However, at the same
time, the other thread (let's say its name is B) is using the printer to print some data. Therefore, thread A has to
wait for thread B to use the printer. Thus, thread A is in the blocked state. A thread in the blocked state is unable to
perform any execution and thus never consume any cycle of the Central Processing Unit (CPU). Hence, we can
say that thread A remains idle until the thread scheduler reactivates thread A, which is in the waiting or blocked
state.

When the main thread invokes the join() method then, it is said that the main thread is in the waiting state. The
main thread then waits for the child threads to complete their tasks. When the child threads complete their job, a
notification is sent to the main thread, which again moves the thread from waiting to the active state.

If there are a lot of threads in the waiting or blocked state, then it is the duty of the thread scheduler to determine
which thread to choose and which one to reject, and the chosen thread is then given the opportunity to run.

Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its name is A) has entered the
critical section of a code and is not willing to leave that critical section. In such a scenario, another thread (its
name is B) has to wait forever, which leads to starvation. To avoid such scenario, a timed waiting state is given to
thread B. Thus, thread lies in the waiting state for a specific span of time, and not forever. A real example of timed
waiting is when we invoke the sleep() method on a specific thread. The sleep() method puts the thread in the timed
wait state. After the time runs out, the thread wakes up and start its execution from when it has left earlier.

Terminated: A thread reaches the termination state because of the following reasons:

o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an unhandled exception or
segmentation fault.

A terminated thread means the thread is no more in the system. In other words, the thread is dead, and there is no
way one can respawn (active after kill) the dead thread.

The following diagram shows the different states involved in the life cycle of a thread.
How to create a thread in Java

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends
Object class and implements Runnable interface.

Commonly used Constructors of Thread class:


o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)

Commonly used methods of Thread class:


1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease
execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause and allow other
threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.

Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be executed by a
thread. Runnable interface have only one method named run().

2.5M
288
Features of Java - Javatpoint
1. public void run(): is used to perform action for a thread.

Starting a thread:

The start() method of Thread class is used to start a newly created thread. It performs the following tasks:

o A new thread starts(with new callstack).


o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.

1) Java Thread Example by extending Thread class

FileName: Multi.java

1. class Multi extends Thread{


2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. }
9. }

Output:

thread is running...

2) Java Thread Example by implementing Runnable interface

FileName: Multi3.java

1. class Multi3 implements Runnable{


2. public void run(){
3. System.out.println("thread is running...");
4. }
5.
6. public static void main(String args[]){
7. Multi3 m1=new Multi3();
8. Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
9. t1.start();
10. }
11. }
Output:

thread is running...

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 the Thread class object. We are passing the object of your class that implements Runnable so that
your class run() method may execute.

3) Using the Thread Class: Thread(String Name)

We can directly use the Thread class to spawn new threads using the constructors defined above.

FileName: MyThread1.java

1. public class MyThread1


2. {
3. // Main method
4. public static void main(String argvs[])
5. {
6. // creating an object of the Thread class using the constructor Thread(String name)
7. Thread t= new Thread("My first thread");
8.
9. // the start() method moves the thread to the active state
10. t.start();
11. // getting the thread name by invoking the getName() method
12. String str = t.getName();
13. System.out.println(str);
14. }
15. }

Output:

My first thread

9.Aim: Develop java programs using collections (using list, set, Map and generics).
Collections in Java

The Collection in Java is a framework that provides an 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)

What is a framework in Java


o It provides readymade architecture.
o It represents a set of classes and interfaces.
o It is optional.

What is Collection framework

The Collection framework represents a unified architecture for storing and manipulating a group of objects. It has:

1. Interfaces and its implementations, i.e., classes


2. Algorithm

java List

List in Java provides the facility to maintain the ordered collection. It contains the index-based methods to insert,
update, delete and search the elements. It can have the duplicate elements also. We can also store the null elements
in the list.

The List interface is found in the java.util package and inherits the Collection interface. It is a factory of
ListIterator interface. Through the ListIterator, we can iterate the list in forward and backward directions. The
implementation classes of List interface are ArrayList, LinkedList, Stack and Vector. The ArrayList and
LinkedList are widely used in Java programming. The Vector class is deprecated since Java 5.

java List Example

Let's see a simple example of List where we are using the ArrayList class as the implementation.

1. import java.util.*;
2. public class ListExample1{
3. public static void main(String args[]){
4. //Creating a List
5. List<String> list=new ArrayList<String>();
6. //Adding elements in the List
7. list.add("Mango");
8. list.add("Apple");
9. list.add("Banana");
10. list.add("Grapes");
11. //Iterating the List element using for-each loop
12. for(String fruit:list)
13. System.out.println(fruit);
14.
15. }
16. }

Output:

Mango
Apple
Banana
Grapes
Set in Java
The set is an interface available in the java.util package. The set interface extends the Collection interface. An
unordered collection or list in which duplicates are not allowed is referred to as a collection interface. The set
interface is used to create the mathematical set. The set interface use collection interface's methods to avoid the
insertion of the same elements. SortedSet and NavigableSet are two interfaces that extend the set implementation.

SetExample1.java
1.import java.util.*;
2.public class setExample{
3. public static void main(String[] args)
4. {
5. // creating LinkedHashSet using the Set
6. Set<String> data = new LinkedHashSet<String>();
7.
8. data.add("JavaTpoint");
9. data.add("Set");
10. data.add("Example");
11. data.add("Set");
12.
13. System.out.println(data);
14. }
15. }

Output:

Java Map Interface

A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is known as an entry. A
Map contains unique keys.

A Map is useful if you have to search, update or delete elements on the basis of a key.

Java Map Hierarchy

There are two interfaces for implementing Map in java: Map and SortedMap, and three classes: HashMap,
LinkedHashMap, and TreeMap. The hierarchy of Java Map is given below:
A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and LinkedHashMap allow null
keys and values, but TreeMap doesn't allow any null key or value.

Java Map Example: Non-Generic (Old Style)


1. //Non-generic
2. import java.util.*;
3. public class MapExample1 {
4. public static void main(String[] args) {
5. Map map=new HashMap();
6. //Adding elements to map
7. map.put(1,"Amit");
8. map.put(5,"Rahul");
9. map.put(2,"Jai");
10. map.put(6,"Amit");
11. //Traversing Map
12. Set set=map.entrySet();//Converting to Set so that we can traverse
13. Iterator itr=set.iterator();
14. while(itr.hasNext()){
15. //Converting to Map.Entry so that we can get key and value separately
16. Map.Entry entry=(Map.Entry)itr.next();
17. System.out.println(entry.getKey()+" "+entry.getValue());
18. }
19. }
20. }

Output:

1 Amit
2 Jai
5 Rahul
6 Amit
Generics in Java

The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. It makes the code stable
by detecting the bugs at compile time.

Before generics, we can store any type of objects in the collection, i.e., non-generic. Now generics force the java
programmer to store a specific type of objects.

Example of Generics in Java

Here, we are using the ArrayList class, but you can use any collection class such as ArrayList, LinkedList,
HashSet, TreeSet, HashMap, Comparator etc.

1. import java.util.*;
2. class TestGenerics1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("rahul");
6. list.add("jai");
7. //list.add(32);//compile time error
8.
9. String s=list.get(1);//type casting is not required
10. System.out.println("element is: "+s);
11.
12. Iterator<String> itr=list.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }

1. import java.util.*;
2. class TestGenerics1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("rahul");
6. list.add("jai");
7. //list.add(32);//compile time error
8.
9. String s=list.get(1);//type casting is not required
10. System.out.println("element is: "+s);
11.
12. Iterator<String> itr=list.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }

Output:
element is: jai
rahul
jai

10 Aim: CASE STUDY: Develop a program to calculate SGPA & CGPA of a student anddisplay
the progress report.
INPUT:
INPUT

HOW MANY SEMESTERS?


ROLL NO NAME
Semester wise : Subject Code, Subject
Name And Marks
OUTPUT:
Progress report of

<NAME>Roll No:
Program(BE/ME)
Branch:
College Code and Name:
Year of joining:
Semester-I Grades Semester-II Grades Semester-III Grades
Subject 1: Subject 1: Subject 1:
Subject 2: Subject 2: Subject 2:
Subject 3: Subject 3: Subject 3:
…. …. ….
SGPA : SGPA : SGPA :
CGPA : CGPA : CGPA :
VIVA VOCE
JAVA VIVA QUESTIONS

1) What is Java?

Java is the high-level, object-oriented, robust, secure programming language, platform-independent, high performance,
Multithreaded, and portable programming language. It was developed by James Gosling in June 1991. It can also be
known as the platform as it provides its own JRE and API.

2) What are the differences between C++ and Java?

The differences between C++ and Java are given in the following table.

Comparison C++ Java


Index

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


independent

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

Goto C++ supports Java doesn't support the goto statement.


the goto statement.

Multiple C++ supports multiple Java doesn't support multiple inheritance


inheritance inheritance. through class. It can be achieved
by interfaces in java.

Operator C++ supports operator Java doesn't support operator


Overloading overloading. overloading.

Pointers C++ supports pointers. You can Java supports pointer internally.
write pointer program in C++. However, you can't write the pointer
program in java. It means java has
restricted pointer support in Java.

Compiler and C++ uses compiler only. C++ is Java uses compiler and interpreter both.
Interpreter compiled and run using the Java source code is converted into
compiler which converts source bytecode at compilation time. The
code into machine code so, interpreter executes this bytecode at
C++ is platform dependent. runtime and produces output. Java is
interpreted that is why it is platform
independent.

Call by Value C++ supports both call by value Java supports call by value only. There is
and Call by and call by reference. no call by reference in java.
reference

Structure and C++ supports structures and Java doesn't support structures and
Union unions. unions.

Thread Support C++ doesn't have built-in Java has built-in thread support.
support for threads. It relies on
third-party libraries for thread
support.

Documentation C++ doesn't support Java supports documentation comment


comment documentation comment. (/** ... */) to create documentation for java
source code.

Virtual Keyword C++ supports virtual keyword Java has no virtual keyword. We can
so that we can decide whether override all non-static methods by default.
or not override a function. In other words, non-static methods are
virtual by default.

unsigned right C++ doesn't support >>> Java supports unsigned right shift >>>
shift >>> operator. operator that fills zero at the top for the
negative numbers. For positive numbers,
it works same like >> operator.

Inheritance C++ creates a new inheritance Java uses a single inheritance tree
Tree tree always. always because all classes are the child
of Object class in java. The object class is
the root of the inheritance tree in java.

Hardware C++ is nearer to hardware. Java is not so interactive with hardware.

Object-oriented C++ is an object-oriented Java is also an object-oriented language.


language. However, in C However, everything (except fundamental
language, single root hierarchy types) is an object in Java. It is a single
is not possible. root hierarchy as everything gets derived
from java.lang.Object.

3) List the features of Java Programming language.

There are the following features in Java Programming Language.

o Simple: Java is easy to learn. The syntax of Java is based on C++ which makes easier to write the program in it.

o Object-Oriented: Java follows the object-oriented paradigm which allows us to maintain our code as the
combination of different type of objects that incorporates both data and behavior.

o Portable: Java supports read-once-write-anywhere approach. We can execute the Java program on every
machine. Java program (.java) is converted to bytecode (.class) which can be easily run on every machine.

o Platform Independent: Java is a platform independent programming language. It is different from other
programming languages like C and C++ which needs a platform to be executed. Java comes with its platform on
which its code is executed. Java doesn't depend upon the operating system to be executed.

o Secured: Java is secured because it doesn't use explicit pointers. Java also provides the concept of ByteCode and
Exception handling which makes it more secured.

o Robust: Java is a strong programming language as it uses strong memory management. The concepts like
Automatic garbage collection, Exception handling, etc. make it more robust.

o Architecture Neutral: Java is architectural neutral as it is not dependent on the architecture. In C, the size of data
types may vary according to the architecture (32 bit or 64 bit) which doesn't exist in Java.

o Interpreted: Java uses the Just-in-time (JIT) interpreter along with the compiler for the program execution.

o High Performance: Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g., C++).

o Multithreaded: We can write Java programs that deal with many tasks at once by defining multiple threads. The
main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a common memory
area. Threads are important for multi-media, Web applications, etc.
o Distributed: Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB
are used for creating distributed applications. This feature of Java makes us able to access files by calling the
methods from any machine on the internet.

o Dynamic: Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on
demand. It also supports functions from its native languages, i.e., C and C++.

4) What do you understand by Java virtual machine?

Java Virtual Machine is a virtual machine that enables the computer to run the Java program. JVM acts like a run-time
engine which calls the main method present in the Java code. JVM is the specification which must be implemented in the
computer system. The Java code is compiled by JVM to be a Bytecode which is machine independent and close to the
native code.

5) What is the difference between JDK, JRE, and JVM?

JVM

JVM is an acronym for Java Virtual Machine; it is an abstract machine which provides the runtime environment in which
Java bytecode can be executed. It is a specification which specifies the working of Java Virtual Machine. Its implementation
has been provided by Oracle and other companies. Its implementation is known as JRE.

JVMs are available for many hardware and software platforms (so JVM is platform dependent). It is a runtime instance
which is created when we run the Java class. There are three notions of the JVM: specification, implementation, and
instance.

JRE

JRE stands for Java Runtime Environment. It is the implementation of JVM. The Java Runtime Environment is a set of
software tools which are used for developing Java applications. It is used to provide the runtime environment. It is the
implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime.

JDK

JDK is an acronym for Java Development Kit. It is a software development environment which is used to develop Java
applications and applets. It physically exists. It contains JRE + development tools. JDK is an implementation of any one of
the below given Java Platforms released by Oracle Corporation:

o Standard Edition Java Platform


o Enterprise Edition Java Platform
o Micro Edition Java Platform

More Details.

6) How many types of memory areas are allocated by JVM?


Many types:

1. Class(Method) Area: Class Area stores per-class structures such as the runtime constant pool, field, method data,
and the code for methods.
2. Heap: It is the runtime data area in which the memory is allocated to the objects
3. Stack: Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation
and return. Each thread has a private JVM stack, created at the same time as the thread. A new frame is created
each time a method is invoked. A frame is destroyed when its method invocation completes.
4. Program Counter Register: PC (program counter) register contains the address of the Java virtual machine
instruction currently being executed.
5. Native Method Stack: It contains all the native methods used in the application.

More Details.

7) What is JIT compiler?

Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the bytecode that have similar
functionality at the same time, and hence reduces the amount of time needed for compilation. Here the term “compiler”
refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

8) What is the platform?

A platform is the hardware or software environment in which a piece of software is executed. There are two types of
platforms, software-based and hardware-based. Java provides the software-based platform.

9) What are the main differences between the Java platform and other platforms?

There are the following differences between the Java platform and other platforms.

o Java is the software-based platform whereas other platforms may be the hardware platforms or software-based
platforms.
o Java is executed on the top of other hardware platforms whereas other platforms can only have the hardware
components.

10) What gives Java its 'write once and run anywhere' nature?

The bytecode. Java compiler converts the Java programs into the class file (Byte Code) which is the intermediate language
between source code and machine code. This bytecode is not platform specific and can be executed on any computer.

11) What is classloader?

Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is loaded first by
the classloader. There are three built-in classloaders in Java.
1. Bootstrap ClassLoader: This is the first classloader which is the superclass of Extension classloader. It loads
the rt.jar file which contains all class files of Java Standard Edition like java.lang package classes, java.net package
classes, java.util package classes, java.io package classes, java.sql package classes, etc.
2. Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of System classloader. It
loads the jar files located inside $JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: This is the child classloader of Extension classloader. It loads the class files
from the classpath. By default, the classpath is set to the current directory. You can change the classpath using "-
cp" or "-classpath" switch. It is also known as Application classloader.

12) Is Empty .java file name a valid source file name?

Yes, Java allows to save our java file by .java only, we need to compile it by javac .java and run by java classname Let's
take a simple example:

1. //save by .java only


2. class A{
3. public static void main(String args[]){
4. System.out.println("Hello java");
5. }
6. }
7. //compile by javac .java
8. //run by java A

compile it by javac .java

run it by java A

13) Is delete, next, main, exit or null keyword in java?

No.

14) If I don't provide any arguments on the command line, then what will the value stored in the
String array passed into the main() method, empty or NULL?

It is empty, but not null.

15) What if I write static public void instead of public static void?

The program compiles and runs correctly because the order of specifiers doesn't matter in Java.

16) What is the default value of the local variables?


The local variables are not initialized to any default value, neither primitives nor object references.

17) What are the various access specifiers in Java?

In Java, access specifiers are the keywords which are used to define the access scope of the method, class, or a variable.
In Java, there are four access specifiers given below.

o Public The classes, methods, or variables which are defined as public, can be accessed by any class or method.
o Protected Protected can be accessed by the class of the same package, or by the sub-class of this class, or within
the same class.
o Default Default are accessible within the package only. By default, all the classes, methods, and variables are of
default scope.
o Private The private class, methods, or variables defined as private can be accessed within the class only.

18) What is the purpose of static methods and variables?

The methods or variables defined as static are shared among all the objects of the class. The static is the part of the class
and not of the object. The static variables are stored in the class area, and we do not need to create the object to access
such variables. Therefore, static is used in the case, where we need to define variables or methods which are common to all
the objects of the class.

For example, In the class simulating the collection of the students in a college, the name of the college is the common
attribute to all the students. Therefore, the college name will be defined as static.

19) What are the advantages of Packages in Java?

There are various advantages of defining packages in Java.

o Packages avoid the name clashes.


o The Package provides easier access control.
o We can also have the hidden classes that are not visible outside and used by the package.
o It is easier to locate the related classes.

20) What is the output of the following Java program?


1. class Test
2. {
3. public static void main (String args[])
4. {
5. System.out.println(10 + 20 + "Javatpoint");
6. System.out.println("Javatpoint" + 10 + 20);
7. }
8. }

The output of the above code will be


30Javatpoint
Javatpoint1020

Explanation

In the first case, 10 and 20 are treated as numbers and added to be 30. Now, their sum 30 is treated as the string and
concatenated with the string Javatpoint. Therefore, the output will be 30Javatpoint.

In the second case, the string Javatpoint is concatenated with 10 to be the string Javatpoint10 which will then be
concatenated with 20 to be Javatpoint1020.

21) What is the output of the following Java program?


1. class Test
2. {
3. public static void main (String args[])
4. {
5. System.out.println(10 * 20 + "Javatpoint");
6. System.out.println("Javatpoint" + 10 * 20);
7. }
8. }

The output of the above code will be

200Javatpoint
Javatpoint200

Explanation

In the first case, The numbers 10 and 20 will be multiplied first and then the result 200 is treated as the string and
concatenated with the string Javatpoint to produce the output 200Javatpoint.

In the second case, The numbers 10 and 20 will be multiplied first to be 200 because the precedence of the multiplication is
higher than addition. The result 200 will be treated as the string and concatenated with the string Javatpointto produce the
output as Javatpoint200.

22) What is the output of the following Java program?


1. class Test
2. {
3. public static void main (String args[])
4. {
5. for(int i=0; 0; i++)
6. {
7. System.out.println("Hello Javatpoint");
8. }
9. }
10. }

The above code will give the compile-time error because the for loop demands a boolean value in the second part and we
are providing an integer value, i.e., 0.
Core Java - OOPs Concepts: Initial OOPs Interview Questions
There is given more than 50 OOPs (Object-Oriented Programming and System) interview questions. However, they have
been categorized in many sections such as constructor interview questions, static interview questions, Inheritance Interview
questions, Abstraction interview question, Polymorphism interview questions, etc. for better understanding.

23) What is object-oriented paradigm?

It is a programming paradigm based on objects having data and methods defined in the class to which it belongs. Object-
oriented paradigm aims to incorporate the advantages of modularity and reusability. Objects are the instances of classes
which interacts with one another to design applications and programs. There are the following features of the object-
oriented paradigm.

o Follows the bottom-up approach in program design.


o Focus on data with methods to operate upon the object's data
o Includes the concept like Encapsulation and abstraction which hides the complexities from the user and show only
functionality.
o Implements the real-time approach like inheritance, abstraction, etc.
o The examples of the object-oriented paradigm are C++, Simula, Smalltalk, Python, C#, etc.

24) What is an object?

The Object is the real-time entity having some state and behavior. In Java, Object is an instance of the class having the
instance variables as the state of the object and the methods as the behavior of the object. The object of a class can be
created by using the new keyword.

25) What is the difference between an object-oriented programming language and object-
based programming language?

There are the following basic differences between the object-oriented language and object-based language.

o Object-oriented languages follow all the concepts of OOPs whereas, the object-based language doesn't follow all
the concepts of OOPs like inheritance and polymorphism.
o Object-oriented languages do not have the inbuilt objects whereas Object-based languages have the inbuilt objects,
for example, JavaScript has window object.
o Examples of object-oriented programming are Java, C#, Smalltalk, etc. whereas the examples of object-based
languages are JavaScript, VBScript, etc.

26) What will be the initial value of an object reference which is defined as an instance
variable?

All object references are initialized to null in Java.


Core Java - OOPs Concepts: Constructor Interview Questions

27) What is the constructor?

The constructor can be defined as the special type of method that is used to initialize the state of an object. It is invoked
when the class is instantiated, and the memory is allocated for the object. Every time, an object is created using
the new keyword, the default constructor of the class is called. The name of the constructor must be similar to the class
name. The constructor must not have an explicit return type.

More Details.

28) How many types of constructors are used in Java?

Based on the parameters passed in the constructors, there are two types of constructors in Java.

o Default Constructor: default constructor is the one which does not accept any value. The default constructor is
mainly used to initialize the instance variable with the default values. It can also be used for performing some useful
task on object creation. A default constructor is invoked implicitly by the compiler if there is no constructor defined in
the class.
o Parameterized Constructor: The parameterized constructor is the one which can initialize the instance variables
with the given values. In other words, we can say that the constructors which can accept the arguments are called
parameterized constructors.

29) What is the purpose of a default constructor?

The purpose of the default constructor is to assign the default value to the objects. The java compiler creates a default
constructor implicitly if there is no constructor in the class.

1. class Student3{
2. int id;
3. String name;
4.
5. void display(){System.out.println(id+" "+name);}
6.
7. public static void main(String args[]){
8. Student3 s1=new Student3();
9. Student3 s2=new Student3();
10. s1.display();
11. s2.display();
12. }
13. }
Test it Now

Output:

0 null
0 null

Explanation: In the above class, you are not creating any constructor, so compiler provides you a default constructor. Here
0 and null values are provided by default constructor.

More Details.

30) Does constructor return any value?

Ans: yes, The constructor implicitly returns the current instance of the class (You can't use an explicit return type with the
constructor). More Details.

31)Is constructor inherited?

No, The constructor is not inherited.

32) Can you make a constructor final?

No, the constructor can't be final.


33) Can we overload the constructors?

Yes, the constructors can be overloaded by changing the number of arguments accepted by the constructor or by changing
the data type of the parameters. Consider the following example.

1. class Test
2. {
3. int i;
4. public Test(int k)
5. {
6. i=k;
7. }
8. public Test(int k, int m)
9. {
10. System.out.println("Hi I am assigning the value max(k, m) to i");
11. if(k>m)
12. {
13. i=k;
14. }
15. else
16. {
17. i=m;
18. }
19. }
20. }
21. public class Main
22. {
23. public static void main (String args[])
24. {
25. Test test1 = new Test(10);
26. Test test2 = new Test(12, 15);
27. System.out.println(test1.i);
28. System.out.println(test2.i);
29. }
30. }
31.

In the above program, The constructor Test is overloaded with another constructor. In the first call to the constructor, The
constructor with one argument is called, and i will be initialized with the value 10. However, In the second call to the
constructor, The constructor with the 2 arguments is called, and i will be initialized with the value 15.

34) What do you understand by copy constructor in Java?

There is no copy constructor in java. However, we can copy the values from one object to another like copy constructor in
C++.

There are many ways to copy the values of one object into another in java. They are:
o By constructor
o By assigning the values of one object into another
o By clone() method of Object class

In this example, we are going to copy the values of one object into another using java constructor.

1. //Java program to initialize the values from one object to another


2. class Student6{
3. int id;
4. String name;
5. //constructor to initialize integer and string
6. Student6(int i,String n){
7. id = i;
8. name = n;
9. }
10. //constructor to initialize another object
11. Student6(Student6 s){
12. id = s.id;
13. name =s.name;
14. }
15. void display(){System.out.println(id+" "+name);}
16.
17. public static void main(String args[]){
18. Student6 s1 = new Student6(111,"Karan");
19. Student6 s2 = new Student6(s1);
20. s1.display();
21. s2.display();
22. }
23. }
Test it Now

Output:

111 Karan
111 Karan

35) What are the differences between the constructors and methods?

There are many differences between constructors and methods. They are given below.

Java Constructor Java Method

A constructor is used to initialize the state of an object. A method is used to expose the
behavior of an object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default constructor if you The method is not provided by the
don't have any constructor in a class. compiler in any case.
The constructor name must be same as the class name. The method name may or may not
be same as class name.

36) What is the output of the following Java program?


1. public class Test
2. {
3. Test(int a, int b)
4. {
5. System.out.println("a = "+a+" b = "+b);
6. }
7. Test(int a, float b)
8. {
9. System.out.println("a = "+a+" b = "+b);
10. }
11. public static void main (String args[])
12. {
13. byte a = 10;
14. byte b = 15;
15. Test test = new Test(a,b);
16. }
17. }

The output of the following program is:

a = 10 b = 15

Here, the data type of the variables a and b, i.e., byte gets promoted to int, and the first parameterized constructor with the
two integer parameters is called.

37) What is the output of the following Java program?


1. class Test
2. {
3. int i;
4. }
5. public class Main
6. {
7. public static void main (String args[])
8. {
9. Test test = new Test();
10. System.out.println(test.i);
11. }
12. }

The output of the program is 0 because the variable i is initialized to 0 internally. As we know that a default constructor is
invoked implicitly if there is no constructor in the class, the variable i is initialized to 0 since there is no constructor in the
class.

38) What is the output of the following Java program?


1. class Test
2. {
3. int test_a, test_b;
4. Test(int a, int b)
5. {
6. test_a = a;
7. test_b = b;
8. }
9. public static void main (String args[])
10. {
11. Test test = new Test();
12. System.out.println(test.test_a+" "+test.test_b);
13. }
14. }

There is a compiler error in the program because there is a call to the default constructor in the main method which is not
present in the class. However, there is only one parameterized constructor in the class Test. Therefore, no default
constructor is invoked by the constructor implicitly.
Core Java - OOPs Concepts: static keyword Interview Questions

39) What is the static variable?

The static variable is used to refer to the common property of all objects (that is not unique for each object), e.g., The
company name of employees, college name of students, etc. Static variable gets memory only once in the class area at the
time of class loading. Using a static variable makes your program more memory efficient (it saves memory). Static variable
belongs to the class rather than the object.

1. //Program of static variable


2.
3. class Student8{
4. int rollno;
5. String name;
6. static String college ="ITS";
7.
8. Student8(int r,String n){
9. rollno = r;
10. name = n;
11. }
12. void display (){System.out.println(rollno+" "+name+" "+college);}
13.
14. public static void main(String args[]){
15. Student8 s1 = new Student8(111,"Karan");
16. Student8 s2 = new Student8(222,"Aryan");
17.
18. s1.display();
19. s2.display();
20. }
21. }
Test it Now
Output:111 Karan ITS
222 Aryan ITS
More Details.

40) What is the static method?


o A static method belongs to the class rather than the object.
o There is no need to create the object to call the static methods.
o A static method can access and change the value of the static variable.

More Details.

41) What are the restrictions that are applied to the Java static methods?

Two main restrictions are applied to the static methods.

o The static method can not use non-static data member or call the non-static method directly.
o this and super cannot be used in static context as they are non-static.

42) Why is the main method static?

Because the object is not required to call the static method. If we make the main method non-static, JVM will have to create
its object first and then call main() method which will lead to the extra memory allocation. More Details.

43) Can we override the static methods?


No, we can't override static methods.

44) What is the static block?

Static block is used to initialize the static data member. It is executed before the main method, at the time of classloading.

1. class A2{
2. static{System.out.println("static block is invoked");}
3. public static void main(String args[]){
4. System.out.println("Hello main");
5. }
6. }
Test it Now
Output: static block is invoked
Hello main

More Details.

45) Can we execute a program without main() method?

Ans) No, It was possible before JDK 1.7 using the static block. Since JDK 1.7, it is not possible. More Details.

46) What if the static modifier is removed from the signature of the main method?

Program compiles. However, at runtime, It throws an error "NoSuchMethodError."

47) What is the difference between static (class) method and instance method?
static or class method instance method

1)A method that is declared as static is known as the static A method that is not declared as
method. static is known as the instance
method.

2)We don't need to create the objects to call the static The object is required to call the
methods. instance methods.

3)Non-static (instance) members cannot be accessed in Static and non-static variables


the static context (static method, static block, and static both can be accessed in instance
nested class) directly. methods.

4)For example: public static int cube(int n){ return n*n*n;} For example: public void
msg(){...}.

48) Can we make constructors static?

As we know that the static context (method, block, or variable) belongs to the class, not the object. Since Constructors are
invoked only when the object is created, there is no sense to make the constructors static. However, if you try to do so, the
compiler will show the compiler error.
49) Can we make the abstract methods static in Java?

In Java, if we make the abstract methods static, It will become the part of the class, and we can directly call it which is
unnecessary. Calling an undefined method is completely useless therefore it is not allowed.

50) Can we declare the static variables and methods in an abstract class?

Yes, we can declare static variables and methods in an abstract method. As we know that there is no requirement to make
the object to access the static context, therefore, we can access the static context declared inside the abstract class by
using the name of the abstract class. Consider the following example.

1. abstract class Test


2. {
3. static int i = 102;
4. static void TestMethod()
5. {
6. System.out.println("hi !! I am good !!");
7. }
8. }
9. public class TestClass extends Test
10. {
11. public static void main (String args[])
12. {
13. Test.TestMethod();
14. System.out.println("i = "+Test.i);
15. }
16. }

Output

hi !! I am good !!
i = 102

Core Java - OOPs Concepts: Inheritance Interview Questions

51) What is this keyword in java?

The this keyword is a reference variable that refers to the current object. There are the various uses of this keyword in
Java. It can be used to refer to current class properties such as instance methods, variable, constructors, etc. It can also be
passed as an argument into the methods or constructors. It can also be returned from the method as the current class
instance.
More Details.

52) What are the main uses of this keyword?

There are the following uses of this keyword.

o this can be used to refer to the current class instance variable.


o this can be used to invoke current class method (implicitly)
o this() can be used to invoke the current class constructor.
o this can be passed as an argument in the method call.
o this can be passed as an argument in the constructor call.
o this can be used to return the current class instance from the method.

53) Can we assign the reference to this variable?

No, this cannot be assigned to any value because it always points to the current class object and this is the final reference
in Java. However, if we try to do so, the compiler error will be shown. Consider the following example.

1. public class Test


2. {
3. public Test()
4. {
5. this = null;
6. System.out.println("Test class constructor called");
7. }
8. public static void main (String args[])
9. {
10. Test t = new Test();
11. }
12. }

Output

Test.java:5: error: cannot assign a value to final variable this


this = null;
^
1 error
54) Can this keyword be used to refer static members?

Yes, It is possible to use this keyword to refer static members because this is just a reference variable which refers to the
current class object. However, as we know that, it is unnecessary to access static variables through objects, therefore, it is
not the best practice to use this to refer static members. Consider the following example.

1. public class Test


2. {
3. static int i = 10;
4. public Test ()
5. {
6. System.out.println(this.i);
7. }
8. public static void main (String args[])
9. {
10. Test t = new Test();
11. }
12. }

Output

10

55) How can constructor chaining be done using this keyword?

Constructor chaining enables us to call one constructor from another constructor of the class with respect to the current
class object. We can use this keyword to perform constructor chaining within the same class. Consider the following
example which illustrates how can we use this keyword to achieve constructor chaining.

1. public class Employee


2. {
3. int id,age;
4. String name, address;
5. public Employee (int age)
6. {
7. this.age = age;
8. }
9. public Employee(int id, int age)
10. {
11. this(age);
12. this.id = id;
13. }
14. public Employee(int id, int age, String name, String address)
15. {
16. this(id, age);
17. this.name = name;
18. this.address = address;
19. }
20. public static void main (String args[])
21. {
22. Employee emp = new Employee(105, 22, "Vikas", "Delhi");
23. System.out.println("ID: "+emp.id+" Name:"+emp.name+" age:"+emp.age+" address: "+emp.address);
24. }
25.
26. }

Output

ID: 105 Name:Vikas age:22 address: Delhi

56) What are the advantages of passing this into a method instead of the current class object
itself?

As we know, that this refers to the current class object, therefore, it must be similar to the current class object. However,
there can be two main advantages of passing this into a method instead of the current class object.

o this is a final variable. Therefore, this cannot be assigned to any new value whereas the current class object might
not be final and can be changed.
o this can be used in the synchronized block.

57) What is the Inheritance?

Inheritance is a mechanism by which one object acquires all the properties and behavior of another object of another class.
It is used for Code Reusability and Method Overriding. The idea behind inheritance in Java is that you can create new
classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of
the parent class. Moreover, you can add new methods and fields in your current class also. Inheritance represents the IS-A
relationship which is also known as a parent-child relationship.

There are five types of inheritance in Java.

o Single-level inheritance
o Multi-level inheritance
o Multiple Inheritance
o Hierarchical Inheritance
o Hybrid Inheritance

Multiple inheritance is not supported in Java through class.

More Details.

58) Why is Inheritance used in Java?

There are various advantages of using inheritance in Java that is given below.

o Inheritance provides code reusability. The derived class does not need to redefine the method of base class unless
it needs to provide the specific implementation of the method.
o Runtime polymorphism cannot be achieved without using inheritance.
o We can simulate the inheritance of classes with the real-time objects which makes OOPs more realistic.
o Inheritance provides data hiding. The base class can hide some data from the derived class by making it private.
o Method overriding cannot be achieved without inheritance. By method overriding, we can give a specific
implementation of some basic method contained by the base class.

59) Which class is the superclass for all the classes?

The object class is the superclass of all other classes in Java.

60) Why is multiple inheritance not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider a scenario
where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and
you call it from child class object, there will be ambiguity to call the method of A or B class.

Since the compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So
whether you have the same method or different, there will be a compile time error.

1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. Public Static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }
Test it Now
Compile Time Error

61) What is aggregation?

Aggregation can be defined as the relationship between two classes where the aggregate class contains a reference to the
class it owns. Aggregation is best described as a has-a relationship. For example, The aggregate class Employee having
various fields such as age, name, and salary also contains an object of Address class having various fields such as
Address-Line 1, City, State, and pin-code. In other words, we can say that Employee (class) has an object of Address class.
Consider the following example.

Address.java

1. public class Address {


2. String city,state,country;
3.
4. public Address(String city, String state, String country) {
5. this.city = city;
6. this.state = state;
7. this.country = country;
8. }
9.
10. }

Employee.java

1. public class Emp {


2. int id;
3. String name;
4. Address address;
5.
6. public Emp(int id, String name,Address address) {
7. this.id = id;
8. this.name = name;
9. this.address=address;
10. }
11.
12. void display(){
13. System.out.println(id+" "+name);
14. System.out.println(address.city+" "+address.state+" "+address.country);
15. }
16.
17. public static void main(String[] args) {
18. Address address1=new Address("gzb","UP","india");
19. Address address2=new Address("gno","UP","india");
20.
21. Emp e=new Emp(111,"varun",address1);
22. Emp e2=new Emp(112,"arun",address2);
23.
24. e.display();
25. e2.display();
26.
27. }
28. }

Output

111 varun
gzb UP india
112 arun
gno UP india

62) What is composition?


Holding the reference of a class within some other class is known as composition. When an object contains the other object,
if the contained object cannot exist without the existence of container object, then it is called composition. In other words,
we can say that composition is the particular case of aggregation which represents a stronger relationship between two
objects. Example: A class contains students. A student cannot exist without a class. There exists composition between
class and students.

63) What is the difference between aggregation and composition?

Aggregation represents the weak relationship whereas composition represents the strong relationship. For example, the
bike has an indicator (aggregation), but the bike has an engine (composition).

64) Why does Java not support pointers?

The pointer is a variable that refers to the memory address. They are not used in Java because they are unsafe(unsecured)
and complex to understand.

65) What is super in java?

The super keyword in Java is a reference variable that is used to refer to the immediate parent class object. Whenever you
create the instance of the subclass, an instance of the parent class is created implicitly which is referred by super reference
variable. The super() is called in the class constructor implicitly by the compiler if there is no super or this.

1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. System.out.println("dog is created");
7. }
8. }
9. class TestSuper4{
10. public static void main(String args[]){
11. Dog d=new Dog();
12. }
13. }
Test it Now

Output:

animal is created
dog is created
More Details.

66) How can constructor chaining be done by using the super keyword?
1. class Person
2. {
3. String name,address;
4. int age;
5. public Person(int age, String name, String address)
6. {
7. this.age = age;
8. this.name = name;
9. this.address = address;
10. }
11. }
12. class Employee extends Person
13. {
14. float salary;
15. public Employee(int age, String name, String address, float salary)
16. {
17. super(age,name,address);
18. this.salary = salary;
19. }
20. }
21. public class Test
22. {
23. public static void main (String args[])
24. {
25. Employee e = new Employee(22, "Mukesh", "Delhi", 90000);
26. System.out.println("Name: "+e.name+" Salary: "+e.salary+" Age: "+e.age+" Address: "+e.address);
27. }
28. }

Output

Name: Mukesh Salary: 90000.0 Age: 22 Address: Delhi

67) What are the main uses of the super keyword?

There are the following uses of super keyword.

o super can be used to refer to the immediate parent class instance variable.
o super can be used to invoke the immediate parent class method.
o super() can be used to invoke immediate parent class constructor.

68) What are the differences between this and super keyword?

There are the following differences between this and super keyword.

o The super keyword always points to the parent class contexts whereas this keyword always points to the current
class context.
o The super keyword is primarily used for initializing the base class variables within the derived class constructor
whereas this keyword primarily used to differentiate between local and instance variables when passed in the class
constructor.
o The super and this must be the first statement inside constructor otherwise the compiler will throw an error.

69) What is the output of the following Java program?


1. class Person
2. {
3. public Person()
4. {
5. System.out.println("Person class constructor called");
6. }
7. }
8. public class Employee extends Person
9. {
10. public Employee()
11. {
12. System.out.println("Employee class constructor called");
13. }
14. public static void main (String args[])
15. {
16. Employee e = new Employee();
17. }
18. }

Output

Person class constructor called


Employee class constructor called

Explanation

The super() is implicitly invoked by the compiler if no super() or this() is included explicitly within the derived class
constructor. Therefore, in this case, The Person class constructor is called first and then the Employee class constructor is
called.

70) Can you use this() and super() both in a constructor?

No, because this() and super() must be the first statement in the class constructor.

Example:

1. public class Test{


2. Test()
3. {
4. super();
5. this();
6. System.out.println("Test class object is created");
7. }
8. public static void main(String []args){
9. Test t = new Test();
10. }
11. }

Output:

Test.java:5: error: call to this must be first statement in constructor

71)What is object cloning?

The object cloning is used to create the exact copy of an object. The clone() method of the Object class is used to clone an
object. The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we
don't implement Cloneable interface, clone() method generates CloneNotSupportedException.

72) What is method overloading?

Method overloading is the polymorphism technique which allows us to create multiple methods with the same name but
different signature. We can achieve method overloading in two ways.

o By Changing the number of arguments


o By Changing the data type of arguments

Method overloading increases the readability of the program. Method overloading is performed to figure out the program
quickly.

73) Why is method overloading not possible by changing the return type in java?

In Java, method overloading is not possible by changing the return type of the program due to avoid the ambiguity.

1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static double add(int a,int b){return a+b;}
4. }
5. class TestOverloading3{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));//ambiguity
8. }}
Test it Now

Output:

Compile Time Error: method add(int, int) is already defined in class Adder
More Details.

74) Can we overload the methods by making them static?

No, We cannot overload the methods by just applying the static keyword to them(number of parameters and types are the
same). Consider the following example.
1. public class Animal
2. {
3. void consume(int a)
4. {
5. System.out.println(a+" consumed!!");
6. }
7. static void consume(int a)
8. {
9. System.out.println("consumed static "+a);
10. }
11. public static void main (String args[])
12. {
13. Animal a = new Animal();
14. a.consume(10);
15. Animal.consume(20);
16. }
17. }

Output

Animal.java:7: error: method consume(int) is already defined in class Animal


static void consume(int a)
^
Animal.java:15: error: non-static method consume(int) cannot be referenced from a static
context
Animal.consume(20);
^
2 errors

75) Can we overload the main() method?

Yes, we can have any number of main methods in a Java program by using method overloading.

More Details.

76) What is method overloading with type promotion?

By Type promotion is method overloading, we mean that one data type can be promoted to another implicitly if no exact
matching is found.
As displayed in the above diagram, the byte can be promoted to short, int, long, float or double. The short datatype can be
promoted to int, long, float or double. The char datatype can be promoted to int, long, float or double and so on. Consider
the following example.

1. class OverloadingCalculation1{
2. void sum(int a,long b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4.
5. public static void main(String args[]){
6. OverloadingCalculation1 obj=new OverloadingCalculation1();
7. obj.sum(20,20);//now second int literal will be promoted to long
8. obj.sum(20,20,20);
9. }
10. }
Test it Now

Output

40
60

77) What is the output of the following Java program?


1. class OverloadingCalculation3{
2. void sum(int a,long b){System.out.println("a method invoked");}
3. void sum(long a,int b){System.out.println("b method invoked");}
4.
5. public static void main(String args[]){
6. OverloadingCalculation3 obj=new OverloadingCalculation3();
7. obj.sum(20,20);//now ambiguity
8. }
9. }

Output

OverloadingCalculation3.java:7: error: reference to sum is ambiguous


obj.sum(20,20);//now ambiguity
^
both method sum(int,long) in OverloadingCalculation3
and method sum(long,int) in OverloadingCalculation3 match
1 error

Explanation

There are two methods defined with the same name, i.e., sum. The first method accepts the integer and long type whereas
the second method accepts long and the integer type. The parameter passed that are a = 20, b = 20. We can not tell that
which method will be called as there is no clear differentiation mentioned between integer literal and long literal. This is the
case of ambiguity. Therefore, the compiler will throw an error.

78) What is method overriding:

If a subclass provides a specific implementation of a method that is already provided by its parent class, it is known as
Method Overriding. It is used for runtime polymorphism and to implement the interface methods.

Rules for Method overriding

o The method must have the same name as in the parent class.
o The method must have the same signature as in the parent class.
o Two classes must have an IS-A relationship between them.

More Details.

79) Can we override the static method?

No, you can't override the static method because they are the part of the class, not the object.

80) Why can we not override static method?

It is because the static method is the part of the class, and it is bound with class whereas instance method is bound with the
object, and static gets memory in class area, and instance gets memory in a heap.

81) Can we override the overloaded method?

Yes.
82) Difference between method Overloading and Overriding.
Method Overloading Method Overriding

1) Method overloading increases Method overriding provides the specific implementation of


the readability of the program. the method that is already provided by its superclass.

2) Method overloading occurs Method overriding occurs in two classes that have IS-A
within the class. relationship between them.

3) In this case, the parameters In this case, the parameters must be the same.
must be different.

83) Can we override the private methods?

No, we cannot override the private methods because the scope of private methods is limited to the class and we cannot
access them outside of the class.

84) Can we change the scope of the overridden method in the subclass?

Yes, we can change the scope of the overridden method in the subclass. However, we must notice that we cannot decrease
the accessibility of the method. The following point must be taken care of while changing the accessibility of the method.

o The private can be changed to protected, public, or default.


o The protected can be changed to public or default.
o The default can be changed to public.
o The public will always remain public.

85) Can we modify the throws clause of the superclass method while overriding it in the
subclass?

Yes, we can modify the throws clause of the superclass method while overriding it in the subclass. However, there are
some rules which are to be followed while overriding in case of exception handling.

o If the superclass method does not declare an exception, subclass overridden method cannot declare the checked
exception, but it can declare the unchecked exception.
o If the superclass method declares an exception, subclass overridden method can declare same, subclass exception
or no exception but cannot declare parent exception.

86) What is the output of the following Java program?


1. class Base
2. {
3. void method(int a)
4. {
5. System.out.println("Base class method called with integer a = "+a);
6. }
7.
8. void method(double d)
9. {
10. System.out.println("Base class method called with double d ="+d);
11. }
12. }
13.
14. class Derived extends Base
15. {
16. @Override
17. void method(double d)
18. {
19. System.out.println("Derived class method called with double d ="+d);
20. }
21. }
22.
23. public class Main
24. {
25. public static void main(String[] args)
26. {
27. new Derived().method(10);
28. }
29. }

Output

Base class method called with integer a = 10

Explanation

The method() is overloaded in class Base whereas it is derived in class Derived with the double type as the parameter. In
the method call, the integer is passed.

87) Can you have virtual functions in Java?

Yes, all functions in Java are virtual by default.

88) What is covariant return type?

Now, since java5, it is possible to override any method by changing the return type if the return type of the subclass
overriding method is subclass type. It is known as covariant return type. The covariant return type specifies that the return
type may vary in the same direction as the subclass.

1. class A{
2. A get(){return this;}
3. }
4.
5. class B1 extends A{
6. B1 get(){return this;}
7. void message(){System.out.println("welcome to covariant return type");}
8.
9. public static void main(String args[]){
10. new B1().get().message();
11. }
12. }
Test it Now
Output: welcome to covariant return type
More Details.

89) What is the output of the following Java program?


1. class Base
2. {
3. public void baseMethod()
4. {
5. System.out.println("BaseMethod called ...");
6. }
7. }
8. class Derived extends Base
9. {
10. public void baseMethod()
11. {
12. System.out.println("Derived method called ...");
13. }
14. }
15. public class Test
16. {
17. public static void main (String args[])
18. {
19. Base b = new Derived();
20. b.baseMethod();
21. }
22. }

Output

Derived method called ...

Explanation

The method of Base class, i.e., baseMethod() is overridden in Derived class. In Test class, the reference variable b (of type
Base class) refers to the instance of the Derived class. Here, Runtime polymorphism is achieved between class Base and
Derived. At compile time, the presence of method baseMethod checked in Base class, If it presence then the program
compiled otherwise the compiler error will be shown. In this case, baseMethod is present in Base class; therefore, it is
compiled successfully. However, at runtime, It checks whether the baseMethod has been overridden by Derived class, if so
then the Derived class method is called otherwise Base class method is called. In this case, the Derived class overrides the
baseMethod; therefore, the Derived class method is called.
90) What is the final variable?

In Java, the final variable is used to restrict the user from updating it. If we initialize the final variable, we can't change its
value. In other words, we can say that the final variable once assigned to a value, can never be changed after that. The final
variable which is not assigned to any value can only be assigned through the class constructor.

1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
Test it Now
Output:Compile Time Error
More Details.

91) What is the final method?

If we change any method to a final method, we can't override it. More Details.

1. class Bike{
2. final void run(){System.out.println("running");}
3. }
4.
5. class Honda extends Bike{
6. void run(){System.out.println("running safely with 100kmph");}
7.
8. public static void main(String args[]){
9. Honda honda= new Honda();
10. honda.run();
11. }
12. }
Test it Now
Output:Compile Time Error

92) What is the final class?

If we make any class final, we can't inherit it into any of the subclasses.

1. final class Bike{}


2.
3. class Honda1 extends Bike{
4. void run(){System.out.println("running safely with 100kmph");}
5.
6. public static void main(String args[]){
7. Honda1 honda= new Honda1();
8. honda.run();
9. }
10. }
Test it Now
Output:Compile Time Error
More Details.

93) What is the final blank variable?

A final variable, not initialized at the time of declaration, is known as the final blank variable. We can't initialize the final blank
variable directly. Instead, we have to initialize it by using the class constructor. It is useful in the case when the user has
some data which must not be changed by others, for example, PAN Number. Consider the following example:

1. class Student{
2. int id;
3. String name;
4. final String PAN_CARD_NUMBER;
5. ...
6. }
More Details.

94) Can we initialize the final blank variable?

Yes, if it is not static, we can initialize it in the constructor. If it is static blank final variable, it can be initialized only in the
static block. More Details.

95) Can you declare the main method as final?

Yes, We can declare the main method as public static final void main(String[] args){}.

96) What is the output of the following Java program?


1. class Main {
2. public static void main(String args[]){
3. final int i;
4. i = 20;
5. System.out.println(i);
6. }
7. }

Output

20

Explanation

Since i is the blank final variable. It can be initialized only once. We have initialized it to 20. Therefore, 20 will be printed.

97) What is the output of the following Java program?


1. class Base
2. {
3. protected final void getInfo()
4. {
5. System.out.println("method of Base class");
6. }
7. }
8.
9. public class Derived extends Base
10. {
11. protected final void getInfo()
12. {
13. System.out.println("method of Derived class");
14. }
15. public static void main(String[] args)
16. {
17. Base obj = new Base();
18. obj.getInfo();
19. }
20. }

Output

Derived.java:11: error: getInfo() in Derived cannot override getInfo() in Base


protected final void getInfo()
^
overridden method is final
1 error

Explanation

The getDetails() method is final; therefore it can not be overridden in the subclass.
98) Can we declare a constructor as final?

The constructor can never be declared as final because it is never inherited. Constructors are not ordinary methods;
therefore, there is no sense to declare constructors as final. However, if you try to do so, The compiler will throw an error.

99) Can we declare an interface as final?

No, we cannot declare an interface as final because the interface must be implemented by some class to provide its
definition. Therefore, there is no sense to make an interface final. However, if you try to do so, the compiler will show an
error.

100) What is the difference between the final method and abstract method?

The main difference between the final method and abstract method is that the abstract method cannot be final as we need
to override them in the subclass to give its definition.

You might also like