Ratan Tata Maharashtra State
Skills University (RT-MSSU)
COURSE SYLLABI
School of Science Engineering and Technology Skills
School
(SETS)
Department Department of Engineering
Program Bachelor of Technology
BY
DR. SWATI D. JADHAV
EMAIL: SWATI.JADHAV@MSSU.AC.IN
UNIT 1 Introduction to JAVA 6 HOURS
CO1
Java language introduction, JVM, Class Fundamentals, Object & Object reference , Object
Life time & Garbage Collection, Creating and Operating Objects, Inner Class, static members
and methods, this ref
Java Language Introduction
● Java is a high-level, object-oriented
programming language known for its
platform independence.
● Developed by Sun Microsystems, it
was first released in 1995.
● Java's "write once, run anywhere"
philosophy, achieved through the
Java Virtual Machine (JVM), allows
code to be executed on any device
with a JVM.
● It's widely used for developing
various applications, including web,
mobile, and enterprise software.
Key features of Java:
● Object-oriented:
Java is based on the concept of objects and classes, promoting code
reusability and organization.
● Platform independent:
Java bytecode can run on any platform with a compatible JVM, making
it highly portable.
● Compiled and Interpreted:
Java code is first compiled into bytecode, which is then interpreted by
the JVM.
● Robust and Secure:
Java has built-in security features and mechanisms to handle errors
effectively.
● Multithreaded:
Key features of Java:
● Large Community and Libraries:
Java has a large and active community, along with extensive libraries,
simplifying development.
● Why Java is popular:
● Versatility:
Java can be used to develop a wide range of applications, from small
embedded systems to large enterprise applications.
● Portability:
The platform independence makes it easy to deploy applications across
different operating systems and hardware.
Key features of Java:
● Performance:
Java is known for its performance and efficiency, making it suitable
for performance-critical applications.
● Security:
Java's robust security features make it a good choice for applications
that handle sensitive data.
● Mature Ecosystem:
Java has a mature ecosystem with a vast collection of libraries and
tools.
JVM
Key Components:
● Class Loader: Loads .class files containing bytecode into memory.
● Execution Engine: Executes the bytecode
● Runtime Data Areas: Includes the method area, heap, stack, etc.,
for storing data and managing program execution.
● JVM vs. JRE and JDK:
● JVM: The core engine that executes Java code.
● JRE (Java Runtime Environment): Includes the JVM and other
libraries needed to run Java applications.
● JDK (Java Development Kit): Contains the JRE plus tools for
developing and debugging Java code.
Key Components:
● Platform Independence:
The JVM is crucial for Java's platform independence.
Different operating systems have their own JVM implementations, allowing
the same Java bytecode to run on Windows, macOS, Linux, etc., without
modification.
● Bytecode Execution:
Java code is first compiled into bytecode, which is a set of platform-
independent instructions.
The JVM then interprets or JIT (Just-In-Time) compiles this bytecode into
native machine code for the specific platform.
How JVM Works -
1. Class Loader Subsystem
It is mainly responsible for three activities.
1. Loading
2. Linking
3. Initialization
1. Loading:
● The Class loader reads the “.class” file, generate the corresponding
binary data and save it in the method area.
● For each “.class” file, JVM stores the following information in the method
area.
● The fully qualified name of the loaded class and its immediate parent
class.
● Whether the “.class” file is related to Class or Interface or Enum.
● Modifier, Variables and Method information etc.
● After loading the “.class” file, JVM creates an object of type Class to
represent this file in the heap memory.
● Please note that this object is of type Class predefined in java.lang
package.
2. Linking:
● Performs verification, preparation, and (optionally) resolution.
● Verification: It ensures the correctness of the .class file i.e. it checks
whether this file is properly formatted and generated by a valid
compiler or not.
If verification fails, we get run-time exception java.lang.VerifyError.
● This activity is done by the component ByteCodeVerifier. Once this
activity is completed then the class file is ready for compilation.
● Preparation: JVM allocates memory for class static variables and
initializing the memory to default values.
● Resolution: It is the process of replacing symbolic references from
3. Initialization:
● In this phase, all static variables are assigned with their values defined in
the code and static block(if any).
This is executed from top to bottom in a class and from parent to child in
the class hierarchy.
In general, there are three class loaders:
● Bootstrap class loader:
Every JVM implementation must have a bootstrap class loader, capable of
loading trusted classes.
It loads core java API classes present in the “JAVA_HOME/lib” directory.
This path is popularly known as the bootstrap path.
It is implemented in native languages like C, C++.
3. Initialization:
● Extension class loader:
It is a child of the bootstrap class loader.
It loads the classes present in the extensions directories
“JAVA_HOME/jre/lib/ext”(Extension path) or any other directory specified
by the java.ext.dirs system property.
It is implemented in java by the sun.misc.Launcher$ExtClassLoader class.
● System/Application class loader:
It is a child of the extension class loader.
It is responsible to load classes from the application classpath.
It internally uses Environment Variable which mapped to java.class.path.
It is also implemented in Java by the sun.misc.Launcher$AppClassLoader
class.
Data types
Data type specify the different types of values that are stored in variables
Types 1. Primary 2. Secondary (User Defined)
Numeric (in bytes) Non-numeric Class
char (2) Interface
Byte (1)
boolean(1bit) Arrays
Short (2)
String
int (4)
long (8)
float (4)
Double (8)
First Java Program - Basic Syntax
Let us look at a simple code that will print the words Hello World.
Example
public class MyFirstJavaProgram {
/* This is my first java program.
* This will print 'Hello World' as the output
*/
public static void main(String []args) {
System.out.println("Hello World"); // prints Hello World
}
}
Data type program
Class Fundamentals
What is a Java Variable?
Variable is the name of the memory locations where we store different types of
values
Example of Valid Variables Declarations and Initializations
Following are valid examples of variable declaration and initialization in Java −
int a, b, c; // Declares three ints, a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a iis initialized with value
'a'
Java Variables Types
Java Variables Types
The following are the three types of Java variables:
Local variables
Instance variables
Class/Static variables
Classes and Objects in Java
In Java, classes and objects are basic concepts of Object Oriented
Programming (OOPs) that are used to represent real-world concepts
and entities.
● A class is a template to create objects having similar properties and
behavior, or in other words, we can say that a class is a blueprint for
objects.
● An object is an instance of a class.
● For example, the animal type Dog is a class,
● while a particular dog named Tommy is an object of the Dog class.
Java Classes
// File: Student.java
class Student {
The below Java code
demonstrates the basic int id;
use of class in Java., String n;
It defines a Student class
with two instance // Added constructor to initialize both
fields
variables (id and n),
creates an object s1 and public Student(int id, String n) {
prints values of s1. this.id = id;
this.n = n;
}
}
Java Classes
// File: Main.java
public class Main {
Output
public static void main(String[] args) { 10
Alice
// Creating Student object using the new
constructor
Student s1 = new Student(10, "Alice");
System.out.println(s1.id);
System.out.println(s1.n);
}
}
Properties of Java Classes
Properties of Java Classes
● Class is not a real-world entity. It is just a template or
blueprint, or a prototype from which objects are created.
● A class itself does not occupy memory for its attributes and
methods until an object is instantiated.
● A Class in Java can contain Data members, methods, a
Constructor, Nested classes, and interfaces.
Class Declaration in Java
access_modifier class<class_name> {
data member;
method;
constructor;
nested class;
interface
}
class syntax in Java
Components of Java Classes
In general, class declarations can include these components, in order:
● Modifiers: A class can be public or has default access (Refer this for
more details).
● Class keyword: Class keyword is used to create a class.
● Class name: The name should begin with an initial letter
(capitalized by convention).
● 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.
● Body: The class body is surrounded by braces, { }.
● Fields: Fields are variables defined within a class that hold the
data or state of an object.
Java Objects
Objects are the instances of a class that are created to use the
attributes and methods of a class.
A typical Java program creates many objects, which as you know, interact
by invoking methods. An object consists of:
● State: It is represented by attributes of an object. It also reflects
the properties of an object.
● Behavior: It is represented by the methods of an object. It also
reflects the response of an object with other objects.
● Identity: It gives a unique name to an object and enables one
object to interact with other objects.
Java Objects
Instance- Identity, State, Behavior
Initializing a Java Object
The new operator instantiates a class by allocating memory
for a new object and returning a reference to that memory.
The new operator also invokes the class constructor.
// Java Program to Demonstrate the
// use of a class with instance variable
// Class Declaration
public class Dog {
// Instance Variables
String name;
String breed;
int age;
String color;
// Constructor Declaration of Class
public Dog(String name, String breed, int age,
String color)
{
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
}
// method 1
public String getName() {
return name;
}
// method 2
public String getBreed() {
return breed;
}
// method 3
public int getAge() {
return age;
}
// method 4
public String getColor() {
return color;
} Output
Name is: tuffy
@Override public String toString() Breed, age, and
{ color are:
papillon,5,white
return ("Name is: " + this.getName()
+ "\nBreed, age, and color are: "
+ this.getBreed() + "," + this.getAge()
+ "," + this.getColor());
}
public static void main(String[] args)
{
Dog tuffy
= new Dog("tuffy", "papillon", 5, "white");
System.out.println(tuffy.toString());
}
}
Explanation:
● The Dog class has instance variables for name, breed, age, and
color.
● A constructor initializes these variables using passed
arguments.
● Constructors have no return type and share the class name.
● Object tuffy is created with: new Dog("tuffy", "papillon", 5,
"white").
● toString() returns a string representation of the object.
The result of executing this statement can be illustrated as :
Demonstrate garbage collection
// Main class to demonstrate garbage collection
public class GarbageCollectionDemo {
// A simple class to track when an object is garbage collected
static class DemoObject {
// A unique ID to help track the object
private int id;
// Constructor to assign the ID
public DemoObject(int id) {
this.id = id;
System.out.println("DemoObject " + id + " created.");
}
Demonstrate garbage collection
// finalize() is called by the GC before the object is removed from
memory
@Override
protected void finalize() throws Throwable {
System.out.println("DemoObject " + id + " is being garbage
collected.");
}
}
// Main method: program entry point
public static void main(String[] args) {
// Create first object and assign to obj1
DemoObject obj1 = new DemoObject(1);
// Create second object and assign to obj2
DemoObject obj2 = new DemoObject(2);
Demonstrate garbage collection
// Make obj1 eligible for garbage collection by removing reference
obj1 = null;
// Make obj2 eligible for garbage collection by removing reference
obj2 = null;
// Suggest Java to run garbage collector (note: not guaranteed)
System.out.println("Requesting garbage collection...");
System.gc();
// Pause the program briefly to allow GC time to run
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
// End of program
System.out.println("End of main method.");
Compiled Successfully. memory: 38504 time: 1.31 exit code: 0
DemoObject 1 created.
DemoObject 2 created.
Requesting garbage collection...
DemoObject 2 is being garbage collected.
DemoObject 1 is being garbage collected.
End of main method.
class MyClass {
String name;
MyClass(String name) {
this.name = name;
System.out.println("Object Created: " + name);
}
@Override
protected void finalize() throws Throwable {
System.out.println("Object is being garbage collected: " + name);
}
}
public class ReferenceReassignExample {
public static void main(String[] args) {
// Two separate objects
MyClass obj1 = new MyClass("Object1");
MyClass obj2 = new MyClass("Object2");
// Point obj1 to obj2
obj1 = obj2;
// Now "Object1" has no reference → eligible for GC
// Remove reference to "Object2"
obj2 = null;
// Now both "Object1" and "Object2" have no references → eligible for GC
// Request GC
System.gc();
System.out.println("End of main method");
}
}
Java this Keyword
In Java, "this" is a reference variable that refers to the current object,
or can be said "this" in Java is a keyword that refers to the current object
instance.
It is mainly used to,
● Call current class methods and fields
● To pass an instance of the current class as a parameter
● To differentiate between the local and instance variables.
Using "this" reference can improve code readability and reduce
naming conflicts.
Java "this" Reference Example
The this keyword can be used to access instance
variables and methods of the object on which the
method or constructor is being invoked.
Below is the implementation of "this" reference:
// Java program to demonstrate
// this reference
// Driver Class
public class Person {
// Fields Declared
String name;
int age;
// Constructor
Person(String name, int age)
{
this.name = name;
this.age = age;
}
// Getter for name
public String getName() { return name; }
// Setter for name
public void changeName(String name)
{
this.name = name;
}
// Method to Print the Details of
// the person
public void printDetails()
{
System.out.println("Name: " + this.name);
System.out.println("Age: " + this.age);
System.out.println();
}
// main function
public static void main(String[] args)
{
// Objects Declared
Person first = new Person("ABC", 18);
Person second = new Person("XYZ", 22);
Output
first.printDetails(); Name: ABC
second.printDetails(); Age: 18
Name: XYZ
Age: 22
Explanation:
● Here, we have defined a "Person" class with two private fields "name" and "age". We have
defined the Person class constructor to initialize these fields using "this" keyword. We have
also defined "getter and setter" methods for these fields which use this keyword to refer to
the current object instance.
● In the printDetails() method, we have used "this" keyword to refer to the current object
instance and print its name, age, and object reference.
● In the Main class, we have created two Person objects and called the printDetails() method
on each object. The output shows the name, age, and object reference of each object
instance.
Methods to Use "this" in Java
Following are the ways to use the "this" keyword in Java
mentioned below:
1. Using "this" keyword to refer to current class instance
variables.
2. Using this() to invoke the current class constructor
3. Using 'this' keyword to return the current class instance
4. Using 'this' keyword as the method parameter
5. Using 'this' keyword to invoke the current class method
6. Using 'this' keyword as an argument in the constructor
1. Using "this" to Refer to Current Class Instance
Variables
// Java program for using "this" keyword to
// refer current class instance variables
class Abc {
int a;
int b;
// Parameterized constructor
Abc(int a, int b)
{
this.a = a;
this.b = b;
}
void display()
{
// Displaying value of variables a and b
System.out.println("a = " + a + " b = " + b);
}
public static void main(String[] args)
{
Abc object = new Abc(10, 20);
object.display();
}
}
Output
a = 10 b = 20
2. Using this() to Invoke Current Class Constructor
// Java program for using this() to
// invoke current class constructor
class Abc {
int a;
int b;
// Default constructor
Abc()
{
this(10, 20);
System.out.println("Inside default constructor \n");
}
// Parameterized constructor
Abc(int a, int b)
{
this.a = a;
this.b = b;
System.out.println(
"Inside parameterized constructor");
}
public static void main(String[] args)
{
Abc object = new Abc();
}
}
Output
Inside parameterized constructor
Inside default constructor
3. Using "this" Keyword to Return the Current
Class Instance
// Java program for using "this" keyword
// to return the current class instance
class Abc {
int a;
int b;
// Default constructor
Abc()
{
a = 10;
b = 20;
}
3. Using "this" Keyword to Return the Current Class
Instance
// Method that returns current class instance
Abc get() {
return this;
}
// Displaying value of variables a and b
void display()
{
System.out.println("a = " + a + " b = " + b);
}
public static void main(String[] args)
{ Output
Abc object = new Abc();
object.get().display(); a = 10 b = 20
4. Using "this" Keyword as a Method Parameter
// Java program for using "this"
// keyword as method parameter
class Abc {
int a;
int b;
// Default constructor
Abc()
{
a = 10;
b = 20;
}
4. Using "this" Keyword as a Method Parameter
// Method that receives "this"
// keyword as parameter
void display(Abc obj)
{
System.out.println("a = " + obj.a
+ " b = " + obj.b);
}
// Method that returns current class instance
void get() {
display(this);
}
4. Using "this" Keyword as a Method Parameter
// main function
public static void main(String[] args)
{
Abc object = new Abc();
Abc.get();
}
}
Output
a = 10 b = 20
5. Using "this" Keyword to Invoke the Current
Class Method
// Java program for using this to invoke current
// class method
class Abc {
void display()
{
// calling function show()
this.show();
System.out.println("Inside display
function");
}
5. Using "this" Keyword to Invoke the Current Class
Method
void show()
{
System.out.println("Inside show function");
}
public static void main(String args[])
{
Abc g1 = new Abc();
g1.display(); Output
}
}
Inside show function
Inside display
function
Advantages of Using "this" Reference
There are many advantages of using "this" reference in Java as
mentioned below:
● It helps to distinguish between instance variables and
local variables with the same name.
● It can be used to pass the current object as an
argument to another method.
● It can be used to return the current object from a
method.
● It can be used to invoke a constructor from another
overloaded constructor in the same class.
Disadvantages of Using "this" Reference
Although "this" reference comes with many advantages there are
disadvantages of also:
● Overuse of this can make the code harder to read and
understand.
● Using this unnecessarily can add unnecessary overhead
to the program.
● Using this in a static context results in a compile-time
error.
● Overall, this keyword is a useful tool for working with
objects in Java, but it should be used judiciously and
only when necessary.