[go: up one dir, main page]

0% found this document useful (0 votes)
37 views49 pages

X-51nBc ZqYiRfoi6b EU-yLfUnMoDvnKMsAlF77FxQhGeTJiPb2nA

This document provides an overview of Java including its history, applications, types of Java applications, flavors of Java, features of the Java language, and the Java Virtual Machine (JVM). It discusses that Java was developed in 1995 by Sun Microsystems and is an object-oriented, platform independent language used widely for desktop, web, enterprise, and mobile applications. The document also summarizes the main editions of Java including J2SE, J2ME, J2EE, and Java Card and describes the key features and components of the JVM.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views49 pages

X-51nBc ZqYiRfoi6b EU-yLfUnMoDvnKMsAlF77FxQhGeTJiPb2nA

This document provides an overview of Java including its history, applications, types of Java applications, flavors of Java, features of the Java language, and the Java Virtual Machine (JVM). It discusses that Java was developed in 1995 by Sun Microsystems and is an object-oriented, platform independent language used widely for desktop, web, enterprise, and mobile applications. The document also summarizes the main editions of Java including J2SE, J2ME, J2EE, and Java Card and describes the key features and components of the JVM.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Unit-I Introduction and Object-Oriented Programming

Why 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.
Application
According to Sun, 3 billion devices run Java. There are many devices where Java is
currently used. Some of them are as follows:
Desktop Applications such as acrobat reader, media player, antivirus, etc.
Web Applications such as irctc.co.in, javatpoint.com, etc.
Enterprise Applications such as banking applications.
1. Mobile
2. Embedded System
3. Smart Card
4. Robotics
5. Games, etc.
Types of Java Applications
There are mainly 4 types of applications that can be created using Java programming:
1) Destop Application
Standalone applications are also known as desktop applications or window-based
applications. These are traditional software that we need to install on every machine.
Examples of standalone application are Media player, antivirus, etc. AWT and Swing
are used in Java for creating standalone applications.
2) Web Application
An application that runs on the server side and creates a dynamic page is called a web
application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies
are used for creating web applications in Java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is called
an enterprise application. It has advantages like high-level security, load balancing,
and clustering. In Java, EJB is used for creating enterprise applications.
4) Mobile Application
An application which is created for mobile devices is called a mobile application.
Currently, Android and Java ME are used for creating mobile applications.

Flavors of Java:
1. J2SE(Java Platform, Standard Edition)
Also known as Core Java, this is the most basic and standard version of Java.It’s the
purest form of Java, a basic foundation for all other editions.
It consists of a wide variety of general purpose API’s (like java.lang, java.util) as well
as many special purpose APIs
J2SE is mainly used to create applications for Desktop environment.
It consist all the basics of Java the language, variables, primitive data types, Arrays,
Streams, Strings Java Database Connectivity(JDBC) and much more. This is the
standard, from which all other editions came out, according to the needs of the time.
The famous JVM of Java, the heart of Java development, was also given by this
edition only.It’s because of this feature, that Java has such a wide usage.
2. J2ME(Java Platform, Micro Edition)
This version of Java is mainly concentrated for the applications running on embedded
systems, mobiles and small devices.(which was a constraint before it’s development)
Portability and security was its main features.
JavaFX is another such edition of Java technology, which is now merged with J2SE
8.It is mainly used, to create rich GUI (Graphical User Interface) in Java apps.
It replaces Swings (in J2SE), with itself as the standard GUI library.
It is supported by both Desktop environment as well as web browsers.
PersonalJava was another edition, which was not deployed much, as its function was
fulfilled by further versions of J2ME. Made to support World Wide Web (and Java
applets) and consumer electronics.
PersonalJava was also used for embedded systems and mobile. But, it was
discontinued in its earlier stages.
Constraints included limited processing power, battery limitation, small display etc.
Also, the J2ME apps help in using web compression technologies, which in turn,
reduce network usage, and hence cheap internet accessibility.
J2ME uses many libraries and API’s of J2SE, as well as, many of it’s own.
The basic aim of this edition was to work on mobiles, wireless devices, set top boxes
etc.
Old Nokia phones, which used Symbian OS, used this technology.
Most of the apps, developed for the phones(prior to smartphones era), were built on
J2ME platform only(the .jar apps on Nokia app store).
J2EE(Java Platform, Enterprise Edition)
The Enterprise version of Java has a much larger usage of Java, like development of
web services, networking, server side scripting and other various web based
applications.
J2EE is a community driven edition, i.e. there is a lot of continuous contributions from
industry experts, Java developers and other open source organizations.
J2EE uses many components of J2SE, as well as, has many new features of it’s own
like Servlets, JavaBeans, Java Message Services, adding a whole new functionalities
to the language.
J2EE uses HTML, CSS, JavaScript etc., so as to create web pages and web services.
It’s also one of the most widely accepted web development standard.
There are also many languages like .net and php, which can do that work, but what
distinguishes it from other languages is the versatility, compatibility and security
features, which are not that much prominent in other languages.
Nowadays, developers are going more towards this edition, as it more versatile and
web friendly that it’s other counterparts.
Apart from these three versions, there was another Java version, released Java Card.
This edition was targeted, to run applets smoothly and securely on smart cards and
similar technology.
Features of Java Language
The prime reason behind creation of Java was to bring portability and security feature
into a computer language. Beside these two major features, there were many other
features that played an important role in moulding out the final form of this
outstanding language. Those features are :
1) Simple
Java is easy to learn and its syntax is quite simple, clean and easy to understand.The
confusing and ambiguous concepts of C++ are either left out in Java or they have been
re-implemented in a cleaner way.
Eg : Pointers and Operator Overloading are not there in java but were an important
part of C++.
2) Object Oriented
In java, everything is an object which has some data and behaviour. Java can be easily
extended as it is based on Object Model. Following are some basic concept of OOP's.
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation
3) Robust
Java makes an effort to eliminate error prone codes by emphasizing mainly on
compile time error checking and runtime checking. But the main areas which Java
improved were Memory Management and mishandled Exceptions by introducing
automatic Garbage Collector and Exception Handling.
4) Platform Independent
Unlike other programming languages such as C, C++ etc which are compiled into
platform specific machines. Java is guaranteed to be write-once, run-anywhere
language.
On compilation Java program is compiled into bytecode. This bytecode is platform
independent and can be run on any machine, plus this bytecode format also provide
security. Any machine with Java Runtime Environment can run Java Programs.

5) Secure
When it comes to security, Java is always the first choice. With java secure features it
enable us to develop virus free, temper free system. Java program always runs in Java
runtime environment with almost null interaction with system OS, hence it is more
secure.
6) Multi Threading
Java multithreading feature makes it possible to write program that can do many tasks
simultaneously. Benefit of multithreading is that it utilizes same memory and other
resources to execute multiple threads at the same time, like While typing, grammatical
errors are checked along.
7) Architectural Neutral
Compiler generates bytecodes, which have nothing to do with a particular computer
architecture, hence a Java program is easy to intrepret on any machine.
8) Portable
Java Byte code can be carried to any platform. No implementation dependent features.
Everything related to storage is predefined, example: size of primitive data types
9) High Performance
Java is an interpreted language, so it will never be as fast as a compiled language like
C or C++. But, Java enables high performance with the use of just-in-time compiler.
10) Distributed
Java is also a distributed language. Programs can be designed to run on computer
networks. Java has a special class library for communicating using TCP/IP protocols.
Creating network connections is very much easy in Java as compared to C/C++.
JVM–The heart of Java
Java virtual Machine(JVM) is a virtual Machine that provides runtime environment to
execute java byte code. The JVM doesn't understand Java typo, that's why you
compile your *.java files to obtain *.class files that contain the bytecodes
understandable by the JVM.
JVM control execution of every Java program. It enables features such as automated
exception handling, Garbage-collected heap.
JVM Architecture

Class Loader : Class loader loads the Class for execution.


Method area : Stores pre-class structure as constant pool.
Heap : Heap is a memory area in which objects are allocated.
Stack : Local variables and partial results are store here. Each thread has a private
JVM stack created when the thread is created.
Program register : Program register holds the address of JVM instruction currently
being executed.
Native method stack : It contains all native used in application.
Executive Engine : Execution engine controls the execute of instructions contained
in the methods of the classes.
Native Method Interface : Native method interface gives an interface between java
code and native code during execution.
Native Method Libraries : Native Libraries consist of files required for the
execution of native code.
Difference between JDK and JRE
JRE : The Java Runtime Environment (JRE) provides the libraries, the Java Virtual
Machine, and other components to run applets and applications written in the Java
programming language. JRE does not contain tools and utilities such as compilers or
debuggers for developing applets and applications.

JDK : The JDK also called Java Development Kit is a superset of the JRE, and
contains everything that is in the JRE, plus tools such as the compilers and debuggers
necessary for developing applets and applications.
Java’s Magic Byte code
Byte Code can be defined as an intermediate code generated by the compiler after the
compilation of source code(JAVA Program). This intermediate code makes Java a
platform-independent language.
How is Byte Code generated?
Compiler converts the source code or the Java program into the Byte Code(or machine
code), and secondly, the Interpreter executes the byte code on the system. The
Interpreter can also be called JVM(Java Virtual Machine). The byte code is the
common piece between the compiler(which creates it) and the Interpreter (which runs
it).

Suppose you are writing your first JAVA program.

class demo {
public static void main (String[] args) {
System.out.println("Hello");
}
}
 The above-written code is called JAVA source code.
 The compiler compiles the source code.
 Finally, Interpreter executes the compiled source code.
Whenever we write any program, it is not written in machine code. We write it in a
high-level language like JAVA, C++, Python, etc. But the computer understands only
the machine code. So when we execute our program, it is first converted into machine
code or Byte code by the compiler and then executed by the Interpreter.
Installing Java:
Step 1: Verify that it is already installed or not
Check whether Java is already installed on the system or not. In my case, it is not
installed therefore I need to install JDK 1.8 on my computer.

Step 2: Download JDK


Click the below link to download jdk 1.8 for you windows 64 bit system.
Download JDK For Windows
https://download.oracle.com/java/19/latest/jdk-19_windows-
x64_bin.exe

There are available releases for Linux and mac operating systems. You can visit the
official link for JDK distributions.
Step 3: Install JDK
Open the executable file which you have just downloaded and follow the steps.
Click Next to continue.

Just Choose Development Tools and click Next.

Set up is being ready.


Choose the Destination folder in which you want to install JDK. Click Next to
continue with the installation.
Set up is installing Java to the computer.

We have successfully installed Java SE development kit 8. Close the installation set
up.
Object Oriented Programming Class Fundamentals
Class:-
1. Class is a set of object which shares common characteristics/ behavior and common
properties/ attributes.
2. Class is not a real world entity. It is just a template or blueprint or prototype from
which objects are created.
3. Class does not occupy memory.
4. Class is a group of variables of different data types and group of methods.

A class in java can contain:


• data member
• method
• constructor
• nested class and
• interface
Syntax to declare a class:
access_modifier class<class_name>
{
data member;
method;
constructor;
nested class;
interface;
}
Example:
class Student
{
int id;//data member (also instance variable)
String name; //data member (also instance variable)
public static void main(String args[])
{
Student s1=new Student();//creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
}
}
A class is a user defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one type.
In general, class declarations can include these components, in order:
1. Modifiers: A class can be public or has default access (Refer this for details).
2. Class keyword: class keyword is used to create a class.
3. Class name: The name should begin with an initial letter (capitalized by
convention).
4. Superclass(if any): The name of the class’s parent (superclass), if any,
preceded by the keyword extends. A class can only extend (subclass) one
parent.
5. Interfaces(if any): A comma-separated list of interfaces implemented by the
class, if any, preceded by the keyword implements. A class can implement
more than one interface.
6. Body: The class body is surrounded by braces, { }.
Constructors are used for initializing new objects. Fields are variables that provide the
state of the class and its objects, and methods are used to implement the behavior of
the class and its objects.
There are various types of classes that are used in real time applications such as nested
classes, anonymous classes, lambda expressions.
Object:
It is a basic unit of Object-Oriented Programming and represents real life entities. A
typical Java program creates many objects, which as you know, interact by invoking
methods. An object consists of :
1. State: It is represented by attributes of an object. It also reflects the properties
of an object.
2. Behavior: It is represented by methods of an object. It also reflects the
response of an object with other objects.
3. Identity: It gives a unique name to an object and enables one object to interact
with other objects.
Example:
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
public class Test
{
// using Dog object
Animal obj = new Dog();
// using Cat object
obj = new Cat();
}

Constructor:
Java constructors or constructors in Java is a terminology used to construct something
in our programs. A constructor in Java is a special method that is used to initialize
objects. The constructor is called when an object of a class is created. It can be used to
set initial values for object attributes.
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 the 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.
How Constructors are Different From Methods in Java?
 Constructors must have the same name as the class within which it is defined it
is not necessary for the method in Java.
 Constructors do not return any type while method(s) have the return type
or void if does not return any value.
 Constructors are called only once at the time of Object creation while method(s)
can be called any number of times.
Now let us come up with the syntax for the constructor being invoked at the time of
object or instance creation.
class fruit
{
.......

// A Constructor
fruit() {
}

.......
}
// We can create an object of the above class
// using the below statement. This statement
// calls above constructor.
fruit obj = new fruit();
The first line of a constructor is a call to super() or this(), (a call to a constructor of a
super-class or an overloaded constructor), if you don’t type in the call to super in your
constructor the compiler will provide you with a non-argument call to super at the first
line of your code, the super constructor must be called to create an object:

class Fruit {
Fruit() {
}
public static void main(String[] args)
{
Fruit f1 = new Fruit();
}
}
When Constructor is called?
Each time an object is created using a new() keyword, at least one constructor (it
could be the default constructor) is invoked to assign initial values to the data
members of the same class.
Rules for writing constructors are as follows:
 The constructor(s) of a class must have the same name as the class name in
which it resides.
 A constructor in Java cannot be abstract, final, static, or Synchronized.
 Access modifiers can be used in constructor declaration to control its access i.e
which other class can call the constructor.
So by far, we have learned constructors are used to initialize the object’s state.
Like methods, a constructor also contains a collection of statements(i.e. instructions)
that are executed at the time of Object creation.
Types of Constructors in Java
Now is the correct time to discuss the types of the constructor, so primarily there are
two types of constructors in java:
1. No-argument constructor
2. Parameterized Constructor
1. No-argument constructor
A constructor that has no parameter is known as the No-argument or Zero argument
constructor. If we don’t define a constructor in a class, then the compiler creates
a constructor(with no arguments) for the class. And if we write a constructor with
arguments or no arguments then the compiler does not create a default constructor.
// Java Program to illustrate calling a
// no-argument constructor
class Fruit {
int num;
String name;
// this would be invoked while an object
// of that class is created.
Fruit() { System.out.println("Constructor called"); }
}

class Demo {
public static void main(String[] args)
{
// this would invoke default constructor.
Fruit f1 = new Fruit();
// Default constructor provides the default
// values to the object like 0, null
System.out.println(f1.name);
System.out.println(f1.num);
}
}
Output:
Constructor called
null
0
2. 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.
Example:
class student {
// data members of the class.
String name;
int id;
student(String name, int id)
{
this.name = name;
this.id = id;
}
}
class Demo1 {
public static void main(String[] args)
{
// This would invoke the parameterized constructor.
student s1 = new student("avinash", 68);
System.out.println("Student Name :" + s1.name + " and Student Id :" + s1.id);
}
}
Output:
Student Name :avinash and Student Id :68
JustLike methods, we can overload constructors for creating objects in different ways.
The compiler differentiates constructors on the basis of the number of parameters,
types of parameters, and order of the parameters.

Example:
// Java Program to illustrate constructor overloading
// using same task (addition operation ) for different
// types of arguments.
import java.io.*;

class student {
// constructor with one argument
student(String name)
{
System.out.println("Constructor with one " + "argument - String : " + name);
}

// constructor with two arguments


student(String name, int age)
{

System.out.println("Constructor with two arguments : " + " String and Integer :


" + name + " " + age);
}

// Constructor with one argument but with different


// type than previous..
student(long id)
{
System.out.println("Constructor with one argument : " + "Long : " + id);
}
}
class Demo1 {
public static void main(String[] args)
{
// Creating the objects of the class named 'Geek'
// by passing different arguments

// Invoke the constructor with one argument of


// type 'String'.
student s1 = new student("Shikhar");
// Invoke the constructor with two arguments
student s2 = new student("Dharmesh", 26);

// Invoke the constructor with one argument of


// type 'Long'.
student s3 = new student(325614567);
}
}
Output:
Constructor with one argument - String : Shikhar
Constructor with two arguments : String and Integer : Dharmesh 26
Constructor with one argument : Long : 325614567

Access Modifiers
What are Access Modifiers?
In Java, access modifiers are used to set the accessibility (visibility) of classes,
interfaces, variables, methods, constructors, data members, and the setter methods.
For example,
class Animal {
public void method1() {...}

private void method2() {...}


}

In the above example, we have declared 2 methods: method1() and method2(). Here,
method1 is public - This means it can be accessed by other classes.
method2 is private - This means it can not be accessed by other classes.
Types of Access Modifier
There are four access modifiers keywords in Java and they are:
Default Access Modifier

If we do not explicitly specify any access modifier for classes, methods, variables, etc, then by default
the default access modifier is considered. For example,

package defaultPackage;

class Logger {

void message(){

System.out.println("This is a message");

Here, the Logger class has the default access modifier. And the class is visible to all
the classes that belong to the defaultPackage package. However, if we try to use
the Logger class in another class outside of defaultPackage, we will get a compilation
error.
Private Access Modifier
When variables and methods are declared private, they cannot be accessed outside of
the class. For example,
class Data {
// private variable
private String name;
}
public class Main {
public static void main(String[] main){
// create an object of Data
Data d = new Data();
// access private variable and field from another class
d.name = "Hello World";
}
}
Output:
In the above example, we have declared a private variable named name. When we run
the program, we will get the following error:

Main.java:18: error:
name has

The error is generated because we are trying to access the private variable of
the Data class from the Main class.
You might be wondering what if we need to access those private variables. In this case,
we can use the getters and setters method.
For example,
class Data {
private String name;
// getter method
public String getName() {
return this.name;
}
// setter method
public void setName(String name) {
this.name= name;
}
}
public class Main {
public static void main(String[] main){
Data d = new Data();
// access the private variable using the getter and setter
d.setName("James Gosling");
System.out.println(d.getName());
}
}
Output:
The name is James Gosling
In the above example, we have a private variable named name. In order to access the
variable from the outer class, we have used methods: getName() and setName(). These
methods are called getter and setter in Java.
Here, we have used the setter method (setName()) to assign value to the variable and
the getter method (getName()) to access the variable.
We have used this keyword inside the setName() to refer to the variable of the class.
Protected Access Modifier
When methods and data members are declared protected, we can access them within
the same package as well as from subclasses. For example,
class Animal {
// protected method
protected void display() {
System.out.println("I am an animal");
}
}
class Dog extends Animal {
public static void main(String[] args) {
// create an object of Dog class
Dog dog = new Dog();
// access protected method
dog.display();
}
}
Output:
I am an animal
In the above example, we have a protected method named display() inside
the Animal class. The Animal class is inherited by the Dog class. To learn more about
inheritance, visit Java Inheritance.
We then created an object dog of the Dog class. Using the object we tried to access the
protected method of the parent class.
Since protected methods can be accessed from the child classes, we are able to access
the method of Animal class from the Dog class.

Public Access Modifier


When methods, variables, classes, and so on are declared public, then we can access
them from anywhere. The public access modifier has no scope restriction. For
example,
// Animal.java file
// public class
public class Animal {
// public variable
public int legCount;
// public method
public void display() {
System.out.println("I am an animal.");
System.out.println("I have " + legCount + " legs.");
}
}
// Main.java
public class Main {
public static void main( String[] args ) {
// accessing the public class
Animal animal = new Animal();
// accessing the public variable
animal.legCount = 4;
// accessing the public method
animal.display();
}
}

Output:
I am an animal.
I have 4 legs.
Here,
The public class Animal is accessed from the Main class.
The public variable legCount is accessed from the Main class.
The public method display() is accessed from the Main class.
Access Modifiers Summarized in one figure

Accessibility of all Access Modifiers in Java


Access modifiers are mainly used for encapsulation. It can help us to control what part
of a program can access the members of a class. So that misuse of data can be
prevented.

Inner Class & Anonymous Classes:


In Java, you can define a class within another class. Such class is known as nested
class. For example,
class OuterClass {
// ...
class NestedClass {
// ...
}
}
There are two types of nested classes you can create in Java.
1. Non-static nested class (inner class)
2. Static nested class
Non-Static Nested Class (Inner Class)
A non-static nested class is a class within another class. It has access to members of
the enclosing class (outer class). It is commonly known as inner class.
Since the inner class exists within the outer class, you must instantiate the outer class
first, in order to instantiate the inner class.
Here's an example of how you can declare inner classes in Java.
Example 1: Inner class
class CPU {
double price;
// nested class
class Processor{
// members of nested class
double cores;
String manufacturer;
double getCache(){
return 4.3;
}
}
// nested protected class
protected class RAM{
// members of protected nested class
double memory;
String manufacturer;
double getClockSpeed(){
return 5.5;
}
}
}
public class Main {
public static void main(String[] args) {
// create object of Outer class CPU
CPU cpu = new CPU();
// create an object of inner class Processor using outer class
CPU.Processor processor = cpu.new Processor();
// create an object of inner class RAM using outer class CPU
CPU.RAM ram = cpu.new RAM();
System.out.println("Processor Cache = " + processor.getCache());
System.out.println("Ram Clock speed = " + ram.getClockSpeed());
}
}
Output:
Processor Cache = 4.3
Ram Clock speed = 5.5
In the above program, there are two nested classes: Processor and RAM inside the
outer class: CPU. We can declare the inner class as protected. Hence, we have
declared the RAM class as protected.
Inside the Main class, we first created an instance of an outer class CPU named cpu.
Using the instance of the outer class, we then created objects of inner classes:

CPU.Processor processor = cpu.new Processor;


CPU.RAM ram = cpu.new RAM();
Static Nested Class
In Java, we can also define a static class inside another class. Such class is known
as static nested class. Static nested classes are not called static inner classes.
Unlike inner class, a static nested class cannot access the member variables of the
outer class. It is because the static nested class doesn't require you to create an
instance of the outer class.
OuterClass.NestedClass obj = new OuterClass.NestedClass();
Here, we are creating an object of the static nested class by simply using the class
name of the outer class. Hence, the outer class cannot be referenced
using OuterClass.this.
Example
class MotherBoard {
// static nested class
static class USB{
int usb2 = 2;
int usb3 = 1;
int getTotalPorts(){
return usb2 + usb3;
}
}
}
public class Main {
public static void main(String[] args) {
// create an object of the static nested class
// using the name of the outer class
MotherBoard.USB usb = new MotherBoard.USB();
System.out.println("Total Ports = " + usb.getTotalPorts());
}
}
Output:
Total Ports = 3
In the above program, we have created a static class named USB inside the
class MotherBoard. Notice the line,
MotherBoard.USB usb = new MotherBoard.USB();
Here, we are creating an object of USB using the name of the outer class.
Now, let's see what would happen if you try to access the members of the outer class:
Accessing members of Outer class inside Static Inner Class
class MotherBoard {
String model;
public MotherBoard(String model) {
this.model = model;
}
// static nested class
static class USB{
int usb2 = 2;
int usb3 = 1;
int getTotalPorts(){
// accessing the variable model of the outer classs
if(MotherBoard.this.model.equals("MSI")) {
return 4;
}
else {
return usb2 + usb3;
}
}
}
}
public class Main {
public static void main(String[] args) {
// create an object of the static nested class
MotherBoard.USB usb = new MotherBoard.USB();
System.out.println("Total Ports = " + usb.getTotalPorts());
}
}
When we try to run the program, we will get an error:
Output:
error: non-static variable this cannot be referenced from a static context
This is because we are not using the object of the outer class to create an object of the
inner class. Hence, there is no reference to the outer class Motherboard stored
in Motherboard.this.
Anonymous Class
In Java, a class can contain another class known as nested class. It's possible to create
a nested class without giving any name.
A nested class that doesn't have any name is known as an anonymous class.
An anonymous class must be defined inside another class. Hence, it is also known as
an anonymous inner class. Its syntax is:
class outerClass {
// defining anonymous class
object1 = new Type(parameterList) {
// body of the anonymous class
};
}
Anonymous classes usually extend subclasses or implement interfaces.
Here, Type can be
a superclass that an anonymous class extends
an interface that an anonymous class implements
The above code creates an object, object1, of an anonymous class at runtime.
Example 1: Anonymous Class Extending a Class
class Polygon {
public void display() {
System.out.println("Inside the Polygon class");
}
}
class AnonymousDemo {
public void createClass() {
// creation of anonymous class extending class Polygon
Polygon p1 = new Polygon() {
public void display() {
System.out.println("Inside an anonymous class.");
}
};
p1.display();
}
}
class Main {
public static void main(String[] args) {
AnonymousDemo an = new AnonymousDemo();
an.createClass();
}
}
Output:
Inside an anonymous class.
In the above example, we have created a class Polygon. It has a single
method display().We then created an anonymous class that extends the
class Polygon and overrides the display() method.
When we run the program, an object p1 of the anonymous class is created. The object
then calls the display() method of the anonymous class.
Example 2: Anonymous Class Implementing an Interface
interface Polygon {
public void display();
}
class AnonymousDemo {
public void createClass() {
// anonymous class implementing interface
Polygon p1 = new Polygon() {
public void display() {
System.out.println("Inside an anonymous class.");
}
};
p1.display();
}
}
class Main {
public static void main(String[] args) {
AnonymousDemo an = new AnonymousDemo();
an.createClass();
}
}
Output:
Inside an anonymous class.
In the above example, we have created an anonymous class that implements
the Polygon interface.
Advantages of Anonymous Classes
In anonymous classes, objects are created whenever they are required. That is, objects
are created to perform some specific tasks. For example,
Object = new Example() {
public void display() {
System.out.println("Anonymous class overrides the method display().");
}
};
Here, an object of the anonymous class is created dynamically when we need to
override the display() method.
Abstract Class
The abstract class in Java cannot be instantiated (we cannot create objects of abstract
classes). We use the abstract keyword to declare an abstract class. The abstract class
in Java cannot be instantiated (we cannot create objects of abstract classes). We use
the keyword to declare an abstract class.
abstract
The Syntax for Abstract Class
To declare an abstract class, we use the access modifier first, then the "abstract"
keyword, and the class name shown below.
Syntax:
<Access_Modifier> abstract class <Class_Name> {
//Data_Members;
//Statements;
//Methods;
}
For Example:
// create an abstract class
abstract class Language {
// fields and methods
}
...
// try to create an object Language
// throws an error
Language obj = new Language();
An abstract class can have both the regular methods and abstract methods. For
example,
abstract class Language {
// abstract method
abstract void method1();
// regular method
void method2() {
System.out.println("This is regular method");
}
}
some important observations about abstract classes are as follows:
 The keyword "abstract" is mandatory while declaring an abstract class in Java.
 Abstract classes cannot be instantiated directly.
 An abstract class must have at least one abstract method.
 An abstract class includes final methods.
 An abstract class may also include non-abstract methods.
 An abstract class can consist of constructors and static methods.
Example:
abstract class Language {
// method of abstract class
public void display() {
System.out.println("This is Java Programming");
}
}
class Main extends Language {
public static void main(String[] args) {
// create an object of Main
Main obj = new Main();
// access method of abstract class
// using object of Main class
obj.display();
}
}
Output:
This is Java programming
In the above example, we have created an abstract class named Language. The class
contains a regular method display().
We have created the Main class that inherits the abstract class. Notice the statement,
obj.display();
Here, obj is the object of the child class Main. We are calling the method of the
abstract class using the object obj.
Implementing Abstract Methods
If the abstract class includes any abstract method, then all the child classes inherited
from the abstract superclass must provide the implementation of the abstract method.
For example,
abstract class Animal {
abstract void makeSound();
public void eat() {
System.out.println("I can eat.");
}
}
class Dog extends Animal {
// provide implementation of abstract method
public void makeSound() {
System.out.println("Bark bark");
}
}
class Main {
public static void main(String[] args) {
// create an object of Dog class
Dog d1 = new Dog();
d1.makeSound();
d1.eat();
}
}
Output
Bark bark
I can eat.
In the above example, we have created an abstract class Animal. The class contains an
abstract method makeSound() and a non-abstract method eat().
We have inherited a subclass Dog from the superclass Animal. Here, the
subclass Dog provides the implementation for the abstract method makeSound().
We then used the object d1 of the Dog class to call methods makeSound() and eat().

Interface
An Interface in Java programming language is defined as an abstract type used to
specify the behavior of a class. An interface in Java is a blueprint of a behaviour. A
Java interface contains static constants and abstract methods.
 Interfaces specify what a class must do and not how. It is the blueprint of the
behaviour.
 Interface do not have constructor.
 Represent behaviour as interface unless every sub-type of the class is guarantee
to have that behaviour.
 An Interface is about capabilities like a Player may be an interface and any
class implementing Player must be able to (or must implement) move(). So it
specifies a set of methods that the class has to implement.
 If a class implements an interface and does not provide method bodies for all
functions specified in the interface, then the class must be declared abstract.
 A Java library example is Comparator Interface. If a class implements this
interface, then it can be used to sort a collection.
Syntax:
interface {
// declare constant fields
// declare methods that abstract
// by default.
}
To declare an interface, use the interface keyword. It is used to provide total
abstraction. That means all the methods in an interface are declared with an empty
body and are public and all fields are public, static, and final by default. A class that
implements an interface must implement all the methods declared in the interface. To
implement interface use implements keyword.
Why do we use an Interface?
 It is used to achieve total abstraction.
 Since java does not support multiple inheritances in the case of class, by using
an interface it can achieve multiple inheritances.
 Any class can extend only 1 class but can any class implement infinite number
of interface.
 It is also used to achieve loose coupling.
 Interfaces are used to implement abstraction. So the question arises why use
interfaces when we have abstract classes?
The reason is, abstract classes may contain non-final variables, whereas variables in
the interface are final, public and static.
interface Language {
public void getType();
public void getVersion();
}
Here,
Language is an interface.
It includes abstract methods: getType() and getVersion().
Implementing an Interface
Like abstract classes, we cannot create objects of interfaces.
To use an interface, other classes must implement it. We use the implements keyword
to implement an interface.
interface Polygon {
void getArea(int length, int breadth);
}
// implement the Polygon interface
class Rectangle implements Polygon {
// implementation of abstract method
public void getArea(int length, int breadth) {
System.out.println("The area of the rectangle is " + (length * breadth));
}
}
class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
r1.getArea(5, 6);
}
}
Output:
The area of the rectangle is 30
In the above example, we have created an interface named Polygon. The interface
contains an abstract method getArea().
Here, the Rectangle class implements Polygon. And, provides the implementation of
the getArea() method.
Implementing Multiple Interfaces
In Java, a class can also implement multiple interfaces. For example,
interface A {
// members of A
}
interface B {
// members of B
}
class C implements A, B {
// abstract members of A
// abstract members of B
}
Extending an Interface
Similar to classes, interfaces can extend other interfaces. The extends keyword is used
for extending interfaces. For example,
interface Line {
// members of Line interface
}
// extending interface
interface Polygon extends Line {
// members of Polygon interface
// members of Line interface
}
Here, the Polygon interface extends the Line interface. Now, if any class
implements Polygon, it should provide implementations for all the abstract methods of
both Line and Polygon.
Extending Multiple Interfaces
An interface can extend multiple interfaces. For example,
interface A {
...
}
interface B {
...
}
interface C extends A, B {
...
}
default methods in Java Interfaces
With the release of Java 8, we can now add methods with implementation inside an
interface. These methods are called default methods.
To declare default methods inside interfaces, we use the default keyword.
Why default methods?
Let's take a scenario to understand why default methods are introduced in Java.
Suppose, we need to add a new method in an interface.
We can add the method in our interface easily without implementation. However,
that's not the end of the story. All our classes that implement that interface must
provide an implementation for the method.
If a large number of classes were implementing this interface, we need to track all
these classes and make changes to them. This is not only tedious but error-prone as
well.
To resolve this, Java introduced default methods. Default methods are inherited like
ordinary methods.
Let's take an example to have a better understanding of default methods.
Example: Default Method in Java Interface
interface Polygon {
void getArea();
// default method
default void getSides() {
System.out.println("I can get sides of a polygon.");
}
}
// implements the interface
class Rectangle implements Polygon {
public void getArea() {
int length = 6;
int breadth = 5;
int area = length * breadth;
System.out.println("The area of the rectangle is " + area);
}
// overrides the getSides()
public void getSides() {
System.out.println("I have 4 sides.");
}
}
// implements the interface
class Square implements Polygon {
public void getArea() {
int length = 5;
int area = length * length;
System.out.println("The area of the square is " + area);
}
}
class Main {
public static void main(String[] args) {
// create an object of Rectangle
Rectangle r1 = new Rectangle();
r1.getArea();
r1.getSides();
// create an object of Square
Square s1 = new Square();
s1.getArea();
s1.getSides();
}
}
Output
The area of the rectangle is 30
I have 4 sides.
The area of the square is 25
I can get sides of a polygon.
In the above example, we have created an interface named Polygon. It has a default
method getSides() and an abstract method getArea().
Here, we have created two classes Rectangle and Square that implement Polygon.
The Rectangle class provides the implementation of the getArea() method and
overrides the getSides() method. However, the Square class only provides the
implementation of the getArea() method.
Now, while calling the getSides() method using the Rectangle object, the overridden
method is called. However, in the case of the Square object, the default method is
called.

Argument Passing Mechanism:


There is only call by value in java, not call by reference.
If we call a method passing a value, it is known as call by value.
The changes being done in the called method, is not affected in the calling method.
Call by Value means calling a method with a parameter as value. Through this, the
argument value is passed to the parameter.
While Call by Reference means calling a method with a parameter as a reference.
Through this, the argument reference is passed to the parameter.
In call by value, the modification done to the parameter passed does not reflect in the
caller's scope while in the call by reference, the modification done to the parameter
passed are persistent and changes are reflected in the caller's scope.
Example of call by value in java:
class Operation{
int data=50;
void change(int data)
{
data=data+100
}
public static void main(String args[]){
Operation op=new Operation();
System.out.println("before change "+op.data);
op.change(500);
System.out.println("after change "+op.data);
}
}

Call by reference:
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.
class Operation2
{
int data=50;
void change(Operation2 op)
{
op.data=op.data+100;//changes will be in the instance variable
}
public static void main(String args[])
{
Operation2 op=new Operation2();
System.out.println("before change "+op.data);
op.change(op);//passing object
System.out.println("after change "+op.data);
}
}
Method Overloading in Java:
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
If we have to perform only one operation, having same name of the methods increases
the readability of the program.
There are two ways to overload the method in java:
By changing number of arguments
By changing the data type

Method Overloading: changing no. of arguments


class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1
{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,1
1));
}}
Method Overloading: changing data type of arguments:
class Adder
{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b)
{
return a+b;
}
}
class TestOverloading2
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}
Note: In Java, Method Overloading is not possible by changing the return type of the
method only

Recursion:
The process in which a function calls itself directly or indirectly is called recursion
and the corresponding function is called as recursive function.
public class Test
{
// Factorial function
static int f(int n)
{

// Stop condition
if (n == 0 || n == 1)
return 1;
// Recursive condition
else
return n * f(n - 1);
}
// Driver code
public static void main(String[] args)
{
int n = 5;
System.out.println("factorial of " + n + " is: " + f(n));
}
}
Dealing with Static Members:
In Java, static members are those which belongs to the class and you can access these
members without instantiating the class.
The static keyword can be used with methods, fields, classes (inner/nested), blocks.
Static Methods − You can create a static method by using the keyword static.
Static methods can access only static fields, methods.
To access static methods there is no need to instantiate the class, you can do it just
using the class name as −
public class MyClass {
public static void sample(){
System.out.println("Hello");
}
public static void main(String args[])
{
MyClass.sample();
}
}

Static Fields:
You can create a static field by using the keyword static.
The static fields have the same value in all the instances of the class.
These are created and initialized when the class is loaded for the first time. Just like
static methods you can access static fields using the class name (without instantiation).
public class MyClass {
public static int data = 20;
public static void main(String args[]){
System.out.println(MyClass.data);
}
}
Static Blocks:
These are a block of codes with a static keyword. In general, these are used to
initialize the static members.
JVM executes static blocks before the main method at the time of class loading.
public class MyClass {
static{
System.out.println("Hello this is a static block");
}
public static void main(String args[]){
System.out.println("This is main method");
}
}
Object’s Memory:
An object is created in the memory using new operator. Constructor is used to
initialize the properties of that object.
When an object is no more required, it must be removed from the memory so that
memory can be reused for another objects.
Garbage collection:
Removing unwanted objects or abandoned objects from the memory is called garbage
collection.
In the languages like C,C++, GC is performed manually using destructors
In java, there is no destructors.
There exists better mechanism to handle the garbage collection.
JVM implicitly sweeps out abandoned objects from the memory.
Finalize Method():
Finalize is a method, which is available in object super class.
The purpose of finalize method is to release the resources that is allocated by unused
object, before removing unused object by garbage collector.
Ex: class object
{
Protected finalize()
{
Empty}}
Finalize() method is a protectd and non static method of java.lang.object class.

Garbage Collector Thread:


Garbage collector thread before sweeping out an abandoned object, it calls finalize()
method of that object.
Explicit call to finalize:
You can call finalize() method explicitly on an object before it is abandoned.
When you call only operations kept in finalize() method are performed on an object
Object will not be destroyed from the memory.
That means clean up operations which you have kept in the finalize() method are
executed before an object is destroyed from the memory.
Garbage collector thread calls finalize() method only once for one object.
Native Method:
The native keyword is applied to a method to indicate that the method is implemented
in native code using JNI (Java Native Interface).
Native is a modifier applicable only for methods and we can’t apply it anywhere else.
The methods which are implemented in C, C++ are called native methods or foreign
methods.
The main objectives of the native keyword are:
To improve the performance of the system.
To achieve machine level/memory level communication.
To use already existing legacy non-java code.
For native methods implementation is already available in old languages like C, C++
and we are not responsible to provide an implementation. Hence native method
declaration should end with ; (semi-colon).
We can’t declare a native method as abstract.
The main advantage of native keyword is improvement in performance but the main
disadvantage of native keyword is that it breaks platform-independent nature of java.

You might also like