You are on page 1of 171

JAVA

Introduction to JAVA

 JAVA was developed by Sun Microsystems Inc in 1991, later acquired by Oracle
Corporation. It was developed by James Gosling and Patrick Naughton. It is a
simple programming language. Writing, compiling and debugging a program is
easy in java. It helps to create modular programs and reusable code.
Why to learn JAVA (key Features)
 Object Oriented − In Java, everything is an Object. Java can be easily
extended since it is based on the Object model.
 Platform Independent − Unlike many other programming languages including
C and C++, when Java is compiled, it is not compiled into platform specific
machine, rather into platform independent byte code. This byte code is
distributed over the web and interpreted by the Virtual Machine (JVM) on
whichever platform it is being run on.
 Simple − Java is designed to be easy to learn. If you understand the basic
concept of OOP Java, it would be easy to master.
 Secure − With Java's secure feature it enables to develop virus-free, tamper-
free systems. Authentication techniques are based on public-key encryption.
 Architecture-neutral − Java compiler generates an architecture-neutral
object file format, which makes the compiled code executable on many
processors, with the presence of Java runtime system.
 Portable − Being architecture-neutral and having no implementation dependent aspects of
the specification makes Java portable. Compiler in Java is written in ANSI C with a clean
portability boundary, which is a POSIX subset.
 Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly on
compile time error checking and runtime checking.
 Multithreaded − With Java's multithreaded feature it is possible to write programs that can
perform many tasks simultaneously. This design feature allows the developers to construct
interactive applications that can run smoothly.
 Interpreted − Java byte code is translated on the fly to native machine instructions and is
not stored anywhere. The development process is more rapid and analytical since the linking
is an incremental and light-weight process.
 High Performance − With the use of Just-In-Time compilers, Java enables high performance.
 Distributed − Java is designed for the distributed environment of the internet.
 Dynamic − Java is considered to be more dynamic than C or C++ since it is designed to adapt
to an evolving environment. Java programs can carry extensive amount of run-time
information that can be used to verify and resolve accesses to objects on run-time.
Application
There are many devices where Java is currently used. Some of them are as
follows:

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


2. Web Applications such as irctc.co.in, javatpoint.com, etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.
Types of Java Applications
There are mainly 4 types of applications that can be created using Java programming:

1) Standalone Application
Standalone applications are also known as desktop applications or window-based applications. These are
traditional software that we need to install on every machine. Examples of standalone application are Media
player, antivirus, etc. AWT and Swing are used in Java for creating standalone applications.

2) Web Application
An application that runs on the server side and creates a dynamic page is called a web application. Currently,
Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for creating web applications in Java.

3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is called enterprise application.
It has advantages of the high-level security, load balancing, and clustering. In Java, EJB is used for creating
enterprise applications.

4) Mobile Application
An application which is created for mobile devices is called a mobile application. Currently, Android and Java
ME are used for creating mobile applications.
Java is an Object Oriented language

Object oriented programming is a way of organizing programs as collection of


objects, each of which represents an instance of a class.
4 main concepts of Object Oriented programming are:

1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism
Object-Oriented Programming is a methodology or
paradigm to design a program using classes and objects.

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


watch, etc. An Object can be defined as an instance of a class. An object
contains an address and takes up some space in memory. Objects can
communicate without knowing the details of each other's data or code.
 Class: Collection of objects is called class. It is a logical entity. A class can also be defined as a
blueprint from which you can create an individual object. Class doesn't consume any space.
 Inheritance: When one object acquires all the properties and behaviors of a parent object, it is
known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
 Polymorphism: If one task is performed in different ways, it is known as polymorphism. For
example: to convince the customer differently, to draw something, for example, shape, triangle,
rectangle, etc.
In Java, we use method overloading and method overriding to achieve polymorphism.

 Abstraction: Hiding internal details and showing functionality is known as abstraction. For
example phone call, we don't know the internal processing. In Java, we use abstract class and
interface to achieve abstraction.
 Encapsulation: Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with different medicines. A java class is the
example of encapsulation. Java bean is the fully encapsulated class because all the data members
are private here.
What is the difference between an object-
oriented programming language and object-
based programming language?

 Object-based programming language follows all


the features of OOPs except Inheritance.
JavaScript and VBScript are examples of object-
based programming languages.
C++ vs Java
Comparison Index C++ Java
Platform-independent C++ is platform-dependent. Java is platform-independent.

Mainly used for C++ is mainly used for system Java is mainly used for application programming. It is widely used in
programming. window, web-based, enterprise and mobile applications.

Design Goal C++ was designed for systems and Java was designed and created as an interpreter for printing systems but
applications programming. It was an later extended as a support network computing. It was designed with a goal
extension of C programming of being easy to use and accessible to a broader audience.
language.

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

Multiple inheritance C++ supports multiple inheritance. Java doesn't support multiple inheritance through class. It can be achieved
by interfaces in java.

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

Compiler and Interpreter C++ uses compiler only. C++ is Java uses compiler and interpreter both. Java source code is converted into
compiled and run using the compiler bytecode at compilation time. The interpreter executes this bytecode at
which converts source code into runtime and produces output. Java is interpreted that is why it is platform
machine code so, C++ is platform independent.
dependent.
Call by Value and Call by C++ supports both call by value and call by Java supports call by value only. There is no
reference reference. call by reference in java.
Structure and Union C++ supports structures and unions. Java doesn't support structures and unions.
Thread Support C++ doesn't have built-in support for threads. It Java has built-in thread support.
relies on third-party libraries for thread support.

Documentation comment C++ doesn't support documentation comment. Java supports documentation comment (/** ...
*/) to create documentation for java source
code.

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

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

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

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


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

public class MyFirstJavaProgram {

/* This is my first java program.


* This will print 'Hello World' as the output
*/

public static void main(String []args) {


System.out.println("Hello World"); // prints Hello World
}
}
JAVA PROGRAM STRUCTURE
Basic Syntax
About Java programs, it is very important to keep in mind the following points.
 Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would have
different meaning in Java.
 Class Names − For all class names the first letter should be in Upper Case. If several words are used
to form a name of the class, each inner word's first letter should be in Upper Case. Example: class
MyFirstJavaClass
 Method Names − All method names should start with a Lower Case letter. If several words are used
to form the name of the method, then each inner word's first letter should be in Upper Case.
Example: public void myMethodName()
 Program File Name − Name of the program file should exactly match the class name. When saving
the file, you should save it using the class name (Remember Java is case sensitive) and append
'.java' to the end of the name (if the file name and the class name do not match, your program will
not compile).
But please make a note that in case you do not have a public class present in the file then file name can be
different than class name. It is also not mandatory to have a public class in the file.
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved
as 'MyFirstJavaProgram.java'
 public static void main(String args[]) − Java program processing starts from the main() method
which is a mandatory part of every Java program.
Java Identifiers
All Java components require names. Names used for classes, variables, and methods are
called identifiers.
In Java, there are several points to remember about identifiers. They are as follows −
 All identifiers should begin with a letter (A to Z or a to z), currency character ($) or
an underscore (_).
 After the first character, identifiers can have any combination of characters.
 A key word cannot be used as an identifier.
 Most importantly, identifiers are case sensitive.
 Examples of legal identifiers: age, $salary, _value, __1_value.
 Examples of illegal identifiers: 123abc, -salary.
Java Modifiers

Like other languages, it is possible to modify classes, methods, etc., by


using modifiers. There are two categories of modifiers −
 Access Modifiers − default, public , protected, private
 Non-access Modifiers − final, abstract, strictfp
File compilation and execution

 Save this file as MyFirstJavaProgram.java

 To compile write command javac MyFirstJavaProgram.java


in command prompt.

 To execute this file write command java MyFirstJavaProgram in


command prompt.
Compilation and Execution flow
JVM Architecture
How JVM Works
 Class Loader: The class loader reads the .class file and save the byte code in the method area.
 Method Area: There is only one method area in a JVM which is shared among all the classes. This holds
the class level information of each .class file.
 Heap: Heap is a part of JVM memory where objects are allocated. JVM creates a Class object for each
.class file.
 Stack: Stack is a also a part of JVM memory but unlike Heap, it is used for storing temporary variables.
 PC Registers: This keeps the track of which instruction has been executed and which one is going to be
executed. Since instructions are executed by threads, each thread has a separate PC register.
 Native Method stack: A native method can access the runtime data areas of the virtual machine.
 Native Method interface: It enables java code to call or be called by native applications. Native
applications are programs that are specific to the hardware and OS of a system.
 Garbage collection: A class instance is explicitly created by the java code and after use it is
automatically destroyed by garbage collection for memory management.
JVM Vs JRE Vs JDK
Variables in Java
 To declare a variable follow this syntax: data_type variable_name = value;
Ex: int num;
char ch = 'A';
int number = 100;
 Types of Variables in Java
There are three types of variables in Java.
1) Local variable 2) Static (or class) variable 3) Instance variable
 Variables naming convention in java
1) Variables naming cannot contain white spaces, for example: int num ber = 100; is invalid
because the variable name has space in it.
2) Variable name can begin with special characters such as $ and _
3) As per the java coding standards the variable name should begin with a lower case
letter, for example int number; For lengthy variables names that has more than one words
do it like this: int smallNumber; int bigNumber; (start the second word with capital letter).
4) Variable names are case sensitive in Java.
Data Types
Operators in Java

 An operator is a character that represents an action, for example + is an


arithmetic operator that represents addition.
 Types of Operator in Java
1) Basic Arithmetic Operators
2) Assignment Operators
3) Auto-increment and Auto-decrement Operators
4) Logical Operators
5) Comparison (relational) operators
6) Bitwise Operators
7) Ternary Operator
Java Operator Precedence
Operator Type Category Precedence
Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%


additive +-
Shift shift << >> >>>
Relational comparison < > <= >= instanceof

equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&


logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |=
<<= >>= >>>=
Operator examples
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=10;
System.out.println(a++ + ++a);
System.out.println(b++ + b++);

}
}

Output: 22
21
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);
System.out.println(~b);
System.out.println(!c);
System.out.println(!d);
}}

Output:-11 (minus of total positive value which starts from 0)


9 (positive of total minus, positive starts from 0)
false (opposite of boolean value)
true
Arithmetic operator

class OperatorExample{
public static void main(String args[]){
System.out.println(10*10/5+3-1*4/2);
}}

Output: 21
Type Casting in Java
 Type casting is used to convert an object or variable of one type into another.
 Syntax: dataType variableName = (dataType) variableToConvert;
 There are two casting directions: narrowing (larger to smaller type) and
widening (smaller to larger type). Widening can be done automatically (for
example, int to double), but narrowing must be done explicitly (like double to
int).
 Widening or Automatic Type Conversion: Widening conversion takes place
when two data types are automatically converted. This happens when:
1. The two data types are compatible.
2. When we assign value of a smaller data type to a bigger data type.
Example:
class Test
{
public static void main(String[] args)
{
int i = 100;
//automatic type conversion
long l = i;
//automatic type conversion
float f = l;
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f); } }

Output: Int value 100


Long value 100
Float value 100.0
Narrowing or Explicit Conversion

 If we want to assign a value of larger data type to a smaller data type we perform explicit
type casting or narrowing.

 This is useful for incompatible data types where automatic conversion cannot be done.
 Here, target-type specifies the desired type to convert the specified value to.
Example:
//Java program to illustrate incompatible data
// type for explicit type conversion
public class Test
{
public static void main(String[] argv)
{
char ch = 'c';
int num = 88;
ch = num;
}
}
Output:error: incompatible types: possible lossy conversion from int to char
ch = num;
^
1 error
Explicit Conversion
//Java program to illustrate explicit type conversion
class Test
{ public static void main(String[] args)
{ double d = 100.04;
//explicit type casting
long l = (long)d;
//explicit type casting
int i = (int)l;
System.out.println("Double value "+d);
//fractional part lost
System.out.println("Long value "+l);
//fractional part lost
System.out.println("Int value "+i); } }

Output: Double value 100.04


Long value 100
Int value 100
Control Statement
 If Statement:
//Java Program to demonstate the use of if statement.
public class IfExample {
public static void main(String[] args) {
//defining an 'age' variable
int age=20;
//checking the age
if(age>18){
System.out.print("Age is greater than 18");
} } }
Output: Age is greater than 18
If-else statement
public class LeapYearExample {
public static void main(String[] args) {
int year=2020;
if(((year % 4 ==0) && (year % 100 !=0)) || (year % 400==0)){
System.out.println("LEAP YEAR");
}
else{
System.out.println("COMMON YEAR");
} } }

Output: LEAP YEAR


If else-if Statement
public class PositiveNegativeExample {
public static void main(String[] args) {
int number=-13;
if(number>0){
System.out.println("POSITIVE");
}else if(number<0){
System.out.println("NEGATIVE");
}else{
System.out.println("ZERO");
}
}
}
Output: NEGATIVE
Switch statement
public class SwitchExample {
public static void main(String[] args) {
//Declaring a variable for switch expression
int number=20;
//Switch expression
switch(number){
//Case statements
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
//Default case statement
default:System.out.println("Not in 10, 20 or 30"); } } }
Output: 20
Java Break Statement

 When a break statement is encountered inside a loop, the loop is immediately


terminated and the program control resumes at the next statement following
the loop.

 The Java break is used to break loop or switch statement. It breaks the
current flow of the program at specified condition. In case of inner loop, it
breaks only inner loop.
For Loops

class ForLoopExample {
public static void main(String args[]){
for(int i=10; i>1; i--){
System.out.println("The value of i is: "+i);
}
}
}
Output: The value of i is: 10
The value of i is: 9
The value of i is: 8
The value of i is: 7
The value of i is: 6
The value of i is: 5
The value of i is: 4
The value of i is: 3
The value of i is: 2
For loop example to iterate an array:
Here we are iterating and displaying array elements using the for loop.

class ForLoopExample3 {
public static void main(String args[]){
int arr[]={2,11,45,9};
//i starts with 0 as array index starts with 0 too
for(int i=0; i<arr.length; i++){
System.out.println(arr[i]);
}
}
}
Output: 2
11
45
9
Enhanced For loop
 Enhanced for loop is useful when you want to iterate Array/Collections, it is
easy to write and understand.
class ForLoopExample3 {
public static void main(String args[]){
int arr[]={2,11,45,9};
for (int num : arr) {
System.out.println(num);
}
}
Output:
} 2
11
45
9
Practice for loop

 Write a Java Program to find sum of natural numbers using for loop.
 Write a Java Program to find factorial of a number using loops.
 Write a Java Program to print Fibonacci Series using for loop.
While Loop
class WhileLoopExample {
public static void main(String args[]){
int i=10;
while(i>1){
System.out.println(i);
i--;
} } }
Output:10
9
8
7
6
5
4
3
2
Practice while loop

 Write a Java Program to display Fibonacci Series using while loop.


 Write a Java Program to find factorial using while loop.
Do-while statement
class DoWhileLoopExample {
public static void main(String args[]){
int i=10;
do{
System.out.println(i);
i--;
Output :10
}while(i>1); 9
} 8
7
} 6
5
4
3
2
Continue Statement
 Continue statement is mostly used inside loops. Whenever it is encountered inside a
loop, control directly jumps to the beginning of the loop for next iteration, skipping
the execution of statements inside loop’s body for the current iteration. This is
particularly useful when you want to continue the loop but do not want the rest of the
statements(after continue statement) in loop body to execute for that particular
iteration.
public class ContinueExample {
public static void main(String args[]){
for (int j=0; j<=6; j++) {
if (j==4)
{
continue;
}
System.out.print(j+" "); } } }

Output: 0 1 2 3 5 6
Object and class example
//Java Program to illustrate how to define a class and fields
//Defining a Student class.
class Student{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name); Output: 0
null
}
}
main outside the class
//Java Program to demonstrate having the main method in
//another class
//Creating Student class.
class Student{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main method
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name); Output: 0
null
}
}
Ways to initialize object

 There are 3 ways to initialize object in Java.

1. By reference variable
2. By method
3. By constructor
By reference variable
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name=“Balagurusamy";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
} Output: 101 Balagurusamy
By method
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n; }
void displayInformation(){System.out.println(rollno+" "+name); } }
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
Output: 111 Karan
s2.insertRecord(222,"Aryan"); 222 Aryan
s1.displayInformation();
s2.displayInformation(); } }
Constructor

 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.
 It is a special type of method which is used to initialize the object.
 Every time an object is created using the new() keyword, at least one
constructor is called.
Example of Constructor
Rules for creating Java constructor

There are some rules defined for the constructor.


 Constructor name must be the same as its class name.
 A Constructor must have no explicit return type.
 A Java constructor cannot be abstract, static, final, and synchronized.
 We can use access modifiers while declaring a constructor. It controls the
object creation. In other words, we can have private, protected, public or
default constructor in Java.
Types of Java constructors

 There are two types of constructors in Java:


1. Default constructor (no-arg constructor)
2. Parameterized constructor
Default Constructor

//Java Program to create and call a default constructor


class Bike1{
//creating a default constructor
Bike1(){
System.out.println("Bike is created");
}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
} Output: Bike is created
Parameterized Constructor
 A constructor which has a specific number of parameters is called a parameterized constructor.
//Java Program to demonstrate the use of the parameterized constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n; }
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display(); } }
Copy Constructor
class Rectangle
{
int length;
int breadth;
//constructor to initialize length and bredth of rectang of rectangle
Rectangle(int l, int b)
{
length = l;
breadth= b;
}
//copy constructor
Rectangle(Rectangle obj)
{
System.out.println("Copy Constructor Invoked");
length = obj.length;
breadth= obj.breadth;
}
//method to calcuate area of rectangle
int area()
{
return (length * breadth);
}}
//class to create Rectangle object and calculate area
class CopyConstructor {
public static void main(String[] args) {
Rectangle firstRect = new Rectangle(5,6);
Rectangle secondRect= new Rectangle(firstRect);
System.out.println("Area of First Rectangle : "+ firstRect.area());
System .out.println("Area of First Second Rectangle : "+ secondRect.area()); }}
Method Overloading
 Method Overloading is a feature that allows a class to have more than one method having the same
name, if their argument lists are different.
 If we have to perform only one operation, having same name of the methods increases the readability of
the program.
 Method overloading increases the readability of the program.
 Method overloading is an example of Static Polymorphism.
 Static Polymorphism is also known as compile time binding or early binding.
 Static binding happens at compile time. Method overloading is an example of static binding where
binding of method call to its definition happens at Compile time.
 Invalid case of method overloading: if two methods have same name, same parameters and have
different return type, then this is not a valid method overloading example. This will throw compilation
error.

 int add(int, int)


 float add(int, int)
Three ways to overload a method

 In order to overload a method, the argument lists of the methods must differ in either
of these:
1. Number of parameters.
For example: This is a valid case of overloading
add(int, int)
add(int, int, int)
2. Data type of parameters.
For example:add(int, int)
add(int, float)
3. Sequence of Data type of parameters.
For example:
add(int, float)
add(float, int)
Example 1: Overloading – Different Number of parameters in argument list

class DisplayOverloading
{ public void disp(char c)
{
System.out.println(c); }
public void disp(char c, int num) {
System.out.println(c + " "+num);
} }
class Sample
{ public static void main(String args[])
{ DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10); Output:a
} } a 10
Example 2: Overloading – Difference in data type of parameters
class DisplayOverloading2
{ public void disp(char c)
{ System.out.println(c); }
public void disp(int c)
{ System.out.println(c ); } }
class Sample2
{ public static void main(String args[])
{ DisplayOverloading2 obj = new DisplayOverloading2();
obj.disp('a');
obj.disp(5); } }

Output : a
5
Example3: Overloading – Sequence of data type of arguments
class DisplayOverloading3
{ public void disp(char c, int num)
{ System.out.println("I’m the first definition of method disp” +c);
}
public void disp(int num, char c)
{ System.out.println("I’m the second definition of method disp” + c );
} }
class Sample3
{ public static void main(String args[])
{
DisplayOverloading3 obj = new DisplayOverloading3();
obj.disp('x', 51 );
Output: I’m the first definition of method disp 51
obj.disp(52, 'y'); } } I’m the second definition of method disp 52
Constructor overloading

 Constructor overloading is a concept of having more than one constructor


with different parameters list, in such a way so that each constructor
performs a different task.
class Student {
int Roll;
String Name;
double Marks;
Student(int R,String N,double M) // Constructor 1 {
Roll = R;
Name = N;
Marks = M; }
Student(String N,double M,int R) // Constructor 2 {
Roll = R;
Name = N;
Marks = M; }
void Display() {
System.out.print("\n\t" + Roll+"\t" + Name+"\t" + Marks); } }
class ConstructorOverloadingDemo {
public static void main(String[] args) {
Student S1 = new Student(1,"Kumar",78.53); // Statement 2 Output: Roll Name Marks
Student S2 = new Student("Sumit",89.42,2); // Statement 1
1 Kumar 78.53
System.out.print("\n\tRoll\tName\tMarks\n");
2 Sumit 89.42
S1.Display();
S2.Display(); } }
role of this () in constructor overloading
public class OverloadingExample2{
private int rollNum;
OverloadingExample2() {
rollNum =100; }
OverloadingExample2(int rnum) {
this();
/*this() is used for calling the default
* constructor from parameterized constructor.
* It should always be the first statement
* inside constructor body.
*/
rollNum = rollNum+ rnum; }
public int getRollNum() {
return rollNum; }
public void setRollNum(int rollNum) {
this.rollNum = rollNum; } Output: 112
public static void main(String args[]) {
OverloadingExample2 obj = new OverloadingExample2(12);
System.out.println(obj.getRollNum()); } }
this keyword
 There can be a lot of usage of this keyword. In java, this is a reference variable that refers to the current
object.

Usage of java this keyword: Here is given the 6 usage of java this keyword.

 this can be used to refer current class instance variable.


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

 Static keyword can be used with class, variable, method and block. Static members belong to the
class instead of a specific instance, this means if you make a member static, you can access it
without object.
The static can be:
 Variable (also known as a class variable)
 Method (also known as a class method)
 Block
 Nested class
Java static variable
 If you declare any variable as static, it is known as a static variable.
 The static variable can be used to refer to the common property of all objects (which is not unique for each
object), for example, the company name of employees, college name of students, etc.
 The static variable gets memory only once in the class area at the time of class loading.
 Advantages of static variable: It makes your program memory efficient (i.e., it saves memory).
Understanding the problem without static variable
class Student{
int rollno;
String name;
String college="ITS";
}
 Suppose there are 500 students in my college, now all instance data members will get memory each time
when the object is created. All students have its unique rollno and name, so instance data member is good in
such case. Here, "college" refers to the common property of all objects. If we make it static, this field will
get the memory only once.
 //Java Program to demonstrate the use of static variable
class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n; }
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);} }
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan"); Output: 111 Karan ITS
Student s2 = new Student(222,"Aryan"); 222 Aryan ITS
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display(); } }
Java static method
 If you apply static keyword with any method, it is known as static method.
 A static method belongs to the class rather than the object of a class.
 A static method can be invoked without the need for creating an instance of a class.
 A static method can access static data member and can change the value of it.
 Example of static method
//Java Program to get the cube of a given number using the static method
class Calculate{
static int cube(int x){
return x*x*x; }
public static void main(String args[]){
int result=Calculate.cube(5); Output: 125
System.out.println(result); } }
Java static block

 Is used to initialize the static data member.


 It is executed before the main method at the time of classloading.
 Example:
class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}
Output:static block is invoked
} Hello main
Static Class
 A class can be made static only if it is a nested class.
 Nested static class doesn’t need reference of Outer class
 A static class cannot access non-static members of the Outer class
class JavaExample{
private static String str = "BeginnersBook";
//Static class
static class MyNestedClass{
//non-static method
public void disp() {
/* If you make the str variable of outer class non-static then you will get compilation error
* because: a nested static class cannot access non-static members of the outer class. */
System.out.println(str); } }
public static void main(String args[]) {
/* To create instance of nested class we didn't need the outer class instance but for a regular *nested
class you would need to create an instance of outer class first */
JavaExample.MyNestedClass obj = new JavaExample.MyNestedClass();
obj.disp(); } } Output: BeginnersBook
Inheritance

 Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).
 The idea behind inheritance in Java is that you can create new classes that are built
upon existing classes. When you inherit from an existing class, you can reuse methods
and fields of the parent class. Moreover, you can add new methods and fields in your
current class also.
 Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
 Child Class:
The class that extends the features of another class is known as child class, sub class or
derived class.
 Parent Class:
The class whose properties and functionalities are used(inherited) by another class is
known as parent class, super class or Base class.
 extends Keyword: extends is the keyword used to inherit the properties of a
class. Following is the syntax of extends keyword.

Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
Example:
class Teacher {
String designation = "Teacher";
String collegeName = "Beginnersbook";
void does(){
System.out.println("Teaching");
}
}
public class PhysicsTeacher extends Teacher{
String mainSubject = "Physics";
public static void main(String args[]){
PhysicsTeacher obj = new PhysicsTeacher();
System.out.println(obj.collegeName); Output: Beginnersbook
Teacher
System.out.println(obj.designation); Physics
System.out.println(obj.mainSubject); Teaching
obj.does();
}
}
Types of inheritance in java
 On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.
Single Inheritance Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat(); Output: barking...
eating...
}}
Multilevel Inheritance Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
Output: weeping...
class TestInheritance2{
barking...
public static void main(String args[]){ eating...
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Hierarchical Inheritance Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat(); Output: meowing...
c.meow(); eating...
c.eat();
//c.bark();//C.T.Error
}}
Method overriding
 Declaring a method in sub class which is already present in parent class is known as method
overriding.
 Overriding is done so that a child class can give its own implementation to a method which is
already provided by the parent class.
 In this case the method in parent class is called overridden method and the method in child class is
called overriding method.
 The main advantage of method overriding is that the class can give its own specific
implementation to a inherited method without even modifying the parent class code.
 Method Overriding is an example of runtime polymorphism. When a parent class reference points
to the child class object then the call to the overridden method is determined at runtime, because
during method call which method(parent class or child class) is to be executed is determined by
the type of object. This process in which call to the overridden method is resolved at runtime is
known as dynamic method dispatch
Example
class Human{
//Overridden method
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Output:Boy is eating
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}
}
Example of dynamic dispatch
class ABC{
//Overridden method
public void disp()
{ System.out.println("disp() method of parent class"); } }
class Demo extends ABC{
//Overriding method
public void disp(){
System.out.println("disp() method of Child class"); }
public void newMethod(){
System.out.println("new method of child class"); }
public static void main( String args[]) {
// When Parent class reference refers to the parent class object then in this case overridden method (the
method of parent class) is called. //
ABC obj = new ABC();
obj.disp();
/* When parent class reference refers to the child class object then the overriding method (method of
child class) is called.
* This is called dynamic method dispatch and runtime polymorphism */
Output: disp() method of parent class
ABC obj2 = new Demo();
disp() method of Child class
obj2.disp(); } }
Rules of method overriding
 The argument list should be exactly the same as that of the overridden method.
 The return type should be the same or a subtype of the return type declared in the original
overridden method in the superclass.
 The access level cannot be more restrictive than the overridden method's access level. For
example: If the superclass method is declared public then the overridding method in the
sub class cannot be either private or protected.
 Instance methods can be overridden only if they are inherited by the subclass.
 A method declared final cannot be overridden.
 A method declared static cannot be overridden but can be re-declared.
 If a method cannot be inherited, then it cannot be overridden.
 A subclass within the same package as the instance's superclass can override any superclass
method that is not declared private or final.
 A subclass in a different package can only override the non-final methods declared public
or protected.
 An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not. However, the overriding method should not
throw checked exceptions that are new or broader than the ones declared by the
overridden method. The overriding method can throw narrower or fewer exceptions than
the overridden method.
 Constructors cannot be overridden.
Super keyword
 The super keyword is used for calling the parent class method/constructor.
super.myMethod() calls the myMethod() method of base class while super() calls the
constructor of base class.
class ABC{
public void myMethod()
{
System.out.println("Overridden method");
} }
class Demo extends ABC{
public void myMethod(){
//This will call the myMethod() of parent class
super.myMethod();
Output: Class ABC: mymethod()
System.out.println("Overriding method"); } Class Test: mymethod()
public static void main( String args[]) {
Demo obj = new Demo();
obj.myMethod(); } }
Final keyword

 final is a non-access modifier applicable only to a variable, a method or a


class.
Final variables
 When a variable is declared with final keyword, its value can’t be modified,
essentially, a constant. This also means that you must initialize a final variable.
 We cannot change the value of a final variable once it is initialized. Ex:
class Demo{
final int MAX_VALUE=99;
void myMethod(){
MAX_VALUE=101;
}
public static void main(String args[]){
Demo obj=new Demo();
obj.myMethod();
}
Output:Exception in thread "main" java.lang.Error: Unresolved compilation problem:
} The final field Demo.MAX_VALUE cannot be assigned
Blank final variable
 A final variable that is not initialized at the time of declaration is known as blank final variable.
We must initialize the blank final variable in constructor of the class otherwise it will throw a
compilation error.
 Example: class Demo{
//Blank final variable
final int MAX_VALUE;
Demo(){
//It must be initialized in constructor
MAX_VALUE=100; }
void myMethod(){
System.out.println(MAX_VALUE); }
public static void main(String args[]){ Output: 100

Demo obj=new Demo();


obj.myMethod(); } }
Whats the use of blank final variable?
class StudentData{
//Blank final variable
final int ROLL_NO;

StudentData(int rnum){
//It must be initialized in constructor
ROLL_NO=rnum;
}
void myMethod(){
System.out.println("Roll no is:"+ROLL_NO);
}
public static void main(String args[]){
StudentData obj=new StudentData(1234);
obj.myMethod();
}
}
Final static variable in Java
 If we won’t initialize a static variable, then by default JVM will provide a default value for static
variable. But when we declare a static variable with final modifier then we should take care of the
following conventions:
 Declaring variables only as static can lead to change in their values by one or more instances of a class
in which it is declared.
 Declaring them as static final will help you to create a CONSTANT. Only one copy of variable exists
which can’t be reinitialize.
 Important points about final static variable:
1. Initialization of variable Mandatory : If the static variable declared as final, then we have to perform
initialization explicitly whether we are using it or not and JVM won’t provide any default value for the
final static variable.
2. Initialization before class loading : For final static variable, it is compulsory that we should perform
initialization before class loading completion. We can initialize a final static variable at the time of
declaration.
3. Initialize inside a static block : We can also initialize a final static variable inside a static block
because we should initialize a final static variable before class and we know that static block is
executed before main() method.
Initialization of variable Mandatory :
class Test {
final static int x;
public static void main(String[] args)
{ System.out.println(x);
}
}
Output: Error: variable x might not have been initialized
Initialization before class loading

 / Java program to illustrate that final static variable can be initialized at the time of declaration
class Test {
final static int x = 10;
public static void main(String[] args)
{
System.out.println(x);
}
}

Output: 10
Initialize inside a static block
// Java program to illustrate that final static variable can be initialized inside static block
class Test {
final static int x;
static
{
x = 10;
}
public static void main(String[] args)
{
System.out.println(x);
}
}
Output: 10
Java final method
 When a method is declared with final keyword, it is called a final method. A final method cannot
be overridden.
class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}
Output: Compile Time Error
Java final class
 If you make any class as final, you cannot extend it.
final class Bike{}

class Honda1 extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}
Output: Compile Time Error
There are two uses of a final class :

1. One is to prevent inheritance, as final classes cannot be extended. For


example, all Wrapper Classes like Integer, Float etc. are final classes. We can
not extend them.
 The other use of final with classes is to create an immutable class like the
predefined String class. You can not make a class immutable without making
it final.
Immutable class
 Immutable class means that once an object is created, we cannot change its content. In Java,
all the wrapper classes (like Integer, Boolean, Byte, Short) and String class is immutable. We can
create our own immutable class as well.
 Following are the requirements:
 The class must be declared as final (So that child classes can’t be created)
 Data members in the class must be declared as final (So that we can’t change the value of it
after object creation)
 A parameterized constructor
 Getter method for all the variables in it
 No setters(To not have the option to change the value of the instance variable)
Example to create Immutable class
// An immutable class
public final class Student {
final String name;
final int regNo;
public Student(String name, int regNo) {
this.name = name;
this.regNo = regNo; }
public String getName() {
return name; }
public int getRegNo() {
return regNo; } }
// Driver class
class Test {
public static void main(String args[]) {
Student s = new Student("ABC", 101);
System.out.println(s.getName());
System.out.println(s.getRegNo());
// Uncommenting below line causes error
// s.regNo = 102; } }
Abstract Methods and Classes
 A method without body (no implementation) is known as abstract method. A method must always be
declared in an abstract class, or in other words you can say that if a class has an abstract method, it
should be declared abstract as well.
 A class which is declared with the abstract keyword is known as an abstract class in Java. It can have
abstract and non-abstract methods (method with the body).
 This is how an abstract method looks in java:
public abstract int myMethod(int n1, int n2);
Rules of Abstract Method:
1. Abstract methods don’t have body, they just have method signature.
2. If a class has an abstract method it should be declared abstract, the vice versa is not true, which means
an abstract class doesn’t need to have an abstract method compulsory.
3. If a regular class extends an abstract class, then the class must have to implement all the abstract
methods of abstract parent class or it has to be declared abstract as well.
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}

Output: running safely


Java varargs
 varargs in java enables a method to accept variable number of arguments. We use
three dots (…) also known as ellipsis in the method signature to make it accept
variable arguments. For example:
public static int sum(int i, int...js ){
//do something
}
Few points to know about varargs in java are:
1. We can have only one varargs in the method.
2. Only the last argument of a method can be varargs.
3. According to java documentation, we should not overload a varargs method.
How java varargs work?
When we invoke a method with variable arguments, java compiler matches the
arguments from left to right. Once it reaches to the last varargs parameter, it creates
an array of the remaining arguments and pass it to the method. In fact varargs
parameter behaves like an array of the specified type.
Example:
//method with variable arguments
public static int sum(int i, int...js ){
int sum = i;
for(int x : js){
sum+=x;
}
return sum;
}

//method with same implementation as sum with array as argument


public static int sumArray(int i, int[] js ){
int sum = i;
for(int x : js){
sum+=x;
}
return sum;
}
Why we should not overload varargs method
public class VarargsExample {
public static void main(String[] args) {
System.out.println(sum(1));
System.out.println(sum(1,2)); //compiler error, ambiguous method
}
public static int sum(int i, int...js ){
System.out.println("sum1 called");
int sum = i;
for(int x : js){
sum+=x; }
return sum; }
public static int sum(int i, int k, Object...js ){
System.out.println("sum2 called");
int sum = i+k;
for(Object x : js){
sum+=1; }
return sum; } }
Arrays

 An array is a collection of similar type of elements which have a contiguous


memory location.
 Java array is an object which contains elements of a similar data type.
Additionally, The elements of an array are stored in a contiguous memory
location. It is a data structure where we store similar elements. We can store
only a fixed set of elements in a Java array.
 There are two types of array.

1. Single Dimensional Array

2. Multidimensional Array
Creating an array
 Creation of an array involves three steps:
1. Declaring the array.
2. Creating memory locations.
3. Putting values into the memory locations.
1. Syntax for declaring an one dimensional array
type var-name[];
OR
type[] var-name;
2. Creating memory locations.
Java allows us to create array using new operator only.
arrayname=new type[size];
The above statement does two things −
It creates an array using new type[Size].
It assigns the reference of the newly created array to the variable arrayname
Putting values into memory locations:
Type[] arrayname = {value0, value1, ..., valuek};
Example of array
/Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array Output:10
System.out.println(a[i]); 20
}} 70
40
50
Multidimensional Arrays

 Multidimensional arrays are arrays of arrays with each element of the array
holding the reference of other array. These are also known as Jagged Arrays. A
multidimensional array is created by appending one set of square brackets ([])
per dimension. Examples:

 int[][] intArray = new int[10][20]; //a 2D array or matrix


 int[][][] intArray = new int[10][20][10]; //a 3D array
 class multiDimensional {
public static void main(String args[]) {
// declaring and initializing 2D array
int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };
// printing 2D array
for (int i=0; i< 3 ; i++) {
for (int j=0; j < 3 ; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
} }}
Output:

279
361
742
Passing Arrays to Methods
class Test {
// Driver method
public static void main(String args[])
{
int arr[] = {3, 1, 2, 5, 4};
// passing array to method m1
sum(arr); }
public static void sum(int[] arr) {
// getting sum of array values
int sum = 0;
for (int i = 0; i < arr.length; i++) Output: sum of array values : 15
sum+=arr[i];
System.out.println("sum of array values : " + sum); } }
Returning Arrays from Methods
class Test {
// Driver method
public static void main(String args[])
{
int arr[] = m1();
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i]+" "); }
public static int[] m1()
{ // returning array
return new int[]{1,2,3}; Output: 1 2 3

} }
Some methods use in Array

 length()
 copyOf(original array, length)
 sort(array)
 reverse(array)
 copyOfRange(original array, from, to)
 equals(array1, array 2)
 fill(array , value)
 toString(array)
String

 string is basically an object that represents sequence of char values. An array


of characters works same as Java string. For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint
There are two ways to create String object:
By string literal: String s="welcome";
By new keyword: String s=new String("Welcome")
Example
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
Output: java
}}
strings
example
No. Method Description

1 char charAt(int index) returns char value for the particular index
2 int length() returns string length
3 static String format(String format, Object... args) returns a formatted string.

4 static String format(Locale l, String format, Object... args) returns formatted string with given locale.

5 String substring(int beginIndex) returns substring for given begin index.


6 String substring(int beginIndex, int endIndex) returns substring for given begin index and end index.

7 boolean contains(CharSequence s) returns true or false after matching the sequence of


char value.

8 static String join(CharSequence delimiter, CharSequence... elements) returns a joined string.

9 static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) returns a joined string.

10 boolean equals(Object another) checks the equality of string with the given object.

11 boolean isEmpty() checks if string is empty.


12 String concat(String str) concatenates the specified string.
13 String replace(char old, char new) replaces all occurrences of the specified char value.

14 String replace(CharSequence old, CharSequence new) replaces all occurrences of the specified
CharSequence.

15 static String equalsIgnoreCase(String another) compares another string. It doesn't check case.

16 String[] split(String regex) returns a split string matching regex.


17 String[] split(String regex, int limit) returns a split string matching regex and limit.

18 String intern() returns an interned string.

19 int indexOf(int ch) returns the specified char value index.

20 int indexOf(int ch, int fromIndex) returns the specified char value index starting with given index.

21 int indexOf(String substring) returns the specified substring index.

22 int indexOf(String substring, int fromIndex) returns the specified substring index starting with given index.

23 String toLowerCase() returns a string in lowercase.

24 String toLowerCase(Locale l) returns a string in lowercase using specified locale.

25 String toUpperCase() returns a string in uppercase.

26 String toUpperCase(Locale l) returns a string in uppercase using specified locale.

27 String trim() removes beginning and ending spaces of this string.

28 static String valueOf(int value) converts given type into string. It is an overloaded method.
Interfaces
 The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java
interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.
 In other words, you can say that interfaces can have abstract methods and variables. It cannot have a
method body.
 Declaring Interfaces: The interface keyword is used to declare an interface.
interface MyInterface
{
/* All the methods are public abstract by default
* As you see they have no body
*/
public void method1();
public void method2();
}
 An interface is similar to a class in the following ways −
 An interface can contain any number of methods.
 An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
 The byte code of an interface appears in a .class file.
 Interfaces appear in packages, and their corresponding bytecode file must be in a
directory structure that matches the package name.
 However, an interface is different from a class in several ways, including −
 You cannot instantiate an interface.
 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields. The only fields that can appear in an
interface must be declared both static and final.
 An interface is not extended by a class; it is implemented by a class.
 An interface can extend multiple interfaces.
interface MyInterface
{
public void method1();
public void method2();}
class Demo implements MyInterface{
// This class must have to implement both the abstract methods else you will get
compilation error
public void method1() {
System.out.println("implementation of method1"); }
public void method2() {
System.out.println("implementation of method2"); }
public static void main(String arg[]) {
MyInterface obj = new Demo();
obj.method1(); } }
key points to remember about interfaces:
1) We can’t instantiate an interface in java. That means we cannot create the object of an interface
2) Interface provides full abstraction as none of its methods have body. On the other hand abstract class provides partial
abstraction as it can have abstract and concrete(methods with body) methods both.
3) implements keyword is used by classes to implement an interface.
4) While providing implementation in class of any method of an interface, it needs to be mentioned as public.
5) Class that implements any interface must implement all the methods of that interface, else the class should be
declared abstract.
6) Interface cannot be declared as private, protected or transient.
7) All the interface methods are by default abstract and public.
8) Variables declared in interface are public, static and final by default.
9) Interface variables must be initialized at the time of declaration otherwise compiler will throw an error.
10) Inside any implementation class, you cannot change the variables declared in interface because by default, they are
public, static and final.
11) An interface can extend any interface but cannot implement it. Class implements interface and interface extends
interface.
12) A class can implement any number of interfaces.
13) If there are two or more same methods in two interfaces and a class implements both interfaces, implementation of
the method once is enough.
14) A class cannot implement two interfaces that have methods with same name but different return type.
15) Variable names conflicts can be resolved by interface name.
Multiple Inheritance
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}
Interface inheritance
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}
Default Method in Interface
interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}}
Output: drawing rectangle
default method
Static Method in Interface
interface Drawable{
void draw();
static int cube(int x){return x*x*x;}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}

class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw(); Output: drawing rectangle
27
System.out.println(Drawable.cube(3));
}}
Difference between abstract class and interface
Abstract class Interface
1) Abstract class can have abstract and non-abstract methods. Interface can have only abstract methods. Since Java 8, 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-static Interface has only static and final variables.
variables.

4) Abstract class can provide the implementation of interface. Interface can't provide the implementation of 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 implement An interface can extend another Java interface only.
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();
} }
Packages
 A java package is a group of similar types of classes, interfaces and sub-
packages
 Package in java can be categorized in two form, built-in package and user-
defined package.
 There are many built-in packages such as java, lang, awt, javax, swing, net,
io, util, sql etc.
Advantages of using a package in Java

 Reusability
 Better Organization
 Name Conflicts

Types of packages in Java


As mentioned in the beginning of this guide that we have two types of packages in java.

1) User defined package: The package we create is called user-defined package.

2) Built-in package: The already defined package like java.io.*, java.lang.* etc are known as built-in
packages.
Example of package
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
 How to compile java package
 Syntax: javac -d directory javafilename
 Ex: javac -d . Simple.java
 To Run: java mypack.Simple
How to access package

 There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
Using packagename.*
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Using packagename.classname
 //save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Using fully qualified name
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
How to send the class file to another directory or drive
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run: To run this program from e:\source directory, you need to set classpath of the
directory where the class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
Another way to run this program by -classpath switch of java:
e:\sources> java -classpath c:\classes mypack.Simple
How to put two public classes in a package

//save as A.java

package javatpoint;
public class A{}
//save as B.java

package javatpoint;
public class B{}
Sub packages in Java
 A package inside another package is known as sub package. For example If I create a
package inside letmecalculate package then that will be called sub package.
 Lets say I have created another package inside letmecalculate and the sub package
name is multiply. So if I create a class in this subpackage it should have this package
declaration in the beginning:
Syntax: package letmecalculate.multiply;
Multiplication.java
package letmecalculate.multiply;
public class Multiplication {
int product(int a, int b){
return a*b; } }
Now if I need to use this Multiplication class I have to either import the package like this:
import letmecalculate.multiply;
or I can use fully qualified name like this:
letmecalculate.multiply.Multiplication obj =
new letmecalculate.multiply.Multiplication();
Static import
 Static import is a feature introduced in Java programming language ( versions 5 and above
) that allows members ( fields and methods ) defined in a class as public static to be used
in Java code without specifying the class in which the field is defined.
 Simple Example of static import
import static java.lang.System.*;
class StaticImportExample{
public static void main(String args[]){
out.println("Hello");//Now no need of System.out
out.println("Java");
}
}
Access Modifier in JAVA
Exception Handling
 The Exception Handling in Java is one of the powerful mechanism to
handle the runtime errors so that normal flow of the application can
be maintained.
 Default Exception Handling : Whenever inside a method, if an
exception has occurred, the method creates an Object known as
Exception Object and hands it off to the run-time system(JVM). The
exception object contains name and description of the exception, and
current state of the program where exception has occurred. Creating
the Exception Object and handling it to the run-time system is called
throwing an Exception
Types of Java Exceptions

 There are mainly two types of exceptions: checked and unchecked. Here, an
error is considered as the unchecked exception. According to Oracle, there
are three types of exceptions:

 Checked Exception
 Unchecked Exception
 Error
Difference between Checked and Unchecked
Exceptions

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

 2) Unchecked Exception
 The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.

 3) Error
 Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Example of Exception

public class JavaExceptionExample{


public static void main(String args[]){
int a=Interger.parseInt(args[0]);
int b=Interger.parseInt(args[1]);

//code that may raise exception


int data=a/b;
System.out.println(“Raise exception");
}
}
Methods of Exception Handling

 Using try-catch block


 Using finally
 Using Throws
 Using throw
Try catch block
 Try block: The try block contains set of statements where an exception can occur. A try block is always followed by a
catch block, which handles the exception that occurs in associated try block. A try block must be followed by catch
blocks or finally block or both.
Syntax of try block
try{
//statements that may cause an exception
}
 Catch block
 A catch block is where you handle the exceptions, this block must follow the try block. A single try block can have
several catch blocks associated with it. You can catch different exceptions in different catch blocks. When an
exception occurs in try block, the corresponding catch block that handles that particular exception executes.
Syntax of try catch in java
try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}
Example
public class JavaExceptionExample{
public static void main(String args[]){
try{
int a=Interger.parseInt(args[0]);
int b=Interger.parseInt(args[1]);
//code that may raise exception
int data=a/b;
}catch(ArithmeticException e)
{System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
catch multiple exceptions
 A try block can be followed by one or more catch blocks. Each catch block must
contain a different exception handler. So, if you have to perform different tasks
at the occurrence of different exceptions, use java multi-catch block.
public class MultipleCatchBlock1 {
public static void main(String[] args) {
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"); } Output:Arithmetic Exception occurs
System.out.println("rest of the code"); } } rest of the code
Nested try catch Block

 When a try catch block is present in another try block then it is called the
nested try catch block. Each time a try block does not have a catch handler
for a particular exception, then the catch blocks of parent try block are
inspected for that exception, if match is found that that catch block
executes.
class NestingDemo{
public static void main(String args[]){ //main try-block
try{ //try-block2
try{ //try-block3
try{ int arr[]= {1,2,3,4};
// I'm trying to display the value of an element which doesn't exist. The code should throw an exception
System.out.println(arr[10]);
}catch(ArithmeticException e){
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block3"); } }
catch(ArithmeticException e){
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block2"); } }
catch(ArithmeticException e3){
System.out.print("Arithmetic Exception");
System.out.println(" handled in main try-block"); }
catch(ArrayIndexOutOfBoundsException e4){
System.out.print("ArrayIndexOutOfBoundsException");
System.out.println(" handled in main try-block"); }
catch(Exception e5){
Output:
ArrayIndexOutOfBoundsException handled in main try-block
System.out.print("Exception");
System.out.println(" handled in main try-block"); } } }
Finally Block
 Java finally block is a block that is used to execute important code such as
closing connection, stream etc.
 Java finally block is always executed whether
exception is handled or not.
 Java finally block follows try or catch block.
class Example
{
public static void main(String args[]) {
try{
int num=121/0;
System.out.println(num); }
catch(ArithmeticException e){
System.out.println("Number should not be divided by zero"); }
//Finally block will always execute even if there is no exception in try block
finally{
System.out.println("This is finally block");
}
System.out.println("Out of try-catch-finally");
} }

Output:
Number should not be divided by zero
This is finally block
Out of try-catch-finally
Throw keyword
 The Java throw keyword is used to explicitly throw an exception.
 We can throw either checked or uncheked exception in java by throw keyword. The
throw keyword is mainly used to throw custom exception.
 Syntax: throw new Throwable subclass;
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote"); }
public static void main(String args[]){
validate(13);
System.out.println("rest of the code..."); } }

Output: Exception in thread main java.lang.ArithmeticException:not valid


User Defined Exception
class MyException extends Exception
{
public MyException(String s)
{ // Call constructor of parent Exception
super(s); } }
public class Main
{ // Driver Program
public static void main(String args[])
{ try {
// Throw an object of user defined exception
throw new MyException("GeeksGeeks"); }
catch (MyException ex) {
System.out.println("Caught");
// Print the message from MyException object
System.out.println(ex.getMessage()); } } }
Throws Keyword
 Throws keyword is used for handling checked exceptions . By using throws we can declare
multiple exceptions in one go.
import java.io.*;
class ThrowExample {
void myMethod(int num)throws IOException, ClassNotFoundException{
if(num==1)
throw new IOException("IOException Occurred");
else
throw new ClassNotFoundException("ClassNotFoundException"); } }
public class Example1{
public static void main(String args[]){
try{
ThrowExample obj=new ThrowExample();
obj.myMethod(1);
}catch(Exception ex){
System.out.println(ex); } } }
Catching Multiple Exception in the same catch block
 In Java 7 it was made possible to catch multiple different exceptions in the same catch
block. This is also known as multi catch.
try {

// execute code that may throw 1 of the 3 exceptions below.

} catch(SQLException e) {
logger.log(e);

} catch(IOException e) {
logger.log(e);

} catch(Exception e) {
logger.severe(e);
}
try {

// execute code that may throw 1 of the 3 exceptions below.

} catch(SQLException | IOException e) {
logger.log(e);

} catch(Exception e) {
logger.severe(e);
}
Try with resource statement
 The Java try with resources is an exception handling mechanism that can automatically close
resources like a Java InputStream or a JDBC Connection when you are done with them. To do so,
you must open and use the resource within a Java try-with-resources block. When the execution
leaves the try-with-resources block, any resource opened within the try-with-resources block is
automatically closed, regardless of whether any exceptions are thrown either from inside the try-
with-resources block, or when attempting to close the resources.
Ex: private static void printFile() throws IOException {

try(FileInputStream input = new FileInputStream("file.txt")) {

int data = input.read();


while(data != -1){
System.out.print((char) data);
data = input.read();
}
}
}
Enhancement in try resource statement
When the try block finishes the FileInputStream will be closed automatically. This is
possible because FileInputStream implements the Java interface
java.lang.AutoCloseable. All classes implementing this interface can be used inside the
try-with-resources construct.

private static void printFile() throws IOException {


FileInputStream input = new FileInputStream("file.txt");
try(input) {
int data = input.read();
while(data != -1){
System.out.print((char) data);
data = input.read();
}
}
}
Multithreading
 A thread is a light-weight smallest part of a process that can run concurrently with the
other parts(other threads) of the same process.
 Threads are independent because they all have separate path of execution that’s the
reason if an exception occurs in one thread, it doesn’t affect the execution of other
threads.
 All threads of a process share the common memory.
 The process of executing multiple threads simultaneously is known as
multithreading.
 Java Multithreading is mostly used in games, animation, etc.
 Advantages of Java Multithreading
 1) It doesn't block the user because threads are independent and you can perform
multiple operations at the same time.
 2) You can perform many operations together, so it saves time.
 3) Threads are independent, so it doesn't affect other threads if an exception occurs in
a single thread.

There are two ways to create a thread:

1. By extending Thread class


class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Output:thread is running...
2. By implementing Runnable interface
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Output:thread is running...
Life Cycle of a Thread
Stages of the life cycle

 New − A new thread begins its life cycle in the new state. It remains in this state until the program starts
the thread. It is also referred to as a born thread.

 Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is
considered to be executing its task.

 Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread
to perform a task. A thread transitions back to the runnable state only when another thread signals the
waiting thread to continue executing.

 Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A
thread in this state transitions back to the runnable state when that time interval expires or when the
event it is waiting for occurs.

 Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or
otherwise terminates.
Stopping and Blocking a thread

 Use stop() to stop a thread

 To temporarily block/suspend a thread we can use sleep(), suspend() and


wait() maethod.
 These methods cause the thread to go into the blocked (non runnable) state.
 The thread will return to the runnable state when the specified time is
elapsed in the case of sleep(), the resume() method is invoked in case of
suspend() and notify() method is called in case of wait().
Thread priority

 Each thread have a priority. Priorities are represented by a number between 1


and 10. In most cases, thread schedular schedules the threads according to
their priority (known as preemptive scheduling). But it is not guaranteed
because it depends on JVM specification that which scheduling it chooses.
 3 constants defined in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is
1 and the value of MAX_PRIORITY is 10.
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());

}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();

Output:running thread name is:Thread-0


}
running thread priority is:10
} running thread name is:Thread-1
running thread priority is:1
Synchronization

 Synchronization in java is the capability to control the access of multiple threads to any shared resource.
 Java Synchronization is better option where we want to allow only one thread to access the shared
resource.
 The synchronization is mainly used to : 1. To prevent thread interference.
2. To prevent consistency problem.
class Table{

synchronized void printTable(int n){//synchronized method

for(int i=1;i<=5;i++){

System.out.println(n*i);

try{ Thread.sleep(400);

}catch(Exception e){System.out.println(e);} } } }

class MyThread1 extends Thread{

Table t;

MyThread1(Table t){

this.t=t; }

public void run(){

t.printTable(5); } }

class MyThread2 extends Thread{

Table t;

MyThread2(Table t){

this.t=t; }

public void run(){

t.printTable(100); } }

public class TestSynchronization2{

public static void main(String args[]){

Table obj = new Table();//only one object

MyThread1 t1=new MyThread1(obj);


Inter thread communication
 Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with
each other.
 Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical
section and another thread is allowed to enter (or lock) in the same critical section to be executed.It is
implemented by following methods of Object class:
1. wait() 2. notify() 3. notifyAll()
1) wait() method: Causes current thread to release the lock and wait until either another thread invokes the notify()
method or the notifyAll() method for this object, or a specified amount of time has elapsed.
 The current thread must own this object's monitor, so it must be called from the synchronized method only
otherwise it will throw exception. Method Description:
1. public final void wait()throws InterruptedException (waits until object is notified.)
2. public final void wait(long timeout)throws InterruptedException (waits for the specified amount of time.)
2) notify() method: Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on
this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the
implementation. Syntax:
public final void notify()
3) notifyAll() method: Wakes up all threads that are waiting on this object's monitor. Syntax:
public final void notifyAll()

You might also like