Java Mid-1 Notes
Java Mid-1 Notes
Java Basics:-
1. Introduction
2. History of Java
3. Java buzzwords
4. Data types
5. Variables
6. Scope and Life time of variables
7. Arrays
8. Operators
9. Expressions
10. Control statements
11. Type conversion and casting
12. Simple Java programs
13. Concepts of classes
14. Objects
15. Constructors
16. Methods
17. Access control
18. This keyword
19. Garbage collection
20. Overloading methods
21. Parameter passing
22. Recursion
23. Exploring String Class
TEXT BOOKS
1.What is Java?
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.
2.Application
According to Sun, 3 billion devices run Java. There are many devices where Java is currently used. Some of them
are as follows:
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(Enterprise Java Bean), JPA(Java
Persistence API (Application Programming Interface)), etc.
3) Java ME (Java Micro Edition)
4) JavaFX
It is used to develop rich internet applications. It uses a lightweight user interface API.
o Install the JDK if you don't have installed it, download the JDK and install it.
o Set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-in-java
o Create the Java program
o Compile and run the Java program
1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }
Output:
Hello Java
Compilation Flow:
When we compile Java program using javac tool, the Java compiler converts the source code into byte code.
Can you save a Java source file by another name than the class name?
Yes, if the class is not public. It is explained in the figure given below:
Compile time:
Javac Hard.java
Runtime:
Java FirstProgram
What happens at runtime?
At runtime, the following steps are performed:
To write the simple program, you need to open notepad by start menu -> All Programs -> Accessories
-> Notepad and write a simple program as we have shownbelow:
As displayed in the above diagram, write the simple program of Java in notepad and saved it as
Simple.java. In order to compile and run the above program, you need to open the command prompt
by start menu -> All Programs -> Accessories -> command prompt. When we have done with all the
steps properly, it shows the following output:
If you are saving the Java source file inside the JDK/bin directory, the path is not required to be set because all
the tools will be available in the current directory.
However, if you have your Java file outside the JDK/bin folder, it is necessary to set the path of JDK.
1. Temporary
2. Permanent
For Example:
set path=C:\Program Files\Java\jdk1.6.0_23\bin
o Go to MyComputer properties -> advanced tab -> environment variables -> new tab of user variable -> write path
in variable name -> write path of bin folder in variable value -> ok -> ok -> ok
For Example:
1) Go to MyComputer properties
2) Click on the advanced tab
3) Click on environment variables
8) Click on ok button
9) Click on ok button
Now your permanent path is set. You can now execute any program of java from any drive.
Difference between Pop(Procedure Oriented Programming)
and OOP(Object Oriented Programming)
Java definition: - Java is also an object-oriented, class-based, static, strong, robust, safe,
and high-level programming language. It was developed by James Gosling in 1995.
3 Approach It uses the top- It uses the It also uses the bottom-up approach.
down approach. bottom-up
approach.
5 Code The code is The code is The code is executed by the JVM.
Execution executed executed
directly. directly.
10 Source File The source file The source file The source file has a .java extension.
Extension has a .c has a .cpp
extension. extension.
11 Pointer It supports It also supports Java does not support the pointer
Concept pointer. pointer. concept because of security.
12 Union and It supports It also supports It does not support union and
Structure union and union and structure data types.
Datatype structure data structure data
types. types.
13 Pre-processor It uses pre- It uses pre- It does not use directives but uses
Directives processor processor packages.
directives such directives such
as #include, as #include,
#define, etc. #define,
#header, etc.
16 Memory It uses the It uses new and It uses a garbage collector to manage
Management calloc(), delete operator the memory.
malloc(), free(), to manage the
and realloc() memory.
methods to
manage the
memory.
20 Array Size An array should An array should An array can be declared without
be declared with be declared with declaring the size. For example, int num[].
size. For size.
example, int
num[10].
follows the concept of object. In other words, OOP is a way of writing programs based on the object concept.
(or)
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented
Example Program:-
Syntax:-
<class_name> <object_name>=new <class_name>();
(Or)
<class_name> <object_name>;
<object_name>=new <class_name>();
1. class Car
2. {
3. String color="red";
4. int weight=50;
5. int speed=100;
6. String model="1";
7. void startCar()
8. {
9. System.out.println("car Started");
10. }
11. void changeGear()
12. {
13. System.out.println("Gear Changed");
14. }
15. void slowDown()
16. {
17. System.out.println("Going slowly");
18. }
19. void brake()
20. {
21. System.out.println("Sudden Brake");
22. }
23. public static void main(String args[])// objects are always create in main method because
JVM is executed main method directly
24. {
25. Car bmw=new Car();
26. Car ferrari;
27. ferrari=new Car();
28. System.out.println(bmw.color);//calling variable
29. ferrari.color="block";//initializing a value through object
30. System.out.println(ferrari.color);
31. bmw.startCar();//calling method
32. ferrari.startCar();
33. }
34. }
35. Output:-
36. red
37. block
38. car Started
39. car Started
3.Abstraction:-
Definition:-Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
Another way, it shows only essential things to the user and hides the internal details, for example,
sending SMS where you type the text and send the message. You don't know the internal processing
about the message delivery.
Example 2:-
In Java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction using
interfaces.
The abstract method contains only method declaration but not implementation.
Example program:-
1. abstract class Simple{//abstract class
2. abstract public void withdraw();//abstract method
3. }
4. class Test extends Simple{
5. //if you extend abstract class definitely give the
6. //implementation of abstract method or put this Test class abstract class
7. public void withdraw()
8. {
9. System.out.println("Withdraw amount successfully");
10. }
11. public static void main(String args[])
12. {
13. Test t=new Test();
14. t.withdraw();
15. }
16. }
O/P:- Withdraw amount successfully
9. Encapsulation
Definition:- Binding (or Wrapping) code and data together into a single unit are known as encapsulation.
(or)
It is defined as the wrapping up of data under a single unit. It is the mechanism that binds together the code
and the data it manipulates. Another way to think about encapsulation is that it is a protective shield that
prevents the data from being accessed by the code outside this shield.
Technically, in encapsulation, the variables or the data in a class is hidden from any other class and can be
accessed only through any member function of the class in which they are declared.
In encapsulation, the data in a class is hidden from other classes, which is similar to what data-
hiding does. So, the terms “encapsulation” and “data-hiding” are used interchangeably.
Encapsulation can be achieved by declaring all the variables in a class as private and writing public
methods in the class to set and get the values of the variables.
Real world Example:-
Example Program:-
10. class EncapsulationEx{
11. private int a;
12. public int get()//Accessor Method
13. {
14. return a;
15. }
16. public void set(int a) //mutator method
17. {
18. this.a=a;
19. }
20. }
21. class Test{
22. public static void main(String args[]){
23. EncapsulationEx e=new EncapsulationEx();
24. e.set(10);
25. System.out.println(e.get());
26. }
27. }
O/p:-10
3. Inheritance
Definition:- When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance.
(or)
It is the mechanism in Java by which one class is allowed to inherit the features (fields and methods) of another
class. We are achieving inheritance by using extends keyword. Inheritance is also known as “is-a” relationship.
Let us discuss some frequently used important terminologies:
Superclass: The class whose features are inherited is known as superclass (also known as base or parent
class).
Subclass: The class that inherits the other class is known as subclass (also known as derived or extended
or child class). The subclass can add its own fields and methods in addition to the superclass fields and
methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and
there is already a class that includes some of the code that we want, we can derive our new class from the
existing class. By doing this, we are reusing the fields and methods of the existing class.
Real world Example:-
Example Program:-
1. class Mother
2. {
3. public void walk()
4. {
5. System.out.println("Walking Slowly");
6. }
7. }
8. class Daughter extends Mother //walk method inherited directly
9. {
10. public void eat()
11. {
12. System.out.println("Eating Slowly");
13. }
14. public static void main(String args[])
15. {
16. Daughter d=new Daughter();
17. d.walk();
18. d.eat();
19. }
20. }
Output:-
Walking Slowly
Eating Slowly
4.Polymorphism
Definition:- Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms.
So polymorphism means many forms.
There are two main types of polymorphism i.e. runtime polymorphism and compile-time polymorphism. Runtime
polymorphism (or) dynamic binding is achieved through method overriding , and compile-time polymorphism
(or) static binding is achieved through method overloading. Java doesn't support operator overloading.
Real Time Example:-
Example Program:-
Method Overloading :- If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
It is used to achieve Compile time polymorphism (or) static binding.
1. class MethodOverloadingEx
2. {
3. public void display()
4. {
5. int a=10;
6. System.out.println(a);
7. }
8. public void display(int a)
9. {
10. System.out.println(a);
11. }
12. public static void main(String args[])
13. {
14. MethodOverloadingEx m=new MethodOverloadingEx();
15. m.display();
16. m.display(20);
17. }
18. }
O/p:-
10
20
Method Overriding :- If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
It is used to achieve Run time polymorphism (or) dynamic binding.
1. class Mother{
2. public void walk()
3. {
4. System.out.println("Mother is Walking");
5. }
6. }
7. class Daughter extends Mother
8. {
9. public void walk()
10. {
11. System.out.println("Daughter is Walking");
12. }
13. public static void main(String args[])
14. {
15. Mother m=new Daughter();
16. m.walk();
17. }
18. }
O/p:- Daughter is Walking
2.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.
he 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.
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.
2) 2) Initially it was designed for small, embedded systems in electronic appliances like set-top boxes.
3) 3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) 4) After that, it was called Oak and was developed as a part of the Green project.
5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like the U.S.A., France,
Germany, Romania, etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
According to James Gosling, "Java was one of the top choices along with Silk". Since Java was so unique, most
of the team members preferred Java than other names.
8) Java is an island in Indonesia where the first coffee was produced (called Javacoffee). It is a kind of espresso
bean. Java name was chosen by James Gosling while having a cup of coffee nearby his office.
10) Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation)
and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 was released on January 23, 1996. After the first release of Java, there have been many additional
features added to the language. Now Java is being used in Windows applications, Web applications, enterprise
applications, mobile applications, cards, etc. Each new version adds new features in Java.
Since Java SE 8 release, the Oracle corporation follows a pattern in which every even version is release in March
month and an odd version released in September month.
3.Java buzzwords
A list of the most important features of the Java language is given below.
1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. High Performance
9. Distributed
10. Multithreaded
11. Dynamic
12. Interpreted
1)Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun Microsystem,
Java language is a simple programming language because:
o Java syntax is based on C and C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit pointers, operator
overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in
Java.
2)Object-oriented
OOP stands for Object-Oriented Programming. OOP is a programming paradigm in which every program is
follows the concept of object. In other words, OOP is a way of writing programs based on the object concept.
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
3)Platform Independent
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 code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is
compiled by the compiler and converted into byte code. This byte code is a platform-independent code because it can be
run on multiple platforms, i.e., Write Once and Run Anywhere (WORA).
4)Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which is used to load Java
classes into the Java Virtual Machine dynamically. It adds security by separating the package for the classes of the
local file system from those that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to objects.
o Security Manager: It determines what resources a class can access such as reading and writing to the local disk.
Java language provides these securities by default. Some security can also be provided by an application
developer explicitly through SSL(Secure socket layer), JAAS(java Authentication and authorization service),
Cryptography, etc.
5)Robust
The English mining of Robust is strong. Java is robust because:
6)Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for example, the size of
primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for
64-bit architecture. Java occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.
7)Portable
Java is portable because it facilitates you to carry the Java byte code to any platform. It doesn't require any
implementation.
8)High-performance
Java is faster than other traditional interpreted programming languages because Java byte code is "close" to native
code. It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted language that is why
it is slower than compiled languages, e.g., C, C++, etc.
9)Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI(remote method
invocation) and EJB(Enterprise java bean) 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.
10)Multi-threaded
A thread is like a separate program, executing concurrently. 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.
11)Dynamic
Java is a dynamic language. It supports the 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 supports dynamic compilation and automatic memory management (garbage collection).
12)Interpreted:-
Java is a interpreter language. It is convert byte code to executable code in jvm. It is design to
read the input source code and then translate the executable code instruction by instruction.
4.Data types
Data types specify the different sizes and values that can be stored in the variable.In java, data types are classified
into two types and they are as follows.
The following table provides more description of each primitive data type.
Let's look at the following example java program to illustrate primitive data types in java and their default values.
Example
public class PrimitiveDataTypes {
bytei;
shor j;
in k;
lon l;
float m;
double n;
charch;
boolean p;
System.out.println("i = " + obj.i + ", j = " + obj.j + ", k = " + obj.k + ", l = " + obj.l);
}
}
When we run the above example code, it produces the following output.
Example
public class NonPrimitiveDataTypes {
String str;
public static void main(String[] args) {
When we run the above example code, it produces the following output.
5.Variables
Defination:-A variable is a named memory location used to store a data value. A
variable can be defined as a container that holds a data value.A variable is assigned
with a data type.
In java, we use the following syntax to create variables.
Syntax
data_type variable_name;
(or)
data_type variable_name_1, variable_name_2,...;
(or)
data_type variable_name = value;
(or)
data_type variable_name_1 = value, variable_name_2 = value,...;
Let's look at the following example java program to illustrate instance variable in java.
public class InstanceVariables { //class Scope
int x = 100;// instance variable
public void show() {
System.out.println("Inside show method, x = " + x);
x = x + 100;
}
public void display() {
System.out.println("Inside display method, x = " + x);
}
public static void main(String[] args) {
InstanceVariables obj = new InstanceVariables();
obj.show();
obj.display();
}
}
OutPut:-
Inside show method, x = 100
Inside display method, x = 200
Static variables or Class variables
A static variable is a variable that declared using static keyword. The instance
variables can be static variables but local variables can not. Static variables are
initialized only once, at the start of the program execution. The static variable only has
one copy per class irrespective of how many objects we create.
The static variable is access by using class name.
Let's look at the following example java program to illustrate static variable in java.
Ex:-
public class StaticVariablesExample {int x=10, y=20; // Instance variables
static int z=30; // Static variable
public void show() {
int a; // Local variables
System.out.println("Inside show method,");
System.out.println("x = " + x + ", y = " + y + ", z = " + z);
}
public static void main(String[] args) {
StaticVariablesExample obj = new
StaticVariablesExample();
System.out.println(obj.x);
System.out.println(obj.y);
System.out.println(StaticVariablesExample.z);
obj.show();
}
}
Output:-10
20
30
Inside show method,
x = 10, y = 20, z = 30
Final variables
A final variable is a variable that declared using final keyword. The final variable is
initialized only once, and does not allow any method to change it's value again. The
variable created using final keyword acts as constant. All variables like local, instance,
and static variables can be final variables.
Let's look at the following example java program to illustrate final variable in java.
Ex:-
public class Student
{
final int id=10;
void show()
{
System.out.println(id);
id=20;//final variable can’t modify
}
public static void main(String args[]){
Student s1=new Student();
s1.show();
//System.out.println(s1.id);//printing members with a white space }
}
Output:-10
Scope of a Variable
A variable can be declared and defined inside a class, method, or block. It defines the
scope of the variable where a variable is available to use. i.e. the visibility or
accessibility of a variable. Variable declared inside a block or method are not visible to
outside. If we try to do so, we will get a compilation error.
Example:-
class DemoScope
{ //class scope
public static void main(String args[])
{ //main method scope
int x;
x=10;
if(x==10)
{ //condition scope
int y=20;
System.out.println("X and Y:"+x+" "+y);
x=y*2;
}
//y=100;//get compilation error
System.out.println("X is:"+x);}
}
Life Time of a Variable:
The lifetime of a variable is the time during which the variable stays in memory
and is therefore accessible during program execution. The variables that are
local to a method are created the moment the method is activated and are
destroyed when the activation of the method terminates.
Ex:-
class DemoLifeTime
{
public static void main(String args[])
{
int x;
for(x=0;x<3;x++)
{
int y=-1;
System.out.println("Y is"+y);
y=20;
System.out.println("Y is "+y);
}// After loop completion y is destroyed no longer can use
}
}
7.Arrays
Java Arrays
Defination:-Array is a collection of similar type of elements which has contiguous memory location.
An array is a collection of similar data values with a single name. An array can also be defined
as, a special type of variable that holds multiple values of the same data type at a time.
In java, arrays are objects and they are created dynamically using new operator.
Every array in java is organized using index values. The index value of an array starts with '0' and ends
with 'size-1'. We use the index value to access individual elements of an array.
In java, there are two types of arrays and they are as follows.
1. One Dimensional Array (or) Single Dimensional Array
2. Multi Dimensional Array
Creating an array
Syntax
data_type array_name[ ] = new data_type[size];(or)
data_type[ ] array_name = new data_type[size];
Let's look at the following example program.
Example
public class ArrayExample {
public static void main(String[] args) {
int list[] = new int[5];
list[0] = 10;
System.out.println("Value at index 0 - " + list[0]);
System.out.println("Length of the array - " + list.length);
}
}
Output:-
When we run the above example code, it produces the following output. In java, an array can also be initialized
at the time of its declaration. When an array is initialized at the time of its declaration, it need not specify the
size of the array and use of the new operator.
Here, the size is automatically decided based on the number of values that are initialized.
Syntax:-
Datatype arrayname[]={value1, value2, value3,…..etc.,);
Example
int list[ ] = {10, 20, 30, 40, 50};
Example
public class ArrayExample {
public static void main(String[] args) {
short list[] = null;list[0] = 10;
System.out.println("Value at index 0 - " + list[0]);
}
}
When we run the above example code, it produces the following output.
Example
public class ArrayExample {public static void main(String[] args) {
short list[] = {10, 20, 30};
list[4] = 10;
System.out.println("Value at index 0 - " + list[0]);
}
}
When we run the above example code, it produces the following output.
Looping through an array
An entire array is accessed using either simple for statement or for-each statement. Look at the following
example program to display sum of all the elements in a list.
Example
import java.util.Scanner;
public class ArrayExample {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int size, sum = 0;
System.out.print("Enter the size of the list: ");
size = read.nextInt();
short list[] = new short[size];
System.out.println("Enter any " + size + " numbers: ");
for(int i = 0; i < size; i++) // Simple for statement
list[i] = read.nextShort();
for(int i : list) // for-each statement
sum = sum + i;
System.out.println("Sum of all elements: " + sum);
}
}
When we run the above example code, it produces the following output.
2. Multidimensional Array
2.1 Two Dimensional Array:-
In java, we can create an array with multiple dimensions. We can create 2-dimensional, 3- dimensional, or any
dimensional array.
In Java, multidimensional arrays are arrays of arrays. To create a multidimensional array variable, specify each
additional index using another set of square brackets. We use the following syntax to create two-dimensional
array.
Syntax to Declare Multidimensional Array in Java
1. dataType[][] arrayRefVar; (or)
2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in Java
Syntax
data_type array_name[ ][ ] = new data_type[rows][columns];
(or)
data_type[ ][ ] array_name = new data_type[rows][columns];
When we create a two-dimensional array, it created with a separate index for rows and columns.
The individual element is accessed using the respective row index followed by the column index. A
multidimensional array can be initialized while it has created using the following syntax.
Syntax
data_type array_name[ ][ ] = {{value1, value2}, {value3, value4}, {value5, value6},...};
When an array is initialized at the time of declaration, it need not specify the size of the array and use of the
new operator. Here, the size is automatically decided based on the number of values that are initialized.
Example
int[][] arr=new int[3][3];//3 row and 3 column
int matrix_a[ ][ ] = {{1, 2},{3, 4},{5, 6}};
The above statement creates a two-dimensional array of three rows and two columns.
Example Program:-
public class Multidimensional {
public static void main(String args[])
{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}Out Put:-
123
245
445
Syntax:-
Data_type array_name[][]=new data_type[n][];\\ n means number
of rows
array_name[]=new datatype[n1];\\n1 means number of columns
(or)
Int arr_name[][]={{value1,value2},{value1,value2,value3}};
Ex:-
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
Example Program:-
class TestJaggedArray{
public static void main(String[] args){
//declaring a 2D array with odd columns
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
//initializing a jagged array
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
//printing the data of a jagged array
for (int i=0; i<arr.length; i++){
for (int j=0; j<arr[i].length; j++){
System.out.print(arr[i][j]+" "); }
System.out.println();//new line
}
}
}
Out Put:-
012
3456
78
Addition of 2 Matrices in Java
Let's see a simple example that adds two matrices.
//Java Program to demonstrate the addition of two matrices in Java
class Testarray5{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}}
Output:
268
6 8 10
Output:
6 6 6
12 12 12
18 18 18
Example:-
int[ ][ ][ ] x = new int[2][3][4];
For example:
x[0][0][0] refers to the data in the first table, first row, and first column.
x[1][0][0] refers to the data in the second table, first row, and first column.
x[1][2][3] refers to the data in the second table, thrid row, and fourth
column.
Example program:-
package arraysProgram;
public class ThreeDArray {
public static void main(String[] args)
{
int[ ][ ][ ] x;
x = new int[3][3][3];
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
for(int k = 0; k < 3; k++)
x[i][j][k] = i + 1;
}
for(int i = 0; i < 3; i++)
{
System.out.println("Table-" +(i + 1));
for(int j = 0; j < 3; j++)
{
for(int k = 0; k < 3; k++)
System.out.print(x[i][j][k] +" ");System.out.println();
}
System.out.println();
}
}
}
Out Put:-
Table-1
111
111
111
Table-2
222
222
222
Table-3
333
333
333
8.Operators
An Operator is a symbol that performs an operation. An operator acts on some variables, called operands to
get the desired result, For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Bitwise Operator,
o Assignment Operator,
o Relational Operator,
o Logical Operator,
o Ternary Operator and
o Special Operator.
1.Unary Operator: -
The Java unary operators require only one operand. Unary operators are used to perform various operations.
Logical or boolean !
Example:-
class UnaryOperator
{
public static void main(String args[])
{
int a=10,b=-5,d=10;
boolean c=true;
System.out.println(a);//10
System.out.println(a++);//10(11)
System.out.println(++a);//12
System.out.println(a--);//12(11)
System.out.println(--a);//10
System.out.println(~d);//-11
System.out.println(~b);//4
System.out.println(!c);//false
System.out.println(!c);//false
}
}
2.Arithmetic Operators:
In java, arithmetic operators are used to performing basic mathematical operations like addition, subtraction,
multiplication, division, modulus, increment, decrement, etc.,
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
Example:-
Ex:-
public class BitwiseOperator{
public static void main(String args[]){
int a=5;
int b=6;
int c=2;
int d=-2;
System.out.println(a&b);//4
System.out.println(a|b);//7
System.out.println(a^b);//3
System.out.println(a<<c);//20 5*2^2=5*4=20
System.out.println(a>>c);//1 5/2^2=5/4=1
System.out.println(d>>c);-1
System.out.println(a>>>c);//1
System.out.println(d>>>c);//1073741823
}
}
Assignment Operator:-
The operator is used to store some value into a variable .
The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand side variable (Lvalue).
The assignment operator is used in different variants along with arithmetic operators. The following table
describes all the assignment operators in the java programming language.
Assignment operator
+= Add both left and right-hand side values and store the result into left-hand side variable A += 10
-= Subtract right-hand side value from left-hand side variable value and store the result into left- A -= B
hand side variable
/= Divide left-hand side variable value with right-hand side variable value and store the result A /= B
into the left-hand side variable
division
%= Divide left-hand side variable value with right-hand side variable value and store the A %= B
remainder into the left-hand side variable
modulus
|= Logical OR assignment -
Ex:-
public class UnaryOperator{
public static void main(String args[]){
int a=10,b=10;
System.out.println(a+=b);//20
System.out.println(a-=b);//10
System.out.println(a*=b);//100
System.out.println(a/=b);//10
System.out.println(a%=b);//0
System.out.println(a&=b);//0
System.out.println(a|=b);10
System.out.println(a^=b);0
}
}
< Returns TRUE if the first value is smaller than second value otherwise returns FALSE 10 < 5 is FALSE
> Returns TRUE if the first value is larger than second value otherwise returns FALSE 10 > 5 is TRUE
<= Returns TRUE if the first value is smaller than or equal to second value otherwise 10 <= 5 is
returns FALSE FALSE
>= Returns TRUE if the first value is larger than or equal to second value otherwise 10 >= 5 is TRUE
returns FALSE
!= Returns TRUE if both values are not equal otherwise returns FALSE 10 != 5 is TRUE
Logical Operators
The logical operators are the symbols that are used to combine multiple conditions into one condition. The
following table provides information about logical operators.
& Logical AND - Returns TRUE if all conditions are TRUE otherwise returns FALSE false & true =>
false
| Logical OR - Returns FALSE if all conditions are FALSE otherwise returns TRUE false | true =>
true
^ Logical XOR - Returns FALSE if all conditions are same otherwise returns TRUE true ^ true =>
false
! Logical NOT - Returns TRUE if condition is FLASE and returns FALSE if it is !false => true
TRUE
&& short-circuit AND - Similar to Logical AND (&), but once a decision is finalized it false & true =>
does not evaluate remianing. false
|| short-circuit OR - Similar to Logical OR (|), but once a decision is finalized it does not false | true =>
evaluate remianing. true
��� The operators &, |, and ^ can be used with both boolean and integer data type values. When they are used
with integers, performs bitwise operations and with boolean, performs logical operations.
��� Logical operators and Short-circuit operators both are similar, but in case of short-circuit operators once
the decision is finalized it does not evaluate remaining expressions.
Ex:-
class Test4
{
public static void main(String args[])
{
int a=10,b=20;
System.out.println(a>b & a<b);//false
System.out.println(a>b && a<b);//false
System.out.println(a>b | a<b);//true
System.out.println(a>b || a<b);//true
System.out.println(a>b ^ a<b);//true
System.out.println(!(a>b));//true
}
}
Conditional or Ternary Operator:-
The Ternary operator is a conditional operator that decreases the length of code while performing comparisons and
conditionals. This method is an alternative for using if-else and nested if-else statements. The order of execution for this
operator is from left to right.
Ex:-
class Test4
{
public static void main(String args[])
{
int a=10,b=20;
int max=a>b?a:b;
System.out.println(max);
}
}
Special Operators:-
1.instanceof operator
2.Member or Dot Operator
3.Cast Operator
1.Instanceof: This operator allows us to determine that the object belongs to a particular class or
not.Ex: Person instanceof Student (Object instanceof Class)2. . (Dot) Operator: This operator
is used to access the instance variables and the methods of class objectsEx: Person.age;
Person.getdata();
3.Cast Operator:- Cast operator is used to convert one data type to other.
class Test4
{
double b=20;
int a=(int)b;
public static void main(String args[])
{
Test4 t=new Test4();
System.out.println(t instanceof Test4);
System.out.println(t.b);
System.out.println(t.a);
}
}
9. Expressions
In any programming language, if we want to perform any calculation or to frame any condition etc., we use a set
of symbols to perform the task. These set of symbols makes an expression.In the java programming language, an
expression is defined as follows.
An expression is a collection of operators and operands that represents a specific value.
In the above definition, an operator is a symbol that performs tasks like arithmetic operations, logical
operations, and conditional operations, etc.
Operands are the values on which the operators perform the task. Here operand can be a direct value or
variable or address of memory location.
Expression Types
In the java programming language, expressions are divided into THREE types. They are as follows.
Infix Expression
Postfix Expression
Prefix Expression
Infix Expression
The expression in which the operator is used between operands is called infix expression.
The infix expression has the following general structure.
Example
Postfix Expression
The expression in which the operator is used after operands is called postfix expression.
The postfix expression has the following general structure.
Example
Prefix Expression
The expression in which the operator is used before operands is called a prefix expression.
The prefix expression has the following general structure.
Example
10.Control statements
Java Control Statements
In java, the default execution flow of a program is a sequential order. But the sequential order of execution flow
may not be suitable for all situations. Sometimes, we may want to jump from line to another line, we may want
to skip a part of the program, or sometimes we may want to execute a part of the program again and again. To
solve this problem, java provides control statements.
In java, the control statements are the statements which will tell us that in which order the instructions are getting
executed. The control statements are used to control the order of execution according to our requirements. Java
provides several control statements, and they are classified as follows.
if statement in java
In java, we use the if statement to test a condition and decide the execution of a block of statements based on that
condition result. The if statement checks, the given condition then decides the execution of a block of statements.
If the condition is True, then the block of statements is executed and if it is False, then the block of statements is
ignored. The syntax and execution flow of if the statement is as follows.
Java Program
import java.util.Scanner;
if((num % 5) == 0) {
System.out.println("We are inside the if-block!");
System.out.println("Given number is divisible by 5!!");
}
System.out.println("We are outside the if-block!!!");
In the above execution, the number 12 is not divisible by 5. So, the condition becomes False and the condition
is evaluated to False. Then the if statement ignores the execution of its block of statements.
When we enter a number which is divisible by 5, then it produces the output as follows.
if-else statement in java
In java, we use the if-else statement to test a condition and pick the execution of a block of statements out
of two blocks based on that condition result. The if-else statement checks the given condition then decides
which block of statements to be executed based on the condition result. If the condition is True, then the
true block of statements is executed and if it is False, then the false block of statements is executed. The
syntax and execution flow of if-else statement is as follows.
Java Program
import java.util.Scanner;
if((num % 2) == 0) {
System.out.println("We are inside the true-block!");
System.out.println("Given number is EVEN number!!");
}
else {
System.out.println("We are inside the false-block!");
System.out.println("Given number is ODD number!!");
}
Java Program
import java.util.Scanner;
}
When we run this code, it produce the following output.
Syntax
if(condition_1){
condition_1 true-block;
...
}
else if(condition_2){
condition_2 true-block;
condition_1 false-block too;
...
}
Java Program
import java.util.Scanner;
public class IfElseIfStatementTest {
else
The switch statement contains multiple blocks of code called cases and a single case is executed based on the variable
which is being switched.
switch( value )
{
case 0: System.out.println("ZERO") ; break ;
case 1: System.out.println("ONE") ; break ;
case 2: System.out.println("TWO") ; break ;
case 3: System.out.println("THREE") ; break ;
case 4: System.out.println("FOUR") ; break ;
case 5: System.out.println("FIVE") ; break ;
case 6: System.out.println("SIX") ; break ;
case 7: System.out.println("SEVEN") ; break ;
case 8: System.out.println("EIGHT") ; break ;
case 9: System.out.println("NINE") ; break ;
default: System.out.println("Not a Digit") ;
}
while statement
do-while statement
for statement
for-each statement
Java Program
ipublic class WhileTest {
int num = 1;
Java Program
public class DoWhileTest {
do {
System.out.println(num);
num++;
}while(num <= 10);
Java Program
public class ForTest {
The for-each statement has the following syntax and execution flow diagram.
Let's look at the following example java code.
Java Program
public class ForEachTest {
for(int i : arrayList) {
System.out.println("i = " + i);
}
break
continue
return
The floowing picture depictes the execution flow of the break statement.
Let's look at the following example java code.
Java Program
public class JavaBreakStatement {
for(int i : list) {
if(i == 30)
break;
System.out.println(i);
}
Java Program
public class JavaContinueStatement {
for(int i : list) {
if(i == 30)
continue;
System.out.println(i);
}
Java Program
import java.util.Scanner;
verify: if (value % 2 == 0) {
System.out.println("\nYou won!!!");
System.out.println("Your score is " + (4-i)*10 + " out of 30.");
break reading;
} else {
System.out.println("\nSorry try again!!!");
System.out.println("You let with " + (3-i) + " more options...");
continue reading;
}
}
}
}
In java, the return statement used with both methods with and without return type. In the case of a method with
the return type, the return statement is mandatory, and it is optional for a method without return type.
When a return statement used with a return type, it carries a value of return type. But, when it is used without a
return type, it does not carry any value. Instead, simply transfers the execution control.
Let's look at the following example java code.
Java Program
import java.util.Scanner;
public class JavaReturnStatementExample {
int value;
int readValue() {
Scanner read = new Scanner(System.in);
obj.showValue(obj.readValue());
}
}
Double->float->long->int->char->short->byte
Syntax:
Target_datatype: It is the data type in which we want to convert the destination data type. The variable defines
a value that is to be converted in the target_data type. Let's understand the concept of type casting with an
example.
Suppose, we want to convert the float data type into int data type. Here, the target data type is smaller than the
source data because the size of int is 4 bytes, and the size of the float data type is 8 bytes. And when we change
it, the value of the float variable is truncated and convert into an integer variable. Casting can be done with a
compatible and non-compatible data type.
1. float b = 3.0;
2. int a = (int) b; // converting a float value into integer
AreaOfRectangle.java
() is Cast operator
Datatype variable=(target-type)variable;
Java Variable example:Narrowing (typecasting)
Class Simple
{
Public static void main(String args[])
{
float f=10.5f;
Int a=(int)f;
System.out.println(a);
System.out.println(f);
}
}
o/p:-
10.5
10
Byte->short->char->int->long->float->double
Suppose, we have an int data type and want to convert it into a float data type. These are data types compatible
with each other because their types are numeric, and the size of int is 4 bytes which is smaller than float data
type. Hence, the compiler automatically converts the data types without losing or truncating the values.
1. int a = 20;
2. Float b;
3. b = a; // Now the value of variable b is 20.000 /* It defines the conversion of int data type to float data type without losin
g the information. */
In the above example, the int data type is converted into the float, which has a larger size than int, and hence it
widens the source data type.
Class Simple
{
Public static void main(String args[])
{
Int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
}
}
o/p:
10
10.0
Note:
1.For widening conversions,the numeric types,including integer and floating-point types are compatible with each other.
2.No automatic conversions from the numeric types to char or Boolean. also, char and Boolean are not compatible with
each other.
1 Type casting is a mechanism in which one data Type conversion allows a compiler to convert one data type
type is converted to another data type using a to another data type at the compile time of a program or code.
casting () operator by a programmer.
2 It can be used both compatible data type and Type conversion is only used with compatible data types, and
incompatible data type. hence it does not require any casting operator.
3 It requires a programmer to manually casting one It does not require any programmer intervention to convert
data into another type. one data type to another because the compiler automatically
compiles it at the run time of a program.
4 It is used while designing a program by the It is used or take place at the compile time of a program.
programmer.
5 When casting one data type to another, the When converting one data type to another, the destination
destination data type must be smaller than the type should be greater than the source data type.
source data.
6 It is also known as narrowing conversion because It is also known as widening conversion because one smaller
one larger data type converts to a smaller data data type converts to a larger data type.
type.
8 There is a possibility of data or information being In type conversion, data is unlikely to be lost when
lost in type casting. converting from a small to a large data type.
Example:-
1. class FibonacciExample1{
2. public static void main(String args[])
3. {
4. int n1=0,n2=1,n3,i,count=10;
5. System.out.print(n1+" "+n2);//printing 0 and 1
6.
7. for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are already printed
8. {
9. n3=n1+n2;
10. System.out.print(" "+n3);
11. n1=n2;
12. n2=n3;
13. }
14.
15. }}
Output:-
0 1 1 2 3 5 8 13 21 34
In the above array, the first duplicate will be found at the index 4 which is the duplicate of the element (2) present
at index 1. So, duplicate elements in the above array are 2, 3 and 8.
Output:-
Output:-
Duplicate elements in given array:
2
3
8
To solve this problem, First of all, we need to convert every upper-case character in the string to lower-case so
that the comparisons can be done with the lower-case vowels only not upper-case vowels, i.e.(A, E, I, O, U).
Then, we have to traverse the string using a for or while loop and match each character with all the vowels, i.e.,
a, e, i, o, u. If the match is found, increase the value of count by 1 otherwise continue with the normal flow of the
program.
Example:-
1. public class CountVowelConsonant {
2. public static void main(String[] args) {
3.
4. //Counter variable to store the count of vowels and consonant
5. int vCount = 0, cCount = 0;
6.
7. //Declare a string
8. String str = "This is a really simple sentence";
9.
10. //Converting entire string to lower case to reduce the comparisons
11. str = str.toLowerCase();
12.
13. for(int i = 0; i < str.length(); i++) {
14. //Checks whether a character is a vowel
15. if(str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u')
{
16. //Increments the vowel counter
17. vCount++;
18. }
19. //Checks whether a character is a consonant
20. else if(str.charAt(i) >= 'a' && str.charAt(i)<='z') {
21. //Increments the consonant counter
22. cCount++;
23. }
24. }
25. System.out.println("Number of vowels: " + vCount);
26. System.out.println("Number of consonants: " + cCount);
27. }
28. }
Output:-
Number of vowels: 10
Number of consonants: 17
13.Concepts of Classes:-
Definition: - A class is a template or blueprint from which you can create an individual
object. Class doesn’t consume any space. It is logical entity.
Ex:-Car
Example Program:-
New:-
The new keyword is used to allocate memory at runtime. All objects get memory in heap memory area.
Syntax:-
<class_name> <object_name>=new <class_name>();
(Or)
<class_name> <object_name>;
<object_name>=new <class_name>();
class Car
{
String color="red";
int weight=50;
int speed=100;
String model="1";
void startCar()
{
System.out.println("car Started");
}
void changeGear()
{
System.out.println("Gear Changed");
}
void slowDown()
{
System.out.println("Going slowly");
}
void brake()
{
System.out.println("Sudden Brake");
}
public static void main(String args[])// objects are always create in main method because JVM is
executed main method directly
{
Car bmw=new Car();
Car ferrari;
ferrari=new Car();
System.out.println(bmw.color);//calling variable
ferrari.color="block";//initializing a value through object
System.out.println(ferrari.color);
bmw.startCar();//calling method
ferrari.startCar();
}
}
Output:-
red
block
car Started
car Started
15.Constructors
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created.
At the time of calling constructor, memory for the object is allocated in the memory.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides
a default constructor by default.
Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to
write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have
any.
Output:
Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a default constructor.
The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type.
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.
Java Parameterized Constructor
A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of the
class with our own values, then use a parameterized constructor.
Why use the parameterized constructor?
The parameterized constructor is used to provide different values to distinct objects. However, you can provide
the same values also.
Output:
111 Karan
222 Aryan
3.Copy Constructor
Unlike other constructors copy constructor is passed with another object which copies the data available from
the passed object to the newly created object.
1. import java.io.*;
2. class Geek {
3. // data members of the class.
4. String name;
5. int id;
6. // Parameterized Constructor
7. Geek(String name, int id)
8. {
9. this.name = name;
10. this.id = id;
11. }
26. System.out.println();
First Object
GeekName :avinash and GeekId :68
Constructor overloading in Java is a technique of having more than one constructor with different parameter lists.
They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler
by the number of parameters in the list and their types.
Example of Constructor Overloading
1. //Java program to overload constructors
2. class Student5{
3. int id;
4. String name;
5. int age;
6. //creating two arg constructor
7. Student5(int i,String n){
8. id = i;
9. name = n;
10. }
11. //creating three arg constructor
12. Student5(int i,String n,int a){
13. id = i;
14. name = n;
15. age=a;
16. }
17. void display(){System.out.println(id+" "+name+" "+age);}
18.
19. public static void main(String args[]){
20. Student5 s1 = new Student5(111,"Karan");
21. Student5 s2 = new Student5(222,"Aryan",25);
22. s1.display();
23. s2.display();
24. }
25. }
Test it Now
Output:
111 Karan 0
222 Aryan 25
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 don't have The method is not provided by the compiler
any constructor in a class. in any case.
The constructor name must be same as the class name. The method name may or may not be same as
the class name.
16.Methods
What is a method in Java?
A method is a block of code or collection of statements or a set of code grouped together to perform a certain
task or operation. It is used to achieve the reusability of code. We write a method once and use it many times.
We do not require to write code again and again. It also provides the easy modification and readability of code,
just by adding or removing a chunk of code. The method is executed only when we call or invoke it.
Method Signature: Every method has a method signature. It is a part of the method declaration. It includes
the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility of the
method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our application.
o Private: When we use a private access specifier, the method is accessible only in the classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within the same package or subclasses
in a different package.
o Default: When we do not use any access specifier in the method declaration, Java uses default access specifier by
default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data type, object,
collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be corresponding to the
functionality of the method. Suppose, if we are creating a method for subtraction of two numbers, the method
name must be subtraction(). A method is invoked by its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses. It
contains the data type and variable name. If the method has no parameter, left the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is enclosed
within the pair of curly braces.
Naming a Method
While defining a method, remember that the method name must be a verb and start with a lowercase letter. If
the method name has more than two words, the first name must be a verb followed by adjective or noun. In the
multi-word method name, the first letter of each word must be in uppercase except the first word. For example:
Single-word method name: sum(), area()
It is also possible that a method has the same name as another method name in the same class, it is known
as method overloading.
Types of Method
There are two types of methods in Java:
o Predefined Method
o User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries is known as
predefined methods. It is also known as the standard library method or built-in method. We can directly use
these methods just by calling them in the program at any point. Some pre-defined methods are length(), equals(),
compareTo(), sqrt(), etc. When we call any of the predefined methods in our program, a series of codes related
to the corresponding method runs in the background that is already stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is defined in
the java.io.PrintStream class. It prints the statement that we write inside the method. For
example, print("Java"), it prints Java on the console.
Demo.java
Output:
In the above example, we have used three predefined methods main(), print(), and max(). We have used these
methods directly without declaration because they are predefined. The print() method is a method
of PrintStream class that prints the result on the console. The max() method is a method of the Math class that
returns the greater of two numbers.
In the above method signature, we see that the method signature has access specifier public, non-access
modifier static, return type int, method name max(), parameter list (int a, int b). In the above example, instead
of defining the method, we have just invoked the method. This is the advantage of a predefined method. It makes
programming less complicated.
Similarly, we can also see the method signature of the print() method.
User-defined Method
The method written by the user or programmer is known as a user-defined method. These methods are modified
according to the requirement.
The method of the class is known as an instance method. It is a non-static method defined in the class. Before
calling or invoking the instance method, it is necessary to create an object of its class. Let's see an example of an
instance method.
Let's create a user defined method that checks the number is even or odd. First, we will define the method.
We have defined the above method named findevenodd(). It has a parameter num of type int. The method does
not return any value that's why we have used void. The method body contains the steps to check the number is
even or odd. If the number is even, it prints the number is even, else prints the number is odd.
Once we have defined a method, it should be called. The calling of a method in a program is simple. When we
call or invoke a user-defined method, the program control transfer to the called method.
1. import java.util.Scanner;
2. public class EvenOdd
3. {
4. public static void main (String args[])
5. {
6. //creating Scanner class object
7. Scanner scan=new Scanner(System.in);
8. System.out.print("Enter the number: ");
9. //reading value from the user
10. int num=scan.nextInt();
11. //method calling
12. findEvenOdd(num);
13. }
In the above code snippet, as soon as the compiler reaches at line findEvenOdd(num), the control transfer to the
method and gives the output accordingly.
Let's combine both snippets of codes in a single program and execute it.
EvenOdd.java
1. import java.util.Scanner;
2. public class EvenOdd
3. {
4. public static void main (String args[])
5. {
6. EvenOdd e=new EvenOdd ();
7. //creating Scanner class object
8. Scanner scan=new Scanner(System.in);
9. System.out.print("Enter the number: ");
10. //reading value from user
11. int num=scan.nextInt();
12. //method calling
13. e.findEvenOdd(num);
14. }
15. //user defined method
16. public void findEvenOdd(int num)
17. {
18. //method body
19. if(num%2==0)
20. System.out.println(num+" is even");
21. else
22. System.out.println(num+" is odd");
23. }
24. }
Output 1:
Output 2:
Let's see another program that return a value to the calling method.
In the following program, we have defined a method named add() that sum up the two numbers. It has two
parameters n1 and n2 of integer type. The values of n1 and n2 correspond to the value of a and b, respectively.
Therefore, the method adds the value of a and b and store it in the variable s and returns the sum.
Addition.java
Output:
o Accessor Method
o Mutator Method
Accessor Method: The method(s) that reads the instance variable(s) is known as the accessor method. We can
easily identify it because the method is prefixed with the word get. It is also known as getters. It returns the value
of the private field. It is used to get the value of the private field.
Example
Mutator Method: The method(s) read the instance variable(s) and also modify the values. We can easily identify
it because the method is prefixed with the word set. It is also known as setters or modifiers. It does not return
anything. It accepts a parameter of the same data type that depends on the field. It is used to set the value of the
private field.
Example
Student.java
1. class Student
2. {
3. private int roll;
4. public int getRoll() //accessor method
5. {
6. return roll;
7. }
8. public void setRoll(int roll) //mutator method
9. {
10. this.roll = roll;
11. }
12. public static void main(String args[])
13. {
14. Student s=new Student();
15. s.setRoll(10);
16. System.out.println(s.getRoll());
17. }
18. }
OutPut:-
10
Static Method
A method that has static keyword is known as static method. In other words, a method that belongs to a class
rather than an instance of a class is known as a static method. We can also create a static method by using the
keyword static before the method name.
The main advantage of a static method is that we can call it without creating an object. It can access static data
members and also change the value of it. It is used to create an instance method. It is invoked by using the class
name. The best example of a static method is the main() method.
Display.java
Output:
Syntax
Demo.java
Output:
Abstract method...
17.Access control
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can
change the access level of fields, constructors, methods, and class by applying the access modifier on it.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
18.This keyword
‘this’ is a reference variable that refers to the current object, or can be said “this” in Java is a keyword that
refers to the current object instance. It can be used to call current class methods and fields, to pass an instance
of the current class as a parameter, and to differentiate between the local and instance variables. Using “this”
reference can improve code readability and reduce naming conflicts.
1. class A5{
2. void m(){
3. System.out.println(this);//prints same reference ID
4. }
5. public static void main(String args[]){
6. A5 obj=new A5();
7. System.out.println(obj);//prints the reference ID
8. obj.m();
9. }
10. }
Test it Now
Output:
A5@22b3ea59
A5@22b3ea59
Let's understand the problem if we don't use this keyword by the example given below:
1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. rollno=rollno;
7. name=name;
8. fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12. class TestThis1{
13. public static void main(String args[]){
14. Student s1=new Student(111,"ankit",5000f);
15. s1.display();
16. }}
Test it Now
Output:
0 null 0.0
In the above example, parameters (formal arguments) and instance variables are same. So, we are using this
keyword to distinguish local variable and instance variable.
Solution of the above problem by this keyword(write on exam this example program only)
1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. this.rollno=rollno;
7. this.name=name;
8. this.fee=fee;
9. }
10.
11. class TestThis2{
12. public static void main(String args[]){
13. Student s1=new Student(111,"ankit",5000f);
14. s1.display();
15. }}
Test it Now
Output:
If local variables(formal arguments) and instance variables are different, there is no need to use this keyword like
in the following program:
Output:
this keyword can be used inside the method in order to call another method from same class. Below example
demonstrates the same.
1. class Simple{
2. int a=10;
3. void m1(Simple s1)
4. {
5. System.out.println(s1.a);
6. }
7. void m2()
8. {
9.
//Simple s=new Simple();
//m1(Simple s2);
10. m1(this);
11. System.out.println("hello");
12. }
13. public static void main(String args[])
14. {
15. //int a=10;
16. Simple s=new Simple();
17. s.m2();
18. }
19. }
Output:-
10
Hello
class Simple{
int m1()
{
int a=10;
return a;
}
float m2()
{
float b=2.5f;
return b;
}
Simple m3()
{
//Simple s3=new Simple();
//return s3;
return this;
}
public static void main(String args[])
{
//int a=10;
Simple s=new Simple();
System.out.println(s.m1());
System.out.println(s.m2());
System.out.println(s.m3());
}
}
Output:-
10
2.5
practice.Simple@19e0bfd
1. class Test {
2. int a;
3. int b;
4. // Default constructor
5. Test()
6. {
7. this(10, 20);//calling parameterized constructor
8. System.out.println("Inside default constructor \n");
9. }
1. class Simple{
2. Simple()
3. {
// Simple s2=new Simple();
// Test t=new Test(s2);
4.
Test t=new Test(this);
System.out.println(this);
5. }
6. public static void main(String args[])
7. {
8. }
9. }
10. class Test{
11. Simple obj;
12. Test(Simple s1)
13. {
obj=s1;
System.out.println(obj);
14. }
15. }
Output:-
Simple@19e0bfd
Simple@19e0bfd
Garbage collection
In java, garbage means unreferenced objects
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it
is a way to destroy the unused objects.
To achieve this we can use
free() function in C language and Delete() in C++
But, in java it is performed automatically. So, java provides better memory management.
Finalize() method
It is invoked each time before the object is garbage collected.
This method can be used to perform cleanup processing.
This method is defined in Object class as
Protected void finalize(){}
gc() method
It is used to invoke the garbage collector to perform cleanup processing.
The gc() is found in System and Runtime classes.
It is static method which is used to call finalize before destroying the object.
public static void gc(){}
Example Program:-
class Animal
{
Animal(){
System.out.println("Object is created");
}
protected void finalize()
{
System.out.println("Object is destroyed");
}
}
class AnimalDemo
{
public static void main(String args[])
{
Animal a=new Animal();
a=null;//1.By assigning a null
Animal a1=new Animal();
Animal a2=new Animal();
a1=a2;//2. By assigning reference to another
new Animal();//By anonymous object
System.gc();
}
}
Output:-
Object is created
Object is created
Object is created
Object is created
Object is destroyed
Object is destroyed
Object is destroyed
20.Overloading methods
Defination:-
If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.
Note:- 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
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. }}
Test it Now
Output:
22
24.9
21.Parameter passing
There are different ways in which parameter data can be passed into and out of methods and
functions. Let us assume that a function B() is called from another function A(). In this case A is
called the “caller function” and B is called the “called function or callee function”. Also, the
arguments which A sends to B are called actual arguments and the parameters of B are called formal
arguments.
Types of parameters:
Formal Parameter: A variable and its type as they appear in the prototype of the function or
method.
Syntax:
function_name(datatype variable_name)
Actual Parameter: The variable or expression corresponding to a formal parameter that appears in
the function or method call in the calling environment.
Syntax:
func_name(variable name(s));
1.Pass by Value (or) call by value: In the pass by value concept, the method is called by passing a value. So, it is called
pass by value. It does not affect the original parameter.
In case of call by value original value is not changed.
Example:-
1. class Operation{
2. int data=50;
3.
4. void change(int data){
5. data=data+100;//changes will be in the local variable only
6. }
7.
8. public static void main(String args[]){
9. Operation op=new Operation();
10.
11. System.out.println("before change "+op.data);
12. op.change(500);
13. System.out.println("after change "+op.data);
14.
15. }
16. }
Output:
before change 50
after change 50
2.Pass by Reference (or) call by reference: In the pass by reference concept, the method is called using an alias or
reference of the actual parameter. So, it is called pass by reference. It forwards the unique identifier of the object to the
method. If we made changes to the parameter's instance member, it would affect the original value.
In case of call by reference original value is changed if we made changes in the called method. If we pass object
in place of any primitive value, original value will be changed. In this example we are passing object as a value.
1. class Operation2{
2. int data=50;
3.
4. void change(Operation2 op){
5. op.data=op.data+100;//changes will be in the instance variable
6. }
7. public static void main(String args[]){
8. Operation2 op=new Operation2();
9.
10. System.out.println("before change "+op.data);
11. op.change(op);//passing object
12. System.out.println("after change "+op.data);
13.
14. }
15. }
Output:
before change 50
after change 150
Why Java does not support pass by reference concept?
Java does not support call by reference because in call by reference we need to pass the address and address are stored in
pointers n java does not support pointers and it is because pointers breaks the security. Java is always pass-by-value.
22.Recursion
a method that calls itself is known as a recursive method. And, this process is known as recursion.
A physical world example would be to place two parallel mirrors facing each other. Any object in
between them would be reflected recursively.
In the above example, we have called the recurse() method from inside the main method. (normal
method call). And, inside the recurse() method, we are again calling the same recurse method. This
is a recursive call.
In order to stop the recursive call, we need to provide some conditions inside the method.
Otherwise, the method will be called infinitely.
Hence, we use the if...else statement (or similar approach) to terminate the recursive call inside the
method.
Example: Factorial of a Number Using Recursion
class Factorial {
Output:
4 factorial = 24
In the above example, we have a method named factorial() . The factorial() is called from
the main() method. with the number variable passed as an argument.
Here, notice the statement,
return n * factorial(n-1);
The factorial() method is calling itself. Initially, the value of n is 4 inside factorial() . During the next
recursive call, 3 is passed to the factorial() method. This process continues until n is equal to 0.
When n is equal to 0, the if statement returns false hence 1 is returned. Finally, the accumulated
result is passed to the main() method.
Working of Factorial Program
The image below will give you a better idea of how the factorial program is executed using
recursion.
Factorial Program using Recursion
23.Exploring String Class
Defination:-String is a sequence of characters. In java, objects of String are immutable which means
a constant and cannot be changed once created. String is represented by String class which is
located into java.lang package.
The Java String class implements Serializable, Comparable and CharSequence interface
that we have represented using the below image.
String can be created in number of ways, here are a few ways of creating string object.
String literal is a simple string enclosed in double quotes " ". A string literal is treated as a
String object.
System.out.println(s1);
Hello Java
We can create a new string object by using new operator that allocates memory for the
object.
System.out.println(s1);
}
Hello Java
Each time we create a String literal, the JVM checks the string pool first. If the string
literal already exists in the pool, a reference to the pool instance is returned. If string does
not exist in the pool, a new string object is created, and is placed in the pool. String
objects are stored in a special memory area known as string constant pool inside the
heap memory.
When we create a new string object using string literal, that string literal is added to the
string pool, if it is not present there already.
And, when we create another object with same string, then a reference of the string literal
already present in string pool is returned.
str2=str2.concat("world");
String Methods:-
String Methods List
Method Description
static String format(Locale l, String format, It returns formatted string with given
Object... args) locale.
Concat() method is used to add two or more string into a single string object. It is string
class method and returns a string object.
String s = "Hello";
System.out.println(str1);
Copy
HelloJava
2) Using + operator
Java uses "+" operator to concatenate two string objects into single one. It can also
concatenate numeric value with string object. See the below example.
String s = "Hello";
System.out.println(str1);
System.out.println(str2);
Copy
HelloJava
Java11
String Comparison
To compare string objects, Java provides methods and operators both. So we can
compare string in following three ways.
equals() method compares two strings for equality. Its general syntax is,
Copy
Example
It compares the content of the strings. It will return true if string matches, else
returns false.
String s = "Hell";
String s1 = "Hello";
String s2 = "Hello";
System.out.println(b);
b= s.equals(s1) ; //false
System.out.println(b);
Copy
true
false
2.Using == operator
The double equal (==) operator compares two object references to check whether they
refer to same instance. This also, will return true on successful match else returns false.
String s1 = "Java";
String s2 = "Java";
System.out.println(b);
System.out.println(b);
Copy
true
false
Explanation
We are creating a new object using new operator, and thus it gets created in a non-pool
memory area of the heap. s1 is pointing to the String in string pool while s3 is pointing to
the String in heap and hence, when we compare s1 and s3, the answer is false.
String compareTo() method compares values and returns an integer value which tells if the
string compared is less than, equal to or greater than the other string. It compares the
String based on natural ordering i.e alphabetically. Its general syntax is.
Syntax:
Example:
String s1 = "Abhi";
String s2 = "Viraaj";
String s3 = "Abhi";
System.out.println(a);
System.out.println(a);
System.out.println(a);
-21
0
21
1.charAt() method
String charAt() function returns the character located at the specified index.
System.out.println(str.charAt(2));
Output: u
NOTE: Index of a String starts from 0, hence str.charAt(2) means third character of the
String str.
2.equalsIgnoreCase() method
String equalsIgnoreCase() determines the equality of two Strings, ignoring their case (upper
or lower case doesn't matter with this method).
OutPut:-true
3.indexOf() method
String indexOf() method returns the index of first occurrence of a substring or a character.
indexOf() method has four override methods:
int indexOf(String str): It returns the index within this string of the first occurrence of
the specified substring.
int indexOf(int ch, int fromIndex): It returns the index within this string of the first
occurrence of the specified character, starting the search at the specified index.
int indexOf(int ch): It returns the index within this string of the first occurrence of the
specified character.
int indexOf(String str, int fromIndex): It returns the index within this string of the first
occurrence of the specified substring, starting at the specified index.
Example:
String str="StudyTonight";
String subString="Ton";
11
-1
NOTE: -1 indicates that the substring/Character is not found in the given String.
4.length() method
System.out.println(str.length());
5.replace() method
String replace() method replaces occurances of character with a specified new character.
Change Me
6.substring() method
String substring() method returns a part of the string. substring() method has two override
methods.
The first argument represents the starting point of the subtring. If the substring() method is
called with only one argument, the subtring returns characters from specified starting
point to the end of original string.
If method is called with two arguments, the second argument specify the end point of
substring.
System.out.println(str.substring(4));
System.out.println(str.substring(4,7));
}
456789
456
7.toLowerCase() method
String toLowerCase() method returns string with all uppercase characters converted to
lowercase.
System.out.println(str.toLowerCase());
abcdef
8.toUpperCase() method
This method returns string with all lowercase character changed to uppercase.
System.out.println(str.toUpperCase());
}
ABCDEF
9.valueOf() method
String class uses overloaded version of valueOf() method for all primitive data types and
for type Object.
NOTE: valueOf() function is used to convert primitive data types into Strings.
System.out.println(s1);
35
10.toString() method
String toString() method returns the string representation of an object. It is declared in the
Object class, hence can be overridden by any java class. (Object class is super class of all
java classes).
{
Car c = new Car();
System.out.println(c);
Whenever we will try to print any object of class Car, its toString() function will be called.
NOTE: If we don't override the toString() method and directly print the object, then it
would print the object id that contains some hashcode.
11.trim() method
This method returns a string from which any leading and trailing whitespaces has been
removed.
System.out.println(str.trim());
}
hello
12.contains()Method
String contains() method is used to check the sequence of characters in the given string. It
returns true if a sequence of string is found else it returns false.
boolean b = a.contains("studytonight.com");
System.out.println(b);
System.out.println(a.contains("javatpoint"));
true
false
13.endsWith() Method
String endsWith() method is used to check whether the string ends with the given suffix or
not. It returns true when suffix matches the string else it returns false.
System.out.println(a.endsWith("m"));
System.out.println(a.endsWith("com"));
true
true
14.format() Method
String format() is a string method. It is used to the format of the given string.
%a floating point
%b Any type
%c character
%d integer
%e floating point
%f floating point
%g floating point
%h any type
%n none
%o integer
%s any type
%t Date/Time
%x integer
Hexadecimal Value: 7d
Char Value: a
15.getBytes() Method
String getBytes() method is used to get byte array of the specified string.
String a="studytonight";
byte[] b=a.getBytes();
for(int i=0;i<b.length;i++)
System.out.println(b[i]);
16.getChars() Method
String getChars() method is used to copy the content of the string into a char array.
try
System.out.println(ch);
catch(Exception ex)
System.out.println(ex);
Welcom
17.isEmpty() Method
String isEmpty() method is used to check whether the string is empty or not. It returns true
when length string is zero else it returns false.
{
public static void main(String args[])
String a="";
String b="studytonight";
System.out.println(a.isEmpty());
System.out.println(b.isEmpty());
true
false
18.join() Method
String join() method is used to join strings with the given delimiter. The given delimiter is
copied with each element
System.out.println(s);
String date1 = String.join("/","23","01","2020");
System.out.println("Date: "+date1);
System.out.println("Time: "+time1);
Welcome to studytonight.com
Date: 23/01/2020
Time: 2:39:10
19.startsWith() Method
String startsWith() is a string method in java. It is used to check whether the given string
starts with given prefix or not. It returns true when prefix matches the string else it
returns false.
System.out.println(str.startsWith("s"));
System.out.println(str.startsWith("t"));
System.out.println(str.startsWith("study",1));
}
}
true
false
false
StringBuffer Class
Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer class in Java is
the same as String class except it is mutable i.e. it can be changed.
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it is safe and
will result in an order.
StringBuffer() It creates an empty String buffer with the initial capacity of 16.
StringBuffer(int capacity) It creates an empty String buffer with the specified capacity as length.
StringBufferExample.java
1. class StringBufferExample{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }
Output:
Hello Java
StringBuilder Class
Java StringBuilder class is used to create mutable (modifiable) String. The Java StringBuilder class is same as
StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.
Constructor Description
StringBuilder() It creates an empty String Builder with the initial capacity of 16.
StringBuilder(int length) It creates an empty String Builder with the specified capacity as length.
StringBuilder Examples
.
StringBuilderExample.java
1. class StringBuilderExample{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }
Output:
Hello Java
Difference between String and StringBuffer
2) String is slow and consumes more memory when we concatenate StringBuffer is fast and consumes less
too many strings because every time it creates new instance. memory when we concatenate t strings.
3) String class overrides the equals() method of Object class. So you StringBuffer class doesn't override the
can compare the contents of two strings by equals() method. equals() method of Object class.
4) String class is slower while performing concatenation operation. StringBuffer class is faster while performing
concatenation operation.
5) String class uses String constant pool. StringBuffer uses Heap memory
1) StringBuffer is synchronized i.e. thread safe. It StringBuilder is non-synchronized i.e. not thread
means two threads can't call the methods of safe. It means two threads can call the methods of
StringBuffer simultaneously. StringBuilder simultaneously.
2) StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.
3) StringBuffer was introduced in Java 1.0 StringBuilder was introduced in Java 1.5
Unit-2
Inheritance and Polymorphism:-
1. Types of inheritance
2. Member access rules
3. Super uses
4. Using final with inheritance
5. The object class and its methods
6. Method Overriding
7. Dynamic Binding
8. Abstract Classes
9. Abstract Methods
Inheritance:-
Defination:- 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.
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.
Example program:-
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output:-
1.Types of Inheritance:-
o Single Inheritance
o Multi-level Inheritance
o Hierarchical Inheritance
o Hybrid Inheritance
o Multiple Inheritance
1.Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the properties
and behavior of a single-parent class. Sometimes it is also known as simple inheritance.
In the above figure, Employee is a parent class and Executive is a child class. The Executive class
inherits all the properties of the Employee class.
Executive.java
class Employee
{
float salary=34534*12;
}
public class Executive extends Employee
{
float bonus=3000*6;
public static void main(String args[])
{
Executive obj=new Executive();
System.out.println("Total salary credited: "+obj.salary);
System.out.println("Bonus of six months: "+obj.bonus);
}
}
Output:
2.Multi-level Inheritance
In multi-level inheritance, a class is derived from a class which is also derived from another
class is called multi-level inheritance. In simple words, we can say that a class that has more than
one parent class is called multi-level inheritance. Note that the classes must be at different levels.
Hence, there exists a single base class and single derived class but multiple intermediate base
classes.
In the above figure, the class Marks inherits the members or methods of the class Students. The
class Sports inherits the members of the class Marks. Therefore, the Student class is the parent
class of the class Marks and the class Marks is the parent of the class Sports. Hence, the class
Sports implicitly inherits the properties of the Student along with the class Marks.
MultilevelInheritanceExample.java
//super class
class Student
{
int reg_no;
void getNo(int no)
{
reg_no=no;
}
void putNo()
{
System.out.println("registration number= "+reg_no);
}
}
//intermediate sub class
class Marks extends Student
{
float marks;
void getMarks(float m)
{
marks=m;
}
void putMarks()
{
System.out.println("marks= "+marks);
}
}
//derived class
class Sports extends Marks
{
float score;
void getScore(float scr)
{
score=scr;
}
void putScore()
{
System.out.println("score= "+score);
}
}
public class MultilevelInheritanceExample
{
public static void main(String args[])
{
Sports ob=new Sports();
ob.getNo(0987);
ob.putNo();
ob.getMarks(78);
ob.putMarks();
ob.getScore(68.7);
ob.putScore();
}
}
Output:
3.Hierarchical Inheritance
If a number of classes are derived from a single base class, it is called hierarchical inheritance.
In the above figure, the classes Science, Commerce, and Arts inherit a single parent class named
Student.
Let's implement the hierarchical inheritance mechanism in a Java program.
HierarchicalInheritanceExample.java
//parent class
class Student
{
public void methodStudent()
{
System.out.println("The method of the class Student invoked.");
}
}
class Science extends Student
{
public void methodScience()
{
System.out.println("The method of the class Science invoked.");
}
}
class Commerce extends Student
{
public void methodCommerce()
{
System.out.println("The method of the class Commerce invoked.");
}
}
class Arts extends Student
{
public void methodArts()
{
System.out.println("The method of the class Arts invoked.");
}
}
public class HierarchicalInheritanceExample
{
public static void main(String args[])
{
Science sci = new Science();
Commerce comm = new Commerce();
Arts art = new Arts();
//all the sub classes can access the method of super class
sci.methodStudent();
comm.methodStudent();
art.methodStudent();
}
}
Output:
4.Hybrid Inheritance
Hybrid means consist of more than one. Hybrid inheritance is the combination of two or more
types of inheritance.
In the above figure, GrandFather is a super class. The Father class inherits the properties of
the GrandFather class. Since Father and GrandFather represents single inheritance. Further,
the Father class is inherited by the Son and Daughter class. Thus, the Father becomes the
parent class for Son and Daughter. These classes represent the hierarchical inheritance.
Combinedly, it denotes the hybrid inheritance.
Daughter.java
//parent class
class GrandFather
{
public void show()
{
System.out.println("I am grandfather.");
}
}
//inherits GrandFather properties
class Father extends GrandFather
{
public void show()
{
System.out.println("I am father.");
}
}
//inherits Father properties
class Son extends Father
{
public void show()
{
System.out.println("I am son.");
}
}
//inherits Father properties
public class Daughter extends Father
{
public void show()
{
System.out.println("I am a daughter.");
}
public static void main(String args[])
{
Daughter obj = new Daughter();
obj.show();
}
}
Output:
I am daughter.
5.Multiple Inheritance (not supported)
Java does not support multiple inheritances due to ambiguity. For example, consider the
following Java program.
Demo.java
class Wishes
{
void message()
{
System.out.println("Best of Luck!!");
}
}
class Birthday
{
void message()
{
System.out.println("Happy Birthday!!");
}
}
public class Demo extends Wishes, Birthday //considering a scenario
{
public static void main(String args[])
{
Demo obj=new Demo();
//can't decide which classes' message() method will be invoked
obj.message();
}
}
The above code gives error because the compiler cannot decide which message() method is to
be invoked. Due to this reason, Java does not support multiple inheritances at the class level
but can be achieved through an interface.
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.
In this example, we have created two classes A and Simple. A class contains private data member
and private method. We are accessing these private members from outside the class, so there is a
compile-time error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
If you make any class constructor private, you cannot create the instance of that class from outside
the class. For example:
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
The access level of a default modifier is only within the sub classes,class and package . It cannot
be accessed from outside the sub class,class and package. If you do not specify any keyword, it
will be the default.
If you don't use any modifier, it is treated as default by default. The default modifier is accessible
only within package. It cannot be accessed from outside the package. It provides more
accessibility than private. But, it is more restrictive than protected, and public.
In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be accessed
from outside the package.
3) Protected
The protected access modifier is accessible within sub class,class and package and outside the
sub class package but through inheritance only.
Methods declared protected in a superclass must either be protected or public in subclasses; they cannot
be private.
The protected access modifier can be applied on the data member, method and constructor.
It can't be applied on the class.
In this example, we have created the two packages pack and mypack. The A class of pack package
is public, so can be accessed from outside the package. But msg method of this package is
declared as protected, so it can be accessed from outside the class only through inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello
4) Public
The public access modifier is accessible everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package. It has the widest scope among all
other modifiers.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
class A{
protected void msg(){System.out.println("Hello java");} //used protected
}
The default modifier is more restrictive than protected. That is why, there is a compile-time error.
3.Super Uses:-
Super Keyword in Java
The super keyword in Java is a reference variable which is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred
by super reference variable.
Usage of Java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
Example program:-
1. class Animal{
2. String color="white";
3. }
4. class Dog extends Animal{
5. String color="black";
6. void printColor(){
7. System.out.println(color);//prints color of Dog class
8. System.out.println(super.color);//prints color of Animal class
9. }
10. }
11. class TestSuper1{
12. public static void main(String args[]){
13. Dog d=new Dog();
14. d.printColor();
15. }}
Output:-
black
white
In the above example, Animal and Dog both classes have a common property color. If we print color property, it will
print the color of current class by default. To access the parent property, we need to use super keyword.
Example Program:-
1. class Animal1{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog1 extends Animal1{
5. void eat(){System.out.println("eating bread...");}
6. void bark(){System.out.println("barking...");}
7. void work(){
8. super.eat();
9. bark();
10. }
11. }
12. class TestSuper2{
13. public static void main(String args[]){
14. Dog1 d=new Dog1();
15. d.work();
16. }}
Output:-
eating…
barking…
In the above example Animal and Dog both classes have eat() method if we call eat() method from Dog class, it
will call the eat() method of Dog class by default because priority is given to local.
Note: super() is added in each class constructor automatically by compiler if there is no super() or this().
Example program:-
1. class Animal2{
2. Animal2(){System.out.println("animal is created");}
3. }
4. class Dog2 extends Animal2{
5. Dog2(){
6. super();//without use of super keyword java compiler automatically executed
7. System.out.println("dog is created");
8. }
9. }
10. class TestSuper3{
11. public static void main(String args[]){
12. Dog2 d=new Dog2();
13. }}
Output:-
animal is created
dog is created
Does a super class reference be used to refer sub class
object?justify
Ans:-
So difference between referencing using superclass reference and referencing using subclass
reference is use superclass referencing can holds object of subclass and could only access
the methods which are defined/overridden by subclass while use subclass referencing can
not hold object of superclass and could access the methods of both superclass and subclass.
If you assign an object of the subclass to the reference variable of the superclass then
the subclass object is converted into the type of superclass and this process is termed
as widening (in terms of references).
class Animal{
void eat(){System.out.println("animal is eating...");}
}
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is called blank final
variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can
be static also which will be initialized in the static block only.
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
OutPut:-
Compile time error //can’t modify final variable value
2) Java final method
If you make any method as final, you cannot override it.
OutPut:-
Compile time error//can’t override method
Object Class in Java is the topmost class among all the classes in Java. We can also say that the
Object class in Java is the parent class for all the classes. It means that all the classes in Java are
derived classes and their base class is the Object class. Object class is present
in java.lang package.
All the classes directly or indirectly inherit from the Object class in Java.
Ex:-public class Object{
/*
1. toString()
2. hashCode()
3. equals(Object o)
4. clone()
5. finalize()
6. getClass()
7. wait()
8. wait(long timeout)
9. wait(long timeout,int nanos)
10.notify()
11.notifyAll()
*/
class Vehicle{
//body of class Vehicle
}
Here we can see that class Vehicle is not inheriting any class, but it inherits the Object class. It
is an example of the direct inheritance of object class.
class Vehicle{
//body of class Vehicle
}
class Car extends Vehicle{
//body of class Car
}
Here we can see that the Car class directly inherits the Vehicle class. The extends keyword is
used to establish inheritance between two classes. But we have seen in the above example that
if we define a class without inheriting it from some other class, it directly inherits the Object
class. Since Car inherits the Vehicle and the Vehicle inherits the Object class, Car indirectly
inherits the Object class. */
Fig.1.Object Class
Method Description
public final Class getClass() returns the Class class object of this object. The Class class
can further be used to get the metadata of this class.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws creates and returns the exact copy (clone) of this object.
CloneNotSupportedException
public final void notify() wakes up single thread, waiting on this object's monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's monitor.
public final void wait(long causes the current thread to wait for the specified milliseconds,
timeout)throws InterruptedException until another thread notifies (invokes notify() or notifyAll() method).
public final void wait(long timeout,int causes the current thread to wait for the specified
nanos)throws InterruptedException milliseconds and nanoseconds, until another thread notifies
(invokes notify() or notifyAll() method).
public final void wait()throws causes the current thread to wait, until another
InterruptedException thread notifies (invokes notify() or notifyAll() method).
6.Method Overriding:-
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.
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).
Syntax:-class A
{
Void show()
{
// block of code
}
}
Class B extends A
{
Void show()
{
//block of code
}
}
OutPut:-
class Bank{
int getRateOfInterest(){return 0;}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
7.Dynamic Binding:-
Connecting a method call to the method body is known as binding.
Understanding Type
Let's understand the type of instance.
class Animal{}
static binding
When type of the object is determined at compiled time(by the compiler), it is known as static binding.
If there is any private, final or static method in a class, there is static binding.
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
class Animal{
void eat(){System.out.println("animal is eating...");}
}
Output:-
dog is eating…
8.Abstraction:-
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS
where you type the text and send the message. You don't know the internal processing about the message
delivery.
Abstract class:-
A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods.
It needs to be extended and its method implemented. It cannot be instantiated.
Syntax:-
Abstract Method
A method which is declared as abstract and does not have implementation is known as an abstract method.
abstract access modifier return type method_name();//no method body and abstract method
In this example, Bike is an abstract class that contains only one abstract method run. Its implementation is
provided by the Honda class.
Output:-
running safely
Abstract Method Using Real Scenario:-Example 2
Example 3:-
File: TestAbstraction2.java
9.Abstract Method
A method declared using the abstract keyword within an abstract class and does not have a definition
(implementation) is called an abstract method.
When we need just the method declaration in a super class, it can be achieved by declaring the methods as
abstracts.
Abstract method is also called subclass responsibility as it doesn't have the implementation in the super class.
Therefore a subclass must override it to provide the method definition.
}
Output:-
Dennie Ritchie
James Gosling
Difference between abstract class and interface
Abstract class Interface
1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstract methods. Since Java 8, it can have
default and static methods also.
3) Abstract class can have final, non-final, static Interface has only static and final variables.
and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.
5) The abstract keyword is used to declare The interface keyword is used to declare interface.
abstract class.
6) An abstract class can extend another Java An interface can extend another Java interface only.
class and implement multiple Java interfaces.
7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".
8) A Java abstract class can have class members Members of a Java interface are public by default.
like private, protected, etc.
9)Example: Example:
public abstract class Shape{ public interface
public abstract void draw(); void
} }
Part-B
/*
Packages are useful to arrange related classes and interfaces into a group. This makes all
the classes and interfaces performing the same task to put together in the same package.
For example, in Java, all the classes and interfaces which perform input and output
operations are stored in java.io package.
packages hide the classes and interfaces in a separate sub directory, so that accidental
deletion of classes and interfaces will not take place.
The classes and interfaces of a package are isolated from the classes and interfaces of
another package. This means that we can use same names for classes of two different
classes. For example, there is a Date class in java.util package and also there is another
Date class available in java.sql package.
A group of packages is called a library. The classes and interfaces of a package are like
books in a library and can be reused several times. This reusability nature of packages
makes programming easy. Just think, the packages in Java are created by JavaSoft people
only once, and millions of programmers all over the world are daily by using them in
various programs.
*/
Different Types of Packages
There are two different types of packages in Java. They are:
Built-in packages
User-defined packages
(or)
Java.lang.* :-This package as primary classes and interfaces essential for Java language. It
consists of Wrapper Classes . Ex: System, String, Integer, Character classes etc..,
Java.util.* :-This Package consist useful classes and interfaces like Stack, LinkedList, Vector,
ArrayList, Date etc.,
java.io.* :-This packages handles Files and input, output related tasks. Ex:- File, FileInputStream,
FilOutputStream, FileReader, FileWriters.
Java.awt.* :-awt means Abstract Window Toolkit. This packages helps to develop GUI. It
consists of two important some packages.
1. Java.awt.*;
2. Java.awt.event.*;
3. Java.awt.image.*;
Javax.swing.* :-This package helps to develop GUI. Java.awt will have additional features than
java.awt.*;
Java.net.* :-Client and Server programming can be done using packages it uses TCP/IP TCP
means Transmission Control Protocol and IP means Internet Protocol.
Java.applet.* : - Applets are small intelligent program which travel from one place to another
place on Internet and executed in client side.
Java.sql.*:-This package helps to connect to the database like Oracle, MsAccess etc..,
Java.beans.*:-Beans are software reusalble components in the network they can be develop this
package.
Java.rmi.*:-rmi stands for Remote Method Invocation. This object which exists one computer
in the network can be invoked from another computer and can be used.
Javax.servlet.* :-Servlets are Server Side Programming which handles clients.
Syntax:-
1. Package packagename; //to create a package
2. Package packagename.subpackagename; //to create a sub package within a package
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
If you are not using any IDE, you need to follow the syntax given below:
For example
javac -d . Simple.java
See the output to understand how to compile a Java program that contains a package. The –d
option (switch) tells the Java compiler to create a separate sub directory and place the .class file
there. The dot(.) after –d indicates that the package should be created in the current directory i.e.,
C:\. We have written as:
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
Ex:-java mypack.Simple
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output:Welcome to package
Note: Sequence of the program must be package then import then class.
If you import a package, all the classes and interface of that package will be imported excluding
the classes and interfaces of the subpackages. Hence, you need to import the subpackage as well.
Subpackage in java:-
Package inside the package is called the subpackage. It should be created to categorize the
package further.
Let's take an example, Sun Microsystem has definded a package named java that contains many
classes like System, String, Reader, Writer, Socket etc. These classes represent a particular group
e.g. Reader and Writer classes are for Input/Output operation, Socket and ServerSocket classes
are for networking etc and so on. So, Sun has subcategorized the java package into subpackages
such as lang, net, io etc. and put the Input/Output related classes in io package, Server and
ServerSocket classes in net packages and so on.
Syntax:-
Example of Subpackage
package high.sub;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
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.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
To Compile: javac -d . B.java
To Run: java mypack.B
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
To Compile: javac -d . B.java
To Run: java mypack.B
Output:Hello
It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
To Compile: javac -d . B.java
To Run: java mypack.B
Output:Hello
There are four types of Java access modifiers using to access Packages:
1) Private
The access level of a private modifier is only within the class. It cannot be accessed from outside
the class.
In this example, we have created two classes A and Simple. A class contains private data member
and private method. We are accessing these private members from outside the class, so there is a
compile-time error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
If you make any class constructor private, you cannot create the instance of that class from outside
the class. For example:
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
2) Default
The access level of a default modifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default.
If you don't use any modifier, it is treated as default by default. The default modifier is accessible
only within package. It cannot be accessed from outside the package. It provides more
accessibility than private. But, it is more restrictive than protected, and public.
In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be accessed
from outside the package.
3) Protected
The protected access modifier is accessible within package and outside the package but through
inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
In this example, we have created the two packages pack and mypack. The A class of pack package
is public, so can be accessed from outside the package. But msg method of this package is
declared as protected, so it can be accessed from outside the class only through inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello
4) Public
The public access modifier is accessible everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package. It has the widest scope among all
other modifiers.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Understanding CLASSPATH:-
The CLASSPATH is an environment variable that tells the Java compiler where to look for class
files import. CLASSPATH is generally set to a directory or a Jar(Java Archive) file.
To see what is there currently in the CLASSPATH variable in your system, you can type in
Windows
C:\>echo %path% \\used to know the all the classpaths in the particular directory
C:\>echo %classpath% \\used to know the current classpath name
send the class file to another directory or drive?
There is a scenario, I am created one class A.java in a e directory folder source. I want to put the
class file of A.java source file in classes folder of c: drive.
//save as Simple.java
package mypack;
public class A{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
To Compile:
The –classpath or -cp switch can be used with javac and java tool.
To run this program from e:\source directory, you can use -classpath switch of java that tells
where to look for class file. For example:
Output:Welcome to package
o Temporary
o By setting the classpath in the command prompt
o By -classpath switch
o Permanent
o By setting the classpath in the environment variables
o By creating the jar file, that contains all the class files, and copying the jar file in the
jre/lib/ext folder.
4.Importing Packages
There are three ways to import a 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.
Syntax:-
import Packagename.*;
import packagename.subpackagename.*;
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
To Compile: javac -d . B.java
To Run: java mypack.B
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Syntax:-
Import packagename.classname;
import packagename.subpackagename.classname;
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
To Compile: javac -d . B.java
To Run: java mypack.B
Output:Hello
It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
To Compile: javac -d . B.java
To Run: java mypack.B
Output:Hello
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.
Java Interface also represents the IS-A relationship.
Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds public,
static and final keywords before data members.
In other words, Interface fields are public, static and final by default, and the methods are public and
abstract.
As shown in the figure given below, a class extends another class, an interface extends another interface,
but a class implements an interface.
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
File: TestInterface1.java
Output:drawing circle
Let's see another example of java interface which provides the implementation of Bank interface.
File: TestInterface2.java
1. interface Bank{
2. float rateOfInterest();
3. }
4. class SBI implements Bank{
5. public float rateOfInterest(){return 9.15f;}
6. }
7. class PNB implements Bank{
8. public float rateOfInterest(){return 9.7f;}
9. }
10. class TestInterface2{
11. public static void main(String[] args){
12. Bank b=new SBI();
13. System.out.println("ROI: "+b.rateOfInterest());
14. }}
Output:ROI: 9.15
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. A7 obj = new A7();
13. obj.print();
14. obj.show();
15. }
16. }
Test it Now
Output:Hello
Welcome
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void print();
6. }
7.
8. class TestInterface3 implements Printable, Showable{
9. public void print(){System.out.println("Hello");}
10. public static void main(String args[]){
11. TestInterface3 obj = new TestInterface3();
12. obj.print();
13. }
14. }
Output:
Hello
As you can see in the above example, Printable and Showable interface have same methods but its
implementation is provided by class TestTnterface1, so there is no ambiguity.
Interface inheritance
1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class TestInterface4 implements Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. TestInterface4 obj = new TestInterface4();
13. obj.print();
14. obj.show();
15. }
16. }
Test it Now
Output:
Hello
Difference between abstract class and interface
Abstract class and interface both are used to achieve abstraction where we can declare the abstract
methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
1) Abstract class can have abstract and non- Interface can have only abstract methods. Since Java 8,
abstract methods. it can have default and static methods also.
2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.
3) Abstract class can have final, non-final, static and non- Interface has only static and final variables.
static variables.
4) Abstract class can provide the implementation of Interface can't provide the implementation of
interface. abstract class.
5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.
6) An abstract class can extend another Java class and An interface can extend another Java interface only.
implement multiple Java interfaces.
7) An abstract class can be extended using keyword "extends". An interface can be implemented using keyword
"implements".
8) A Java abstract class can have class members like private, Members of a Java interface are public by default.
protected, etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully abstraction
(100%).
Unit-3
Exception Handling:
1. Concepts of Exception handling
2. Benefits of Exception Handling
3. Exception Hierarchy
4. Usage of try and catch
5. Usage of throw
6. Usage of throws
7. Usage of finally
9.Built in Exceptions
10.Creating own Exceptions Sub Class
Run Time:-
Java TestRunTimeError
Dividing of two numbers is:10 0
Exception in thread "main" java.lang.ArithmeticException: / by zero
To handle the error during the run time we can use Exception handling to put our error code
inside the try block and catch the error inside the catch block.
Example Program2:-
class TestRunTimeError
{
public static void main (String args[])
{
int a=10;
int b=0;
int c;
try{
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
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.
3.Exception Hierarchy:-
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:
Fig. Exception Hierarchy
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:
Built in exception:-
2.Unchecked Exception:-
Unchecked Exceptions are not checked by the compiler.These are called runtime
exceptions.Unchecked exceptions occur at runtime.These types of exceptions cannot be catched
or handled at the time of compilation,because they get generated by the mistakes in the program.
Ex:-
class TestRunTimeError
{
public static void main (String args[])
{
System.out.println(10/0); //raised run time exception
System.out.println(" Program Ending");
}
}
OutPut:-
Compile Time:-
Javac TestRunTimeError.java
Run Time:-//Unchecked by compile time and raised by run time exception is called
unchecked exception
Java TestRunTimeError
Exception in thread "main" java.lang.ArithmeticException: / by zero
Handle this unchecked exception using Exception handling keyword try and catch block.
There are given some scenarios where unchecked exceptions may occur. They are as follows:
int a=50/0;//ArithmeticException
2) A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be
other reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.
3.Error:-
Errors are problems that mainly occur due to the lack of system resources. It cannot be caught or
handled. It indicates a serious problem. It occurs at run time. These are always unchecked. An
example of errors is OutOfMemoryError, LinkageError, AssertionError, etc. are the
subclasses of the Error class.
Example program:-
1. public class ErrorExample
2. {
3. public static void main(String args[])
4. {
5. //method calling
6. recursiveDemo(10);
7. }
8. public static void recursiveDemo(int i)
9. {
10.while(i!=0)
11.{
12.//increments the variable i by 1
13.i=i+1;
14.//recursive called method
15.recursiveDemo(i);
16.}
17.}
18.}
1. These exceptions are checked at compile time. These exceptions are just opposite to the checked
These exceptions are handled at compile time too. exceptions. These exceptions are not checked and
handled at compile time.
2. These exceptions are direct subclasses of They are the direct subclasses of the RuntimeException
exception but not extended from class.
RuntimeException class.
3. The code gives a compilation error in the case The code compiles without any error because the
when a method throws a checked exception. The exceptions escape the notice of the compiler.
compiler is not able to handle the exception on its These exceptions are the results of user-created
own. errors in programming logic.
4. These exceptions mostly occur when the These exceptions occur mostly due to programming
probability of failure is too high. mistakes.
5. Common checked exceptions include Common unchecked exceptions
IOException, DataAccessException, include ArithmeticException,
InterruptedException, etc. InvalidClassException,
NullPointerException, etc.
6. These exceptions are propagated using the throws These are automatically propagated.
keyword.
7. It is required to provide the try-catch and try- In the case of unchecked exception
finally block to handle the checked exception. it is not mandatory.
In Java, Error, and Exception both are subclasses of the Java Throwable class that belongs to
java.lang package.
Type It can be classified into two categories i.e. All errors in Java are unchecked.
checked and unchecked.
Known or Only checked exceptions are known to the Errors will not be known to the compiler.
unknown compiler.
Causes It is mainly caused by the application It is mostly caused by the environment in which
itself.
the application is running.
Java provides five keywords that are used to handle the exception. The following table describes
each.
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 w
signature.
If an exception occurs at the particular statement in the try block, the rest of the block code will
not execute. So, it is recommended not to keep the code in try block that will not throw an
exception.
Java catch block is used to handle the Exception by declaring the type of exception within the
parameter. The declared exception must be the parent class exception ( i.e., Exception) or the
generated exception type. However, the good approach is to declare the generated type of
exception.
Java try block must be followed by either catch or finally block.
The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM
provides a default exception handler that performs the following tasks:
But if the application programmer handles the exception, the normal flow of the application is
maintained, i.e., rest of the code is executed.
Example program:-
public class TryCatchExample2 {
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
Output:
java.lang.ArithmeticException: / by zero
Points to remember
o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
Flowchart of Multi-catch Block
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Arithmetic Exception occurs
Output:
try{
int a[]=new int[3];
a[4]=10;
}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
// main method
public static void main(String args[])
{
// Main try block
try {
// initializing array
int a[] = { 1, 2, 3, 4, 5 };
Whenever a try block does not have a catch block for a particular exception, then the catch blocks
of parent try block are inspected for that exception, and if a match is found then that catch block
is executed.
// main method
public static void main(String args[])
{
// Main try block
try {
// initializing array
int a[] = { 1, 2, 3, 4, 5 };
Syntax:-
try
finally
}
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.
Rule: For each try block there can be zero or more catch blocks, but only one finally block.
try {
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){
System.out.println(e);
}
finally {
System.out.println("finally block is always executed2");
}
//third final block with error and wrong exception class
try {
int data=25/0;
System.out.println(data);
}
//cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
catch(NullPointerException e){
System.out.println(e);
}
6.Usage of throw:-
Defination:-Throw keyword is used to throw the user defined or customize exception object to the
JVM explicitly for that purpose we use throw keyword.
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(user defined exception) making the
code recovery and debugging easier.
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 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.
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
Output:
The above code throw an unchecked exception. Similarly, we can also throw unchecked and user
defined exceptions.
Note: If we throw unchecked exception from a method, it is must to handle the exception or
declare in throws clause.
7.Usage of throws:-
Defination:-throws keyword is used when we doesn’t want to handle the exception and try to send
the exception to the JVM(JVM or other method)
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.
Example program:-
wait1();
try
{
}
finally{
System.out.println("Successfully Executed");
}
}
}
Output:-
0
1
2
3
4
5
6
7
8
9
10
Finally block
TestExceptionPropagation1.java
class TestExceptionPropagation1{
void m(){
int data=50/0;
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
TestExceptionPropagation1 obj=new TestExceptionPropagation1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...
In the above example exception occurs in the m() method where it is not handled, so it is
propagated to the previous n() method where it is not handled, again it is propagated to the p()
method where exception is handled.
Exception can be handled in any method in call stack either in the main() method, p() method,
n() method or m() method.
9.Built in Exceptions:-
Built-in Exception
Exceptions that are already available in Java libraries are referred to as built-in exception.
These exceptions are able to define the error situation so that we can understand the reason of
getting this error. It can be categorized into two broad categories, i.e., checked
exceptions and unchecked exception.
Checked Exception
Checked exceptions are called compile-time exceptions because these exceptions are checked
at compile-time by the compiler. The compiler ensures whether the programmer handles the
exception or not. The programmer should have to handle the exception; otherwise, the system
has shown a compilation error.
Example program:-
1. FileNotFoundException : This Exception is raised when a file is not accessible or does not
open.
// Java program to demonstrate
// FileNotFoundException
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {
Output:
File does not exist
Unchecked Exceptions
The unchecked exceptions are just opposite to the checked exceptions. The compiler will not
check these exceptions at compile time. In simple words, if a program throws an unchecked
exception, and even if we didn't handle or declare it, the program would not give a compilation
error. Usually, it occurs when the user provides bad data during the interaction with the program.
Example Program:-
1. ArrayIndexOutOfBounds Exception : It is thrown to indicate that an array has been
accessed with an illegal index. The index is either negative or greater than or equal to the
size of the array.
class ArrayIndexOutOfBound_Demo {
public static void main(String args[])
{
try {
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index is Out Of Bounds");
}
}
}
Output:
Array Index is Out Of Bounds
In Java, we can create our own exceptions that are derived classes of the Exception class. Creating
our own Exception is known as custom exception or user-defined exception. Basically, Java
custom exceptions are used to customize the exception according to user need.
Consider the example 1 in which InvalidAgeException class extends the Exception class.
Using the custom exception, we can have your own exception and message.
In order to create custom exception, we need to extend Exception class that belongs to java.lang
package.
Let's see a simple example of Java custom exception. In the following code, constructor of
InvalidAgeException takes a string as an argument. This string is passed to constructor of parent
class Exception using the super() method. Also the constructor of Exception class can be called
without using a parameter and calling super() method is not mandatory.
TestCustomException1.java
// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");
Output:
Difference between throw and throws in Java
Sr. Basis of Differences throw throws
no.
1. Definition Java throw keyword is used Java throws keyword is used in the
throw an exception explicitly method signature to declare an
in the code, inside the exception which might be thrown by the
function or the block of function while the execution of the code.
code.
4. Declaration throw is used within the throws is used with the method
method. signature.
1 Definition final is the keyword and finally is the block in finalize is the method in Java
. access modifier which is Java Exception which is used to perform clean
used to apply restrictions on Handling to execute up processing just before
a class, method or variable. the important code object is garbage collected.
whether the
exception occurs or
not.
2 Applicable Final keyword is used with Finally block is finalize() method is used with
. to the classes, methods and always related to the the objects.
variables. try and catch block
in exception
handling.
3 Functionalit (1) Once declared, final (1) finally block runs finalize method performs
. y variable becomes constant the important code the cleaning activities with
and cannot be modified. even if exception respect to the object before its
(2) final method cannot be occurs or not. destruction.
overridden by sub class. (2) finally block
(3) final class cannot be cleans up all the
inherited. resources used in try
block