Unit 1
Unit 1
Unit 1
J2SE 5.0 September 30, 2004 Java SE 17 (LTS) September 14, 2021
• Working: Many IDEs support plugins or extensions that enhance functionality. Developers can
install and configure plugins to add support for additional languages, frameworks, and tools.
12. Code Collaboration:
• Working: Some IDEs offer features for real-time code collaboration, enabling multiple developers
to work on the same codebase simultaneously. They may include features like pair programming
and code sharing.
These features collectively create a productive and efficient development environment for Java
programmers. IDEs streamline the development process, reduce the likelihood of errors, and provide a
range of tools to improve code quality and maintainability. The choice of IDE often depends on individual
preferences and project requirements, but a well-chosen IDE can significantly boost a developer's
productivity and code quality.
There are several Integrated Development Environments (IDEs) available for Java development, each
offering its own set of features and capabilities. Here are some popular Java IDEs:
1. Eclipse: Eclipse is a widely-used open-source IDE for Java development. It offers a rich set of
features, including code assistance, debugging, version control integration, and a wide range of
plugins for various programming languages and technologies.
2. IntelliJ IDEA: IntelliJ IDEA, developed by JetBrains, is a highly regarded commercial IDE for
Java. It provides a user-friendly interface, powerful code analysis tools, intelligent code
completion, and excellent support for Java frameworks.
3. NetBeans: NetBeans is an open-source IDE that supports multiple programming languages,
including Java. It offers features such as code templates, visual design tools, and seamless
integration with project management and version control systems.
4. Visual Studio Code: Visual Studio Code (VS Code) is a free and open-source code editor from
Microsoft. It has gained popularity in recent years for its extensibility through plugins, including
those for Java development. With the right extensions, it can function as a powerful Java IDE.
5. Android Studio: If you're specifically interested in Android app development using Java (or
Kotlin), Android Studio is the official IDE provided by Google. It includes features tailored for
Android app development and offers a seamless development experience for Android projects.
6. BlueJ: BlueJ is an educational IDE designed for teaching and learning Java programming. It
provides a simplified interface and is often used in introductory Java courses.
7. JDeveloper: Oracle's JDeveloper is an IDE primarily focused on Java EE (Enterprise Edition)
development. It offers tools for building enterprise-level Java applications, including support for
Oracle databases and middleware.
8. DrJava: DrJava is a lightweight and open-source IDE designed for simplicity and ease of use,
making it a good choice for beginners or small projects.
9. JGrasp: JGrasp is another lightweight IDE suitable for educational purposes. It provides visual
representations of code structures and supports multiple programming languages, including Java.
The choice of IDE depends on your specific needs, preferences, and project requirements. Many developers
prefer IntelliJ IDEA for its comprehensive features and excellent Java support, while Eclipse remains a
popular choice, especially for open-source and community-driven projects. Experiment with a few IDEs to
find the one that best suits your workflow and coding style.
JRE
JRE (Java Runtime Environment) is a critical component in the Java ecosystem. It is an essential part of
the Java platform, and it plays a crucial role in running Java applications. Here's an explanation of what
JRE is and how it works:
1. What is JRE?
• The Java Runtime Environment (JRE) is a software package that contains everything needed to run
compiled Java applications and applets. It provides the runtime environment for executing Java
bytecode.
2. Components of JRE:
• The JRE includes several key components:
• Java Virtual Machine (JVM): The JVM is a crucial component of the JRE responsible for
executing Java bytecode. It interprets the bytecode and translates it into machine-specific
instructions that the underlying hardware can understand. The JVM also manages memory,
handles garbage collection, and enforces security.
• Java Class Library: The JRE contains a set of standard class libraries and APIs (Application
Programming Interfaces). These libraries provide pre-written classes and methods that Java
applications can use for various tasks, such as file I/O, networking, and user interface
development. The Java Class Library is part of the Java Standard Library (Java API).
3. How JRE Works:
• When you develop a Java application, you write the source code and then use a Java compiler (e.g.,
javac) to compile it into bytecode. This bytecode is a platform-independent representation of your
code.
• To run the compiled Java application or applet, you need the JRE installed on the target machine.
Here's how it works:
1. You execute the Java application by invoking the java command followed by the name of
the class that contains the main method (the entry point of the application).
2. The java command starts the JVM included in the JRE.
3. The JVM loads the bytecode of your application and executes it.
4. The Java Class Library is used by your application to perform various tasks, such as reading
files, creating user interfaces, and making network requests.
4. Importance of JRE:
• JRE is critical for Java's "Write Once, Run Anywhere" philosophy. Since Java bytecode is
platform-independent, the same compiled Java application can run on any platform with a
compatible JRE. This feature is a significant advantage for Java's cross-platform compatibility.
5. JRE vs. JDK:
• It's essential to distinguish between JRE and JDK (Java Development Kit). The JDK includes the
JRE along with additional tools and libraries for Java development, such as the Java compiler
(javac) and debugging tools. Developers use the JDK to create, compile, and package Java
applications, while end-users only need the JRE to run them.
In summary, the Java Runtime Environment (JRE) is a critical component that allows Java applications to
run on various platforms by providing the necessary runtime environment, including the Java Virtual
Machine (JVM) and the Java Class Library. End-users require JRE to execute Java applications, while
developers use the Java Development Kit (JDK), which includes the JRE, to create and compile Java
applications.
JVM
The JVM, or Java Virtual Machine, is a crucial component of the Java platform. It plays a central role in
executing Java bytecode, making it possible for Java programs to run on different hardware and operating
systems without modification. Here's a detailed explanation of what the JVM is and how it works:
1. What is JVM (Java Virtual Machine)?
• The JVM is a software-based emulation of a physical computer that executes Java bytecode. It's a
part of the Java Runtime Environment (JRE), which also includes the Java Class Library and other
runtime components.
2. Key Components of JVM:
• The JVM consists of several important components:
• Class Loader: The Class Loader is responsible for loading classes and interfaces as needed
during program execution. It loads classes from the classpath, including system classes and
user-defined classes.
• Class Area: The Class Area is a part of memory that stores class metadata, such as class
names, method names, and field names. It also stores the bytecode for loaded classes.
• Heap: The Heap is the memory area where objects are allocated and deallocated. It's used
for dynamic memory allocation, and garbage collection takes place in this area.
• Method Area: The Method Area, also known as the Permanent Generation (PermGen),
stores class-level data, such as static variables, method code, and constant pool data. In
newer versions of Java (Java 8 and later), PermGen has been replaced by the Metaspace.
• Execution Engine: The Execution Engine interprets and executes Java bytecode. It can
use different methods, such as interpretation, Just-In-Time (JIT) compilation, or a
combination of both, to execute code efficiently.
• Native Interface: The Native Interface allows Java applications to interact with native
code written in languages like C or C++. It's essential for platform-specific operations and
system calls.
3. How JVM Works:
• Here's a simplified overview of how the JVM works during the execution of a Java program:
1. You compile your Java source code using a Java compiler (e.g., javac). This compilation
step generates bytecode files (.class files).
2. To run your Java application, you use the java command, specifying the name of the class
that contains the main method (the entry point of the program).
3. The JVM is invoked by the java command. It starts by loading the necessary class files
and verifying their bytecode for correctness and security.
4. The Execution Engine of the JVM executes the bytecode, interpreting it or using JIT
compilation to translate it into native machine code.
5. The program runs within the JVM, using memory areas like the heap for object storage and
the method area for storing class-level information.
6. Garbage collection in the JVM periodically identifies and frees up memory occupied by
objects that are no longer reachable.
4. Platform Independence:
• One of the key advantages of the JVM is its ability to provide platform independence. Java bytecode
is machine-independent, meaning you can write a Java program once and run it on any platform
that has a compatible JVM.
5. Different JVM Implementations:
• There are multiple implementations of the JVM available, including Oracle HotSpot, OpenJ9,
GraalVM, and others. These implementations may optimize the execution of bytecode differently
and offer various features and performance improvements.
In summary, the Java Virtual Machine (JVM) is the runtime environment that executes Java bytecode. It
abstracts the underlying hardware and operating system, providing platform independence for Java
applications. The JVM's components work together to load, verify, and execute Java programs efficiently
while managing memory and providing essential runtime services.
OBJECT ORIENTED PROGRAMMING CONCEPTS
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects. It simplifies
software development and maintenance by providing some concepts:
1) Object
2) Class
3) Inheritance
4) Polymorphism
5) Abstraction
6) Encapsulation
Apart from these concepts, there are some other terms which are used in Object-Oriented design:
a) Coupling
b) Cohesion
c) Association
d) Aggregation
e) Composition
1) Object: Any entity that has state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes up some space
in memory. Objects can communicate without knowing the details of each other's data or code. The only
necessary thing is the type of message accepted and the type of response returned by the objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors like
wagging the tail, barking, eating, etc.
Java is a popular object-oriented programming (OOP) language, and it embraces several core OOP
concepts. These concepts form the foundation for designing and building Java applications. Here are the
fundamental OOP concepts in Java:
• Class: A class is a blueprint or template for creating objects. It defines the structure and behavior
that objects of that class will have. Classes in Java can contain fields (variables) and methods
(functions).
• Object: An object is an instance of a class. It represents a real-world entity and can interact with
other objects.
class Car {
String brand;
int year;
void startEngine() {
// Method implementation
}
}
File: Student.java
Output:
0
null
File: TestStudent1.java
Output:
0
null
Output:
101 Sonu
We can also create multiple objects and store information in it through reference variable.
File: TestStudent3.java
class Student{
int id;
String name;
}
class TestStudent3{
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name="Sonu";
s2.id=102;
s2.name="Amrita";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
}
Output:
101 Sonu
102 Amrita
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");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Output:
111 Karan
222 Aryan
As you can see in the above figure, object gets the memory in heap memory area. The reference variable
refers to the object allocated in the heap memory area. Here, s1 and s2 both are reference variables that
refer to the objects allocated in memory.
3) Object and Class Example: Initialization through a constructor
We will learn about constructors in Java later.
Object and Class Example: Employee
Let's see an example where we are maintaining records of employees.
File: TestEmployee.java
class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}
Output:
101 ajeet 45000.0
102 irfan 25000.0
103 nakul 55000.0
File: TestRectangle1.java
class Rectangle{
int length;
int width;
void insert(int l, int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle1{
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Output:
55
45
Output:
Factorial is 120
Output:
55
45
File: TestAccount.java
Output:
832345 Ankit 1000.0
Balance is: 1000.0
40000.0 deposited
Balance is: 41000.0
15000.0 withdrawn
Balance is: 26000.0
3) 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.
Why use inheritance in java?
• For Method Overriding (so runtime polymorphism can be achieved).
• For Code Reusability.
Terms used in Inheritance
• Class: A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created.
• Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived
class, extended class, or child class.
• Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is
also called a base class or a parent class.
• Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the
fields and methods of the existing class when you create a new class. You can use the same fields
and methods already defined in the previous class.
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an existing class. The
meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is
called child or subclass.
Java Inheritance Example
As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The
relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type
of Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output:
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of Employee class
i.e. code reusability.
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We will learn
about interfaces later.
File: TestInheritance.java
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...
File: TestInheritance2.java
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...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
Output:
weeping...
barking...
eating...
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example
given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.
File: TestInheritance3.java
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();
c.meow();
c.eat();
//c.bark();//C.T.Error
}
}
Output:
meowing...
eating...
4) Polymorphism in Java
Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms. There are two types of polymorphism in
Java: compile-time polymorphism and runtime polymorphism. We can perform polymorphism in java by
method overloading and method overriding. If you overload a static method in Java, it is the example of
compile time polymorphism. Here, we will focus on runtime polymorphism in java.
Upcasting
If the reference variable of Parent class refers to the object of Child class, it is known as upcasting. For
example:
class A{}
class B extends A{}
A a=new B();//upcasting
For upcasting, we can use the reference variable of class type or an interface type. For Example:
interface I{}
class A{}
class B extends A implements I{}
B IS-A A
B IS-A I
B IS-A Object
Since Object is the root class of all classes in Java, so we can write B IS-A Object.
In this example, we are creating two classes Bike and Splendor. Splendor class extends Bike class and
overrides its run() method. We are calling the run method by the reference variable of Parent class. Since it
refers to the subclass object and subclass method overrides the Parent class method, the subclass method is
invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.
class Bike{
void run(){System.out.println("running");}
}
class Splendor extends Bike{
void run(){System.out.println("running safely with 60km");}
public static void main(String args[]){
Bike b = new Splendor();//upcasting
b.run();
}
}
Output:
Consider a scenario where Bank is a class that provides a method to get the rate of interest. However, the
rate of interest may differ according to banks. For example, SBI, ICICI, and AXIS banks are providing
8.4%, 7.3%, and 9.7% rate of interest.
Note: This example is also given in method overriding but there was no upcasting.
class Bank{
float getRateOfInterest(){return 0;}
}
class SBI extends Bank{
float getRateOfInterest(){return 8.4f;}
}
class ICICI extends Bank{
float getRateOfInterest(){return 7.3f;}
}
class AXIS extends Bank{
float getRateOfInterest(){return 9.7f;}
}
class TestPolymorphism{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
}
}
Output:
class Shape{
void draw(){System.out.println("drawing...");}
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle...");}
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle...");}
}
class Triangle extends Shape{
void draw(){System.out.println("drawing triangle...");}
}
class TestPolymorphism2{
public static void main(String args[]){
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
}
}
Output:
drawing rectangle...
drawing circle...
drawing triangle...
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
}
class Cat extends Animal{
void eat(){System.out.println("eating rat...");}
}
class Lion extends Animal{
void eat(){System.out.println("eating meat...");}
}
class TestPolymorphism3{
public static void main(String[] args){
Animal a;
a=new Dog();
a.eat();
a=new Cat();
a.eat();
a=new Lion();
a.eat();
}
}
Output:
eating bread...
eating rat...
eating meat...
A method is overridden, not the data members, so runtime polymorphism can't be achieved by data
members.
In the example given below, both the classes have a data member speedlimit. We are accessing the data
member by the reference variable of Parent class which refers to the subclass object. Since we are accessing
the data member which is not overridden, hence it will access the data member of the Parent class always.
Output:
90
Java Runtime Polymorphism with Multilevel Inheritance
Let's see the simple example of Runtime Polymorphism with multilevel inheritance.
class Animal{
void eat(){System.out.println("eating");}
}
class Dog extends Animal{
void eat(){System.out.println("eating fruits");}
}
class BabyDog extends Dog{
void eat(){System.out.println("drinking milk");}
public static void main(String args[]){
Animal a1,a2,a3;
a1=new Animal();
a2=new Dog();
a3=new BabyDog();
a1.eat();
a2.eat();
a3.eat();
}
}
Output:
eating
eating fruits
drinking Milk
class Animal{
void eat(){System.out.println("animal is eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("dog is eating...");}
}
class BabyDog1 extends Dog{
public static void main(String args[]){
Animal a=new BabyDog1();
a.eat();
}
}
Output:
Dog is eating
Since, BabyDog is not overriding the eat() method, so eat() method of Dog class is invoked.
5) Abstraction:
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).
Before learning the Java abstract class, let's understand the abstraction in Java first.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only essential things to the user and hides the internal details, for example, sending
SMS where you type the text and send the message. You don't know the internal processing about the
message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract
methods. It needs to be extended and its method implemented. It cannot be instantiated.
Points to Remember
A method which is declared as abstract and does not have implementation is known as an abstract method.
In this example, Bike is an abstract class that contains only one abstract method run. Its implementation is
provided by the Honda class.
In this example, Shape is the abstract class, and its implementation is provided by the Rectangle and Circle
classes.
Mostly, we don't know about the implementation class (which is hidden to the end user), and an object of
the implementation class is provided by the factory method.
A factory method is a method that returns the instance of the class. We will learn about the factory method
later.
In this example, if you create the instance of Rectangle class, draw() method of Rectangle class will be
invoked.
File: TestAbstraction1.java
drawing circle
Another example of Abstract class in java
File: TestBank.java
class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}
}
An abstract class can have a data member, abstract method, method body (non-abstract method),
constructor, and even main() method.
File: TestAbstraction2.java
bike is created
running safely..
gear changed
The abstract class can also be used to provide some implementation of the interface. In such case, the end
user may not be forced to override all the methods of the interface.
Note: If you are beginner to java, learn interface first and skip this example.
interface A{
void a();
void b();
void c();
void d();
}
class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}
class Test5{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
a.d();
}
}
Output:
I am a
I am b
I am c
I am d
6) Encapsulation:
Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a
capsule which is mixed of several medicines.
We can create a fully encapsulated class in Java by making all the data members of the class private. Now
we can use setter and getter methods to set and get the data in it.
By providing only a setter or getter method, you can make the class read-only or write-only. In other
words, you can skip the getter or setter methods.
It provides you the control over the data. Suppose you want to set the value of id which should be greater
than 100 only, you can write the logic inside the setter method. You can write the logic not to store the
negative numbers in the setter methods.
It is a way to achieve data hiding in Java because other class will not be able to access the data through the
private data members.
The encapsulate class is easy to test. So, it is better for unit testing.
The standard IDE's are providing the facility to generate the getters and setters. So, it is easy and fast to
create an encapsulated class in Java.
Let's see the simple example of encapsulation that has only one field with its setter and getter methods.
File: Student.java
File: Test.java
Output:
vijay
Read-Only class
Now, you can't change the value of the college data member which is "AKG".
Write-Only class
Now, you can't get the value of the college, you can only change the value of college data member.
Let's see another example of encapsulation that has only four fields with its setter and getter methods.
File: Account.java
File: TestAccount.java
Output:
a) Coupling
Coupling refers to the knowledge or information or dependency of another class. It arises when classes are
aware of each other. If a class has the details information of another class, there is strong coupling. In Java,
we use private, protected, and public modifiers to display the visibility level of a class, method, and field.
You can use interfaces for the weaker coupling because there is no concrete implementation.
b) Cohesion
Cohesion refers to the level of a component which performs a single well-defined task. A single well-
defined task is done by a highly cohesive method. The weakly cohesive method will split the task into
separate parts. The java.io package is a highly cohesive package because it has I/O related classes and
interface. However, the java.util package is a weakly cohesive package because it has unrelated classes and
interfaces.
c) Association
Association represents the relationship between the objects. Here, one object can be associated with one
object or many objects. There can be four types of association between the objects:
• One to One
• One to Many
• Many to One, and
• Many to Many
Let's understand the relationship with real-time examples. For example, One country can have one prime
minister (one to one), and a prime minister can have many ministers (one to many). Also, many MP's can
have one prime minister (many to one), and many ministers can have many departments (many to many).
d) Aggregation
Aggregation is a way to achieve Association. Aggregation represents the relationship where one object
contains other objects as a part of its state. It represents the weak relationship between objects. It is also
termed as a has-a relationship in Java. Like, inheritance represents the is-a relationship. It is another way
to reuse objects.
e) Composition
The composition is also a way to achieve Association. The composition represents the relationship where
one object contains other objects as a part of its state. There is a strong relationship between the containing
object and the dependent object. It is the state where containing objects do not have an independent
existence. If you delete the parent object, all the child objects will be deleted automatically.
2) OOPs provides data hiding, whereas, in a procedure-oriented programming language, global data can be
accessed from anywhere.
3) OOPs provides the ability to simulate real-world event much more effectively. We can provide the
solution of real word problem if we are using the Object-Oriented Programming language.
CONSTRUCTOR IN JAVA
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is
created. At the time of calling constructor, memory for the object is allocated in the memory.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java compiler
provides a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized constructor.
Note: It is called constructor because it constructs the values at the time of object creation. It is not
necessary to write a constructor for a class. It is because java compiler creates a default constructor if your
class doesn't have any.
Note: 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.
<class_name>(){}
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation.
//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
Rule: If there is no constructor in a class, compiler automatically creates a default
constructor.
The default constructor is used to provide the default values to the object like 0, null, etc., depending on the
type.
Output:
0 null
0 null
Explanation: In the above class, you are not creating any constructor so compiler provides you a default
constructor. Here 0 and null values are provided by default constructor.
The parameterized constructor is used to provide different values to distinct objects. However, you can
provide the same values also.
In this example, we have created the constructor of Student class that have two parameters. We can have
any number of parameters in the constructor.
Output:
111 Karan
222 Aryan
In Java, a constructor is just like a method but without return type. It can also be overloaded like Java
methods.
Constructor overloading in Java is a technique of having more than one constructor with different parameter
lists. They are arranged in a way that each constructor performs a different task. They are differentiated by
the compiler by the number of parameters in the list and their types.
Output:
111 Karan 0
222 Aryan 25
Difference between constructor and method in Java
There are many differences between constructors and methods. They are given below.
There is no copy constructor in Java. However, we can copy the values from one object to another like copy
constructor in C++.
There are many ways to copy the values of one object into another in Java. They are:
• By constructor
• By assigning the values of one object into another
• By clone() method of Object class
In this example, we are going to copy the values of one object into another using Java constructor.
//Java program to initialize the values from one object to another object.
class Student6{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
Output:
111 Karan
111 Karan
We can copy the values of one object into another by assigning the objects values to another object. In this
case, there is no need to create the constructor.
class Student7{
int id;
String name;
Student7(int i,String n){
id = i;
name = n;
}
Student7(){}
void display(){System.out.println(id+" "+name);}
Output:
111 Karan
111 Karan
In Java, access specifiers are used to specify the access level of a class or its members (data and methods).
There are four access specifiers in Java:
• public: When we declare class members as public, they are accessible from outside the
class.
• private: When we declare class members as private, they are only accessible within the class
and are not accessible from outside the class.
• default: When we declare class members with no access specifier is considered as default,
they are only accessible within the package and are not accessible from outside the package.
• protected: When we declare class members as protected, they are only accessible by any
class within the same package or by any subclasses of the parent class in which the class
members are declared as protected, regardless of whether the subclass is in the same package
or a different package.
We already know from the previous lessons how to use private and public access specifiers in a Java
program. Now, we will see how to use a default and protected access specifier in a Java program.
Example
import java.util.Scanner;
class Student
{
int roll; // default access specifiers
protected int eng;
protected int math;
};
void show()
{
System.out.println("Roll: " + roll);
System.out.println("English: " + eng);
System.out.println("Math: " + math);
System.out.println("Total Marks: " + total);
System.out.println("Percentage: " + per);
}
}
Output:
Enter Roll: 1
Enter English: 74
Enter Math: 88
Roll: 1
English: 74
Math: 88
Total Marks: 162
Percentage: 81.0
In the above example, we can see that the default and protected data members of the Student class are
accessible from the Result class after inheriting the Student class in it.
Output
A : 10 B : 20
A : 200 B : 100
A : 200 B : 20
The finalize() method in Java is a protected method defined in the Object class, which is the superclass of
all Java classes. It allows an object to perform any necessary cleanup operations before the garbage collector
destroys it. When an object is no longer used or referenced, it becomes eligible for garbage collection.
Before it is removed from memory, the garbage collector calls the finalize() method on the object. If the
object has overridden the finalize() method, any custom cleanup code specified in that method will be
executed.
To use the finalize() method in a class, you must override it with your implementation. In your
implementation, you can include any necessary cleanup code, such as closing open files or releasing other
resources.
However, there are some pitfalls to using the finalize() method. For example, it is not guaranteed to be
called, and there is no way to know when it will be called. The finalize() method can also cause performance
issues if it takes too long to execute.
How does the Finalize Method in Java Work with Garbage Collection?
The Garbage Collector (GC) automatically manages memory by freeing up memory occupied by unused
objects. The GC calls the finalize() method before an object is removed from memory, allowing it to
perform any necessary cleanup operations.
However, the finalize() method can have performance implications and should be used cautiously.
Example code for overriding the finalize() method:
@Override
protected void finalize() throws Throwable {
try {
if (file != null) {
file.close();
}
} finally {
super.finalize();
}
}
In this example, the MyObject class represents an object that holds a reference to a File object. The finalize()
method is overridden to close the file before the GC removes the object from memory.
Syntax of Finalize Method in Java
Here's the syntax for the finalize() method:
protected void finalize() throws Throwable {
// Cleanup code here
}
Parameters
The finalize() method takes no arguments and has a void return type. It is declared protected to ensure that
it can only be called by the garbage collector or by a subclass of the class that defines the finalize() method.
Return Value
The finalize() method does not return any value.
@Override
protected void finalize() throws Throwable {
System.out.println("Object with id " + id + " is being destroyed");
super.finalize();
}
public static void main(String[] args) {
MyClass obj1 = new MyClass(1);
MyClass obj2 = new MyClass(2);
MyClass obj3 = new MyClass(3);
obj1 = null;
obj2 = null;
obj3 = null;
Output
Object with id 1 is being destroyed
Object with id 2 is being destroyed
In this example, we create three instances of MyClass and then set obj1 and obj2 to null, so they are eligible
for garbage collection. We then call the garbage collector explicitly using System.gc() and
Runtime.getRuntime().gc().
When the garbage collector runs, it will call the finalize() method on any objects that are eligible for garbage
collection. In this case, it will call finalize() on obj1 and obj2. The program's output will be:
Working of Finalize() Method in Different Scenarios
Here are a few different cases to illustrate how the finalize() method works:
Case 1: Object is garbage collected, but no finalize() method is defined
In this case, the garbage collector will destroy the object without calling any finalize() method.
• Java
class MyClass {
// No finalize() method defined
}
Output
// No output
Output
Object destroyed
Output
Exception in thread "Finalizer" java.lang.Exception: Exception in finalize() method
at MyClass.finalize(MyClass.java:3)
at java.base/java.lang.ref.Finalizer.invokeFinalizeMethod(Native Method)
at java.base/java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:170)
As you can see, the exception is logged to the console with details of where it occurred.
Handling Exceptions in Finalize () Method
When the garbage collector calls the finalize() method, it has a specific way of handling exceptions. If an
exception occurs while the finalize() method is running, it is usually caught and logged somewhere to keep
a record of it. However, the exception itself is not thrown again. This is because the garbage collector calls
the finalize() method automatically, and throwing an exception from there can cause some unexpected
issues.
1. Object is created
When an object is created, it is in the "live" phase. The object is allocated memory and can be accessed by
the program.
If the finalize() method resurrects the object by creating a new reference to it, the object will remain in the
"finalizable" phase until the finalize() method completes. The object will then re-enter the "live" phase and
continue to exist until it becomes eligible for garbage collection again.
Scope Can be used with Can only be used with Can only be used with
classes, methods, and try/catch blocks. objects.
variables.
Execution Checked at compile Executed after the try/catch Executed just before an
time. blocks, but before control object is garbage collected.
transfers back to its origin.
• It provides a safety net for situations where a programmer may forget to manually clean up
an object's resources, ensuring that the resources are eventually released even if the object is
no longer referenced.
• It can be used in cases where objects need to be "revived" or restored to a previous state
after being garbage collected, although this usage is relatively rare.
• It can be useful for debugging or profiling, as it allows you to monitor when objects are
being garbage collected and potentially identify memory leaks or other issues.
• It can introduce performance issues, as the JVM must perform additional work to manage
finalization and resurrected objects.
• It can make it more difficult to reason about the lifecycle of objects in a program, as the
behavior of the finalize() method may not be immediately apparent.
• It is generally recommended to use other cleanup mechanisms, such as try-with-resources
blocks or explicit close() method calls, instead of relying on the finalize() method.
• Use a shutdown hook: A shutdown hook is a thread executed when the JVM is shutting
down. This can be used to perform any necessary cleanup before the JVM exits. To use a
shutdown hook, you can define a class that extends the Thread class and override the run()
method
• Use a reference queue: A reference queue is a data structure that holds references to
objects that have been garbage collected. By using a reference queue, you can perform
cleanup actions on objects that are no longer needed
1. Be cautious: It is crucial to keep in mind that the finalize() method is not reliable in terms of when or
even if it will be called by the garbage collector. This means relying on finalize() for critical operations or
resource cleanup can be risky. Exploring alternative approaches like try-with-resources or implementing
the Closeable or AutoCloseable interfaces is strongly recommended
2. Keep it simple: When implementing the finalize() method, it's best to keep it simple and lightweight.
Avoid including complex operations, resource-intensive tasks, or any code that could throw
exceptions. Remember, the main purpose of finalize() is to handle basic cleanup operations, so it is
important to focus on that
3. Avoid object resurrection: It's important to avoid using the finalize() method to bring objects back to
life. In other words, we shouldn't try to make objects accessible again by resurrecting them through
finalize(). Attempting to do so can cause confusion, make our program behave strangely, and lead to
unpredictable results
4. Use super.finalize(): In the finalize() method implementation, It's important to remember to include
super.finalize(). This helps ensure the superclass's finalization process is carried out correctly. By doing so,
we maintain the expected behaviour of the class hierarchy and allow any essential cleanup tasks defined in
the superclass to be performed
5. Consider alternatives: Instead of relying on the finalize() method, it's better to use explicit resource
cleanup mechanisms like try-with-resources or implementing the Closeable or AutoCloseable interfaces.
These newer approaches offer improved control and predictability when releasing resources
6. Prefer try-finally for cleanup: To ensure that resources are properly cleaned up. It is usually better to
use a try-finally block or one of the alternative mechanisms mentioned earlier. These approaches ensure
that cleanup operations are performed reliably, regardless of whether the finalize() method is called or not
7. Document intent: If you choose to use the finalize() method in your code, make sure to document its
usage and limitations clearly. Explain why it is necessary and any specific precautions or requirements for
it to work correctly
All above mentioned five variables could be accessed by the index given in the square bracket, which is
known as index-based variables.
The index always starts from 0 by default. So, if we have an array of 5 elements, it will have an index
range from 0 to 4 by default.
In the above example, the first element is stored at index 0 and the last one at the 4th index. The below-
mentioned diagram shows how the array got placed in computer memory.
Example:
// Both will create an int array with a length of 5.
int[] myArray = new int[5];
int myArray1[] = new int[5];
Array will be -
10 0 37 0 0
2. Initialize while declaring - We can also initialize the whole array while declaring it just by using
curly brackets {}. The string must be in quotes, whereas int, float, etc., do not require that.
Example:
int[] myArray = {1, 2, 3, 4, 5}; // For integer type
String[] myArray1 = {"A", "B", "C", "D"}; // For string type
How to Change an Array Element?
To change a value at a specific position in Java arrays, refer to an index. By providing index value, we tell
the Java compiler where we want to change the value.
For this, we need to use a Square bracket [] with an index number inside it. If somehow we entered the
index number bigger than the array length, then an exception occurs of
type ArrayIndexOutOfBoundsException (We will learn more about it in this article).
Example:
int myArray[] = {1, 2, 3, 4, 5};
myArray[1] = 5;
As shown in the above image, there is a total of 9 value in the array, and we start looping from 0 to 8.
Example:
public class Demo {
public static void main (String[] args) {
// declaring and initializing an array
String strArray[] = {"Python", "Java", "C++", "C", "PHP"};
Example:
public class Demo {
public static void main (String[] args) {
// declaring and initializing an array
String strArray[] = {"Python", "Java", "C++", "C", "PHP"};
}
}
Output:
Python Java C++ C PHP
Length of array: 5
In the above example code, we created a single-dimensional array called strArray, which has only one row
and multiple columns.
2. Multi-Dimensional Array
In not all cases, we implement a single-dimensional array. Sometimes, we are required to create an array
within an array.
Suppose we need to write a program that stores five different subjects and the marks of sixty students. In
this case, we just need to implement 60 one-dimensional arrays with a length of five and then implement
all these arrays in one array. Hence, we can make the 2D array with five columns and 60 rows.
A multi-dimensional array is just an array of arrays that represents multiple rows and columns. These arrays
include 2D, 3D, and nD types. 2D data like tables and matrices can be represented using this type of array.
To implement a multi-dimensional array, one needs to add two square brackets instead of one.
Example:
int marks[][] = {
{77,85,68,99,87},
{98,56,79,90,92},
{78,88,56,70,99}
};
OR
int marks[][] = new int[3][5];
// creating another array with the same dimensions to store the result
int arr3[][] = new int[3][3];
}
}
Output:
Student ID is 1 and name is Bharat
Student ID is 5 and name is Vivaan
Student ID is 6 and name is Smith
As you can see in the above code, we have first declared the array of objects with a length of three, which
create three object reference variable obj[0], obj[1], and obj[2]. And then initialized each object reference
by using a new keyword.
Passing Arrays to Methods
Likewise, we pass variables as a parameter and can also pass the array to methods. While passing, we do
not require adding a square bracket with an array name, but we do require that in formal parameters.
Passing an array while calling methods is not required to mention the size of the array. If you do so, then it
will throw the compile-time error.
Note that it is not required to use the same name of the array variable in the parameter of a function as the
array name. We can use any name we want. But make sure to define the parameter variable with the same
data type defined in an array in the main function, or else you will see a compilation error.
Let's understand it more clearly with a small Java program.
public class Test {
// defined function to find max number from an array
public static int findMax(int[] arr) {
int max = arr[0];
for(int i=1;i<arr.length;i++) {
if(max<arr[i]) {
max = arr[i];
}
}
return max;
}
public static void main (String[] args) {
// declaring and initializing an array
int myArray[] = {45,33,98,65,76,43,99,23,68};
// print array
System.out.println("Array multiply by 2 is - " );
for(int i : multiplyArr) {
System.out.print(i + " ");
}
}
}
Output:
Array multiply by 2 is -
2 4 6 8 10
Like we defined the data type of a function according to the return type in an array, we also need to define
a function with an array data type. We have done the same in the above code, defined
function doMultiplication() of type int[], and stored the result of this method in int type array multiplyArr.
Anonymous Array in Java
As its name suggests, arrays having no name are called Anonymous arrays in java. This type of array is
used only when we require an array instantly. We can also pass this array to any method without any
reference variable.
As anonymous arrays do not have reference variables, we can not access its element, though we can use it
entirely to meet our logic.
The primary reason to create an anonymous array is to implement and use an array instantly.
Syntax:
new datatype[] {values separated by comma}
Example:
//One-dimensional integer type anonymous array
new int[] {2,4,6,8};
myArray[0] = 3;
myArray[2] = 6;
myArray[4] = 9;
myArray[6] = 12; // index 6 not exists
for(int i : myArray) {
System.out.println(i);
}
}
}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length
5
at Test.main(Test.java:9)
In the above code, we can see that all work fine till initializing index [4]. But, when we tried to initialize
the array value at index [6], the compiler threw an exception, because we only have the array with a length
of five.
Cloning of Arrays in Java
Cloning an array in Java is nothing but creating a new array, where data is copied from the existing one
using the clone() property.
Syntax:
datatype Array2[] = Array1.clone();
Example:
public class Test{
public static void main (String[] args) {
// declaring and initializing an array
int myArray[] = {1,2,3,4,5};
// In Java
int[] arr; // arr is just a reference variable
arr = new int[5]; // now array will allocate memory
arr[0] = 1; //initializing element
• Whenever we try to access an element using an index less than 0 or greater than the array length,
JVM aborts the program by raising an exception of IndexOutOfBoundsException. At the same
time, C++ does not have a feature to detect such errors. Hence, the program goes into an infinity
loop until the max buffer length is not exceeded.
• As far as an array of objects is concerned, C++ will likely implement the constructed array of
objects in a single operation. On the other hand, Java needs multiple steps to perform an array of
objects.
• Like arrays in Java, C++ does not have a length property to calculate the array length every time
we want. We need to store the length of an array in the C++ program.
Advantages and Disadvantages of Arrays in Java
Advantages
• We can access an array element value randomly just by using the index indicated by the array.
• At a time, we can store lots of values in arrays.
• It becomes easier to create and work with the multi-dimensional arrays.
Disadvantages
• Arrays in Java do not have in-built remove or add methods.
• In Java arrays, we need to specify the size of the array. So there might be a change of memory
wastage. So, it is recommended to use ArrayList.
• Arrays in Java are strongly typed.
As you can see in picture above, String is an array of characters. Let us see how to create string objects in
Java.
How to Create a String Object?
String object can be created using two ways:
1. Using String Literal.
2. Using new keyword.
String Literal and String Constant Pool
A literal, in computer science, is a notation used for representing a value. Java String literal can be created
and represented using the double-quotes. All of the content/characters can be added in between the double
quotes.
For Example:
public class Main {
str = str.trim();
System.out.println(str + " awesome");
Output:
Coding is awesome
Coding is awesome
Explanation: In the above example, we have used the trim() method to trim the extra white spaces of
string str at the ends only.
Please note that it does not remove extra whitespaces if they are present between the text and not at the
ends. Use this Online Compiler to compile your Java code.
12. String replace(char oldChar, char newChar)
Details: The replace() method of string in Java as the name suggests is used to replace all the specified
character of the string with another character.
Syntax:
string.replace(oldChar, newChar)
Example:
String str = "Hi, i will be replaced with a";
str = str.replace('i','a');
System.out.println(str);
Output:
Ha, a wall be replaced wath a
Concatenating Strings
String concatenation in Java involves combining two strings using the + operator or the concat() method.
It is important to note that the original string remains unchanged unless explicitly modified.
Syntax:
String resultantStr = str1 + str2 + ...
Example-1:
String str1 = "Scaler ";
String str2 = " Topics";
String concatenated = str1 + str2;
System.out.println(concatenated);
Output:
Scaler Topics
Creating Format Strings
Details: The format() method is used to format the string as per the passed argument. This method accepts
two arguments: format string and argument(s), then returns the formatted string.
Syntax:
string.format(stringWithFormatSpecifier, anotherString)
Example:
String str = "India";
String str1 = String.format("Country: %s", str);
System.out.println(str1);
Output:
Country: India
Explanation: In the above example, we have used the %s format specifier which is reserved for strings,
Henced India got printed in place of %s. Similarly, there are format specifiers for int(%d), float(%f), etc.
which can be used for formatting of these data type values.
Escape Character () in Java Strings
Escape character is the character with a backslash \ before it.
Example:
public class Main {
The text
after this will be in new line
Java Strings: Mutable or Immutable
In Java, strings are immutable, meaning their values cannot be changed once initialized. This is because a
single string object in the String constant pool can have multiple references. Modifying the value of one
reference could affect other strings or reference variables, leading to conflicts. To prevent these conflicts,
string objects are made immutable in Java.
The concept of the String Constant Pool is closely tied to string immutability in Java.
Although it may seem like string values can be changed in previous sections of this article, the actual string
value remains unchanged.
Let us understand with the help of an example:
// Unmodified string str
String str = "Happy Learning";
System.out.println(str); // Output: Happy Learning
We’ve defined four packages, and some of them even have sub-packages defined inside them. We
distributed Java files to each package. By this example, you can calculate the importance of giving a good
name to files and placing them inside a designated package. The Sooner the application grows, the more
the importance of packages and this structured format becomes prominent.
Create, Compile and Run a Java Package Program
Use package keyword to create a package in Java
package myFirstPackage;
class Main {
public static void main(String args[]) {
System.out.println("Wooohooo!! I created my first package");
}
}
Let’s understand the code snippet. We’ve defined a package named myFirstPackage. After that, we’ve
made a class called Main, and since this is a public class, we must save this file with the same name as the
class i.e. Main.java.
After compilation, when we execute this program, it’ll print us the output. (Hop over to the next point to
know how to compile and execute your program)
A constraint that we must follow – Sequence of the program must start from declaring the package,
then single or multiple import lines and at last class definitions.
Compile a Java Package
To compile the Java package, open the command prompt and run the following command
javac -d destinationDirectoryPathWithName javaFileName
-d switch is used to define the destination folder to keep the generated Java class file. To use the current
directory as a destination folder, use (dot) in place of the destination directory path with the name.
javac -d . Main.java
Run a Java File using Package Name
To run a Java package program:
After compiling (or performing step number (b)), use the below command to run your first Java package
program.
java myFirstPackage.Main
Accessibility of Packages in Java
As you may know, in Java, we do everything inside classes. So, limiting access to variables and methods
by different files must be handled for security purposes. We mainly focus on package-level accessibility
here, but you can check out the table below to know more.
Note: Java has four modifiers: public, protected, private, and default.
Except for private members of a class, all other members can be accessed by all other classes defined inside
the same package. Sub-classes defined inside the different packages only access to public and protected
members.
Here’s the table to get more clarity.
Same Different
Same Same package Difference Package
Access Modifier package non- package non-
class subclass subclass
subclass subclass
Private Yes No No No No
From the above table, you can infer whether data members of a class with certain modifiers can be accessed
by:
1. The same class in which these data members are defined
2. The classes available inside the same package
3. The sub-class of this Java file that is stored outside this package
4. All other classes are available anywhere inside the system.
Let’s understand them in more detail.
Same class
If we make a class named A and define data members inside it with any modifiers
(public, protected, default, and private), then we can access them inside class A.
Same Package
We have single or multiple classes inside a package. Let’s say we’ve two classes inside a package
named A and B. If we try to import class A inside class B, then except for private data members of
class A all others will be accessible to class B.
Same Package Sub-class
Let's create two classes Class A and B where Class B inherits from Class A. In such a scenario, Class B can
access all members of Class A except private members. It can access the default and protected members as
it belongs to the same package.
Different Package Sub-class
Say you have two packages, packageA, and packageB. The packageA contains
class A and packageB contains class B. Class B is a subclass of class A but since they both are in different
packages, that’s why class B can access only public and protected members of
class A, default and private members will be hidden.
Global
Let’s say a class B inside a packageB wants to access class A of packageA. Now, class B is NOT a
subclass of class A. In this case, only public members of class A will be accessible to class B.
How to Access A Package?
Accessing a package inside another Java program file is required in almost every real-life project (or as
soon as you move ahead of the basics of Java).
We use the import keyword to add desired package files into the current Java program. There are mainly
three ways to access a package and its files.
Using packageName (dot) *
package packageB;
import packageA.*;
class B {
import packageA.A;
class B {
class B {
We’ve made two packages, package1 and package2. Both packages contain a file of the same name that
is sameFileName.java. Having them inside a single package causes a name collision error, and we use two
packages to thwart it.
Advantages of Packages in Java
1. Increases ease of managing your application. How? See, as we discussed at the beginning, if we
separate files and arrange them into appropriate packages (folder), it makes files easily accessible,
letting us manage them easily.
2. Provides an extra layer of protection to your files (discussed later).
3. Prevents Naming Collision error.
Understanding Type
Let's understand the type of instance.
1) variables have a type
Each variable has a type, it may be primitive and non-primitive.
Backward Skip 10sPlay VideoForward Skip 10s
1. int data=30;
Here data variable is a type of int.
2) References have a type
class Dog{
public static void main(String args[]){
Dog d1;//Here d1 is a type of Dog
}
}
3) Objects have a type
class Animal{}
static binding
When type of the object is determined at compiled time(by the compiler), it is known as static binding.
If there is any private, final or static method in a class, there is static binding.
Example of static binding
class Dog{
private void eat(){System.out.println("dog is eating...");}
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
Example of dynamic binding
class Animal{
void eat(){System.out.println("animal is eating...");}
}
In the above example object type cannot be determined by the compiler, because the instance of Dog is also an instance
of Animal. So compiler doesn't know its type, only its base type.
Bike10(){
speedlimit=70;
System.out.println(speedlimit);
}
Output: 70