java lab manual
java lab manual
NAME: _____K.KEERTHI________________________________________
ROLLNO:______________________________________________________
BRANCH:______AI&DS______ SEM:_____IV____________________________
VISION
MISSION
To encourage research culture among faculty and students by establishing state of art
laboratories and exposing them to modern industrial and organizational practices.
LABORATORY MANUAL
PreparedBy
Mrs K KEERTHI
AssistantProfessor.
METHODIST
Estd:2008 COLLEGE OF ENGINEERING AND
VISION
MISSION
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
PROGRAM OUTCOMES
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.
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.
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.
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
List of Programs
<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 :
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
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.
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
Lab In – charge
METHODIST
LIST OF EXPERIMENTS
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
).
10 CASE STUDY:
Develop a
program to
calculate SGPA &
CGPA of a
student and
display the
progress report.
ADDITIONAL EXPERIMENTS
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:
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.
It is a Java programming platform. It includes Java programming APIs such as java.lang, java.io, java.net,
java.util, java.sql, java.math etc. It includes core topics like OOPs, String, Regex, Exception, Inner classes,
Multithreading, I/O Stream, Networking, AWT, Swing, Reflection, Collection, etc.
It is an enterprise platform 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.
4) JavaFX
It is used to develop rich internet applications. It uses a lightweight user interface API
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.
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.
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
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.
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.
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.
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:
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.
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
Output:
0
null
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.
Output:
0
null
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.
1. arrayRefVar=new datatype[size];
Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse an
array.
Output:
10
20
70
40
50
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
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.
StringExample.java
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
deConstructor Description
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.
String nextToken() It returns the next token from the StringTokenizer object.
String nextToken(String delim) It returns the next token based on the delimiter.
Object nextElement() It is the same as nextToken() but its return type is Object.
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.
There are mainly three reasons to use interface. They are given below.
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
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.
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
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:
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).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
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.
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.
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
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.
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
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.
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:
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...
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.
In Java, Method Overloading is not possible by changing the return type of the method only.
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
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.
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.
Output:
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.
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.
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.
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.
Let's see an example of Java Exception Handling in which we are using a try-catch statement to handle the
exception.
JavaExceptionExample.java
Output:
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.
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.
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.
Output:
The above code throw an unchecked exception. Similarly, we can also throw unchecked and user defined
exceptions.
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.
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.
Let's see the different cases where Java finally block can be used.
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
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
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.
1) It doesn't block the user because threads are independent and you can perform multiple operations at the same
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:
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
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.
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
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.
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:
FileName: Multi.java
Output:
thread is running...
FileName: Multi3.java
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.
We can directly use the Thread class to spawn new threads using the constructors defined above.
FileName: MyThread1.java
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)
The Collection framework represents a unified architecture for storing and manipulating a group of objects. It has:
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.
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:
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.
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.
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.
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
<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.
The differences between C++ and Java are given in the following table.
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.
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.
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.
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++.
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.
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:
More Details.
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.
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.
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.
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.
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:
run it by java A
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?
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.
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.
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.
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.
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.
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.
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.
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?
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.
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.
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.
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.
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.
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.
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.
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 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.
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.
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.
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
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.
More Details.
41) What are the restrictions that are applied to the Java 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.
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.
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.
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?
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.
4)For example: public static int cube(int n){ return n*n*n;} For example: public void
msg(){...}.
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.
Output
hi !! I am good !!
i = 102
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.
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.
Output
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.
Output
10
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.
Output
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.
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.
o Single-level inheritance
o Multi-level inheritance
o Multiple Inheritance
o Hierarchical Inheritance
o Hybrid Inheritance
More Details.
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.
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
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
Employee.java
Output
111 varun
gzb UP india
112 arun
gno UP india
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).
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.
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
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.
Output
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.
No, because this() and super() must be the first statement in the class constructor.
Example:
Output:
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.
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.
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.
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
Yes, we can have any number of main methods in a Java program by using method overloading.
More Details.
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
Output
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.
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.
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.
No, you can't override the static method because they are the part of the class, not the object.
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.
Yes.
82) Difference between method Overloading and Overriding.
Method Overloading Method Overriding
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.
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.
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.
Output
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.
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.
Output
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.
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
If we make any class final, we can't inherit it into any of the subclasses.
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.
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.
Yes, We can declare the main method as public static final void main(String[] args){}.
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.
Output
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.
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.