Javaenture Workshop Finaldraft.pptx
Javaenture Workshop Finaldraft.pptx
Ex : = ; += ; -= ; *= ; /= ; %=
Ex : + ; - ; ++ ; - -
Operators in Java
JAVA C
Malloc, calloc, realloc, and free are
Java Memory Management: Automatic
examples of functions used in manual
garbage collection memory management. No
memory management. Memory allocation
manual deallocation or allocation of memory
and deallocation must be done directly by
(e.g., no free or malloc).
developers.
1.Data Types : byte, short, int, long, float, double, char, boolean.
2. Flow Control : if, else, switch, case, default, while, do, for, break, continue, return.
“this” stores the memory address of the CURRENT OBJECT (the object
on which the method has been called)
Benefits Of Using “this”. . . .
1. Data Type – The kind of data that it can hold. For example, int,
string, float, char, etc.
2. Variable Name – To identify the variable uniquely within the scope.
3. Value – The data assigned to the variable.
Literals
Any constant value which can be assigned to the variable is called literal/constant.
Syntax:
for (type variableName : arrayName)
{ // code block to be executed}
For each Loop
Strings
1. Strings in Java represent a sequence of characters.
2. They are objects of the String class.
3. Java provides various methods to manipulate strings.
4. Strings are immutable (cannot be changed after creation).
5. Why Are Strings Immutable?
Once created, a String object cannot be modified.
Any modification creates a new String object.
Ensures security and thread-safety.
Efficient memory usage through the String Pool.
Memory Allocation of Strings
1. . In Java, strings are stored in the memory as objects of the class String.
2. When memory is allocated for any Java program, JVM (Java virtual machine)
divides allocated memory into two parts. One part is Stack and the other part is
Heap. In Heap memory, java allocates some memory, especially for literals that
memory is called the String constant pool(SCP). SCP is the predefined area inside
the Heap. String pool helps in saving a lot of space for Java Runtime. String class
uses SCP to store unique string literals.
Memory Allocation of Strings
1. In Stack memory, variables or variable references or references to the objects are
stored.
2. In Heap memory, all the objects that are dynamically allocated are stored. To
allocate memory to an object we use a new keyword.
There are two ways of creating string objects.
1. String literal
String s5 = “java”;
Whenever we create a string literal, JVM first checks if the string literal already
exists in the string constant pool. If not available, it will create a new string literal in
SCP. In the given picture, str1 points to “java” in SCP.
Memory Allocation of Strings
2. By using a new keyword
String s4= new String(“java”);
//Instantiating the string class using a new keyword
When a string object is created using a new keyword, it will create two objects. One
in SCP another in Heap and the reference variable is stored in the stack.
Memory Allocation of Strings
We have already created the literal “java” by using
String s5 = “java”;
As we cannot have duplicates in SCP, So JVM will not create one more object in SCP
but will return the existing reference to the variable str3 in the stack and it will create
one object in Heap. Str3 will point to the object “java” in the Heap but not in SCP.
Memory Allocation of Strings
Following are the different cases of how memory is allocated for string objects.
Case 1: How the string objects defined above are stored in memory.
public class stringsStorageConcept{
public static void main(String[] args){
String str1 = “MyString”;
String str2 = new String(“MyString”);
System.out.println(str1 == str2); //Output:False
System.out.println(str1.equals(str2)); //Output:True
}
}
Memory Allocation of Strings
When we compare str1 and str2 using the “==” operator it returns false. As we know
“==” operator compares their physical addresses. Here in our example str1 is pointing to
the object in SCP and str2 is pointing to the object in the Heap. So it returns false.
But in the case of str1.equals(str2), as we know “equals” function checks the individual
characters both str1 and str3 have the same value stored it returns true.
Memory Allocation of Strings
Case 2: Another string literal
String str3 = “MyString”;
Both str1 and str3 will point to the same string literal in SCP.
public class stringsStorageConcept{
public static void main(String[] args){
String str1 = “MyString”;
String str3 = “MyString”;
System.out.println(str1 == str2); //Output:True
System.out.println(str1.equals(str2)); //Output:True
}
}
Memory Allocation of Strings
s1 == s3 returns true, as “==” operator compares their physical addresses but not the
content.
s1.equals(s3) returns true, and the “equals“ function checks the individual characters in
both reference variables.
Memory Allocation of Strings
Case 3: Another string object is created using a new keyword
In this case, JVM will check for this string in SCP it cannot find the string object with
the value “NewString”, so it will create two objects one in SCP and another in Heap,
the reference variable str4 will be stored in the stack. Str4 will have the reference to
the object in the Heap.
Memory Allocation of Strings
Case 4: Another string literal is created.
In this case, JVM will check in SCP if this literal is already available or not, here
“NewString” is already present in SCP so JVM will not create a duplicate in SCP
instead it returns the reference to the variable str5.
Memory Allocation of Strings
Case 5: Assigning one string to another string
Here str6 and str4 will point to the same object in Heap and will not erase the value in str4.
Memory Allocation of Strings
public class stringsStorageConcept{
public static void main(String[] args){
String str4 = new String(“NewString”);
String str6 = str4;
System.out.println(str4 == str6); //Output:true
}
}
JVM will give the reference of the “NewString” in the heap to the variable str6. That’s the
reason str4 == str6 returns true.
Memory Allocation of Strings
In conclusion, creating string objects using string literal and by ‘new’ operator has
its pros and cons.
By using string literals, we can make memory more efficient by not creating
duplicates. JVM creates one unique object and the string stays in the SCP
forever. The downside of this is that the string pool has a fixed size and it will get
full at some time.
But by using a new keyword it creates two objects, one in SCP and the other in
Heap. In a Heap, if we don’t need the object it will be erased by a garbage
collector to make space. But the downside of this is that with a ‘new’ operator
JVM will always have to create a new object and it is an overload for JVM
Java Program to demonstrate String:-
Result
Addressing of Strings in Java
Basic String Operations
1. Concatenation:
1. Using equals():
System.out.println(str1.equals(str2)); // false
2. Case-insensitive comparison:
System.out.println(str1.equalsIgnoreCase(str2)); // true
Comparing Strings
String str1 = "Hello";
String str2 = "hello";
3. Using compareTo():
System.out.println(str1.compareTo("Apple")); // Positive value
System.out.println(str1.compareTo("Hello")); // 0 (Equal)
System.out.println(str1.compareTo("Zebra")); // Negative value
4. Using '==' (Not Recommended): String str3 = new
String("Hello"); System.out.println(str1 == str3); // false
(different references)
Searching in Strings
Using String phrase = "Java programming is awesome";
Functional Programming
Using classes, we can create multiple objects with the same behaviours
instead of writing their code multiple times.
Example
The objects are what perform your code, they are the part of your code visible to the
viewer/user.
Class
Classes Vs. Objects
This keyword
What the hell is “this” ?
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 can be used to call current class methods and fields, to pass an instance
of the current class as a parameter, and to differentiate between the local
and instance variables. Using “this” reference can improve code readability
and reduce naming conflicts.
Uses of this keyword
1. Accessing Instance Variables: When you have a method parameter or a
local variable with the same name as an instance variable, you can use
this. to distinguish between them.
2. Calling Constructors: you can use this() within a constructor to call
another constructor in the same class.
3. Returning the Current Object: this can be used to return the current object
from a method, enabling method chaining.
Constructors
What is a Constructor ?
It 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 that is used to initialize the object. Every time an
object is created using the new() keyword, at least one constructor is called.
Purpose: Constructors are crucial for setting initial values for object attributes and
ensuring the object is in a valid state from the beginning.
Return Type: Constructors cannot have a return type, not even void.
Constructors
Types of Constructor
1. Default Constructor
2. Parameterised Constructor
3. Copy Constructor
Default Constructor
A constructor that has no parameters is known as default constructor. A default
constructor is invisible. And if we write a constructor with no arguments, the compiler
does not create a default constructor. It is taken out. It is being overloaded and called a
parameterized constructor. The default constructor changed into the parameterized
constructor. But Parameterized constructor can’t change the default constructor. The
default constructor can be implicit or explicit.
Parameterised Constructor
Output:
Pen Details:
Color: Blue
Type: Gel
Price: $2.5
Example: 1
Write a program that to initialise a Car object and display it’s details
Output:
Car Details:
Make: Toyota
Model: Camry
Year: 2022
Important Concepts of OOP
Overview
Encapsulation
What is Encapsulation ?
Encapsulation is the process of binding or wrapping the data and the
codes that operates on the data into a single entity
This means that your bank details are private, so that anyone cannot see
your account details.
Only you will have access to your account details and that too using
method defined inside that class and this method will ask your account id
and password for authentication.
How to achieve or implement Encapsulation in Java ?
Provide the public setter and getter methods in the class to set/modify the
values of the variable/fields.
Example:1 Code without Encapsulation
Example:2 Code with Encapsulation
Inheritance
What is Inheritance?
Inheritance is a technique using which we can acquire the features of an existing
class/object in a newly created class/object.
In JAVA we call the inherited class as sub-class and the class from where it
inherited is called the super-class
Example
Benefits of Inheritance
Output
Specifiers in Java
Specifiers in Java
Access Specifiers:
○ Public: The member is accessible from anywhere in the program.
○ Private: The member is accessible only within the declared class and
cannot be accessed
from outside the class.
○ Protected: The member is accessible within the same package and by
subclasses in
different packages.
○ Default (no modifier): The member is accessible only within the same
package and not from outside the package.
Example:
Final, Static, and Abstract Specifiers:
Final:
■ Used to declare constants.
■ Prevents method overriding in derived classes.
■ Prevents class inheritance if applied to a class
Example:
Static Specifier:
Defines class-level members shared by all objects.
Static methods cannot access non-static members directly.
Example:
Abstract Specifier:
Used to declare abstract classes and methods.
Abstract methods must be implemented by subclasses.
Example:
Usage of Specifiers in Classes and
Methods:
Specifiers play a crucial role in:
Encapsulation: Restricting access to data members.
Code structure and behaviour: Defining constants, shared
members, and enforceable methods.
Security: Preventing unauthorized access and modifications.
Abstraction
What is abstraction ?
Data Abstraction is the property by virtue of which only the essential
details are displayed to the user. The trivial or non-essential units are
not displayed to the user.
Ex: A car is viewed as a car rather than its individual components.
Can have instance variables Only constants: public static final variables.
All exception and error types are subclasses of the class Throwable, which is
the base class of the hierarchy. One branch is headed by Exception. This class
is used for exceptional conditions that user programs should catch.
NullPointerException is an example of such an exception. Another
branch, Error is used by the Java run-time system(JVM) to indicate errors
having to do with the run-time environment itself(JRE). StackoverflowError is
an example of such an error.
The below figure demonstrates the exception hierarchy in
Java:
Types of Java Exceptions
Input and Output in Java
1️⃣ User Input Methods
🔹 Scanner Class (java.util.Scanner)
Used for reading different types of user input (int, double,
string, etc.).
Simple and widely used for console-based programs.
Example:
🔹 BufferedReader & InputStreamReader (java.io)
More efficient than Scanner for large input.
Reads input as a string and requires conversion for numeric
values.
Example:
2️⃣ File Handling in Java
🔹 FileReader & FileWriter (java.io)
FileReader is used for reading files.
FileWriter is used for writing data to files.
Example:
3️⃣ Output Display
🔹 System.out.println()
Used for printing output to the console.
System.out.print() (without ln) prints on the same line
Example:
Arrays in Java
Definition and Importance:
An array in Java is a collection of elements of the same data type,
stored in contiguous memory locations. Arrays allow efficient
data storage and manipulation, making them essential for
handling large datasets, implementing algorithms, and optimizing
performance.
Importance of Arrays:
To find out how many elements an array contains, use the .length property:
Looping through an array
Using a For Loop
A for loop is commonly used to iterate over an array by accessing elements with their index:
2.Static Methods:
Belong to the class itself and are accessed using the class name
3. Constructor Methods:
Special methods used to initialize objects of a class
4.Interface Methods:
Methods declared in an interface, which must be implemented by classes that
implement the interface.
Method Overloading
Java allows you to define multiple methods with the same name but
different parameter lists (number, order, or type of parameters) within
the same class. This is called method overloading.
The compiler distinguishes between these methods based on their
signatures (parameter lists).
Create a Method
A method must be declared within a class. It is defined with the name of the
method, followed by parentheses (). Java provides some pre-defined
methods, such as System.out.println(), but you can also create your own
methods to perform certain actions:
Parameters and Arguments
Information can be passed to methods as a parameter. Parameters act as
variables inside the method.
Arguments are the actual values that are passed in when the method is
invoked. When you invoke a method, the arguments used must match the
declaration's parameters in type and order.