Java Unit-1 Notes
Java Unit-1 Notes
CGB1201
OOPs 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:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
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.
Class
A class can also be defined as a blueprint from which you can create an
individual object. Class doesn't consume any space.
Inheritance
When one object acquires all the properties and behaviors of a parent
object, it is known as inheritance. It provides code reusability. It is used to
achieve runtime polymorphism.
Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to
convince the customer differently, to draw something, for example, shape, triangle, rectangle,
etc.
Another example can be to speak something; for example, a cat speaks meow, dog barks woof,
etc.
Abstraction:
Hiding internal details and showing functionality is known as abstraction. For example phone
call, we don't know the internal processing.
Encapsulation:
Binding (or wrapping) code and data together into a single unit are known as encapsulation.
For example, a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
Key Components:
1. Bootstrap ClassLoader: This is the first classloader which is the super class of
Extension classloader. It loads the rt.jar file which contains all class files of Java
Standard Edition like java.lang package classes, java.net package classes, java.util
package classes, java.io package classes, java.sql package classes etc.
2. Extension ClassLoader: This is the child classloader of Bootstrap and parent
classloader of System classloader. It loades the jar files located inside
$JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: This is the child classloader of Extension
classloader. It loads the classfiles from classpath. By default, classpath is set to
current directory. You can change the classpath using "-cp" or "-classpath" switch.
It is also known as Application classloader.
Class c=ClassLoaderExample.class;
System.out.println(c.getClassLoader());
//If we print the classloader name of String, it will print null because it is an
System.out.println(String.class.getClassLoader());
Output:
sun.misc.Launcher$AppClassLoader@4e0e2f2a
null
These are the internal classloaders provided by Java. If you want to create your own
classloader, you need to extend the ClassLoader class.
2) Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool,
field and method data, the code for methods.
3) Heap
It is the runtime data area in which objects are allocated.
4) Stack
Java Stack stores frames. It holds local variables and partial results, and plays a part in
method invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its
method invocation completes.
7) Execution Engine
It contains:
1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles
parts of the byte code that have similar functionality at the same time, and hence
reduces the amount of time needed for compilation. Here, the term "compiler"
refers to a translator from the instruction set of a Java virtual machine (JVM) to
the instruction set of a specific CPU.
1. Primitive Data Type: such as Boolean, char, int, short, byte, long, float, and
double
2. Non-Primitive Data Type or Object Data type: such as String, Array, etc.
Primitive:
Type Descri Defaul Size Example Range of values
ption t Literals
9,223,372,036,8
54,775,807
Eg:
class GFG {
char a = 'G';
int i = 89;
byte b = 4;
short s = 56;
double d = 4.355453532;
float f = 4.7333434f;
long l = 12121;
Non - Primitve:
The Reference Data Types will contain a memory address of variable
values because the reference types won’t store the variable value
directly in memory. They are strings, objects, arrays, etc.
1. Strings
Example:
2. Class
A class is a user-defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one
type. In general, class declarations can include these components, in order:
3. Object
4. Interface
Like a class, an interface can have methods and variables, but the methods
declared in an interface are by default abstract (only method signature, no body).
Interfaces specify what a class must do and not how. It is the blueprint of the
class.
An Interface is about capabilities like a Player may be an interface and any class
implementing Player must be able to (or must implement) move(). So it
specifies a set of methods that the class has to implement.
If a class implements an interface and does not provide method bodies for all
functions specified in the interface, then the class must be declared abstract.
A Java library example is Comparator Interface . If a class implements this
interface, then it can be used to sort a collection.
5. Array
Eg:
// Define the Student class
class Student {
// Attributes of the Student class
String name;
int age;
Variables
A variable is a container that holds the value while the Java program is
executed. A variable is assigned with a data type.
The variable is the name of a memory location. There are three types of
variables in Java: local, instance, and static.
1) Local Variable
A variable declared inside the body of the method is called local variable. You
can use this variable only within that method and the other methods in the class
aren't even aware that the variable exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is
called an instance variable. It is not declared as static.
3) Static variable
Eg:
public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class
Operators in Java
Java provides many types of operators which can be used according to
the need. They are classified based on the functionality they provide.
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instance of operator
1. Arithmetic Operators
* : Multiplication
/ : Division
% : Modulo
+ : Addition
– : Subtraction
2. Unary Operators
variable = value;
In many cases, the assignment operator can be combined with other
operators to build a shorter version of the statement called a
Compound Statement. For example, instead of a = a+5, we can write a +=
5.
+=, for adding the left operand with the right operand and then
assigning it to the variable on the left.
-=, for subtracting the right operand from the left operand and then
assigning it to the variable on the left.
*=, for multiplying the left operand with the right operand and then
assigning it to the variable on the left.
/=, for dividing the left operand by the right operand and then
assigning it to the variable on the left.
%=, for assigning the modulo of the left operand by the right operand
and then assigning it to the variable on the left.
4. Relational Operators
These operators are used to check for relations like equality, greater
than, and less than. They return boolean results after the
comparison and are extensively used in looping statements as well
as conditional if-else statements. The general format is,
==, Equal to returns true if the left-hand side is equal to the right-
hand side.
!=, Not Equal to returns true if the left-hand side is not equal to
the right-hand side.
<, less than: returns true if the left-hand side is less than the
right-hand side.
<=, less than or equal to returns true if the left-hand side is less
than or equal to the right-hand side.
>, Greater than: returns true if the left-hand side is greater than
the right-hand side.
>=, Greater than or equal to returns true if the left-hand side is
greater than or equal to the right-hand side.
Example:
Java
// Java Program to implement
// Relational Operators
import java.io.*;
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// Comparison operators
int a = 10;
int b = 3;
int c = 5;
Output
a > b: true
a < b: false
a >= b: true
a <= b: false
a == c: false
a != c: true
5. Logical Operators
These operators are used to perform “logical AND” and “logical OR”
operations.
&&, Logical AND: returns true when both conditions are true.
||, Logical OR: returns true if at least one condition is true.
!, Logical NOT: returns true when a condition is false and vice-
versa
Example:
Java
// Java Program to implemenet
// Logical operators
import java.io.*;
// Driver Class
class GFG {
// Main Function
public static void main (String[] args) {
// Logical operators
boolean x = true;
boolean y = false;
Output
x && y: false
x || y: true
!x: false
6. Ternary operator
Example:
Java
// Java program to illustrate
// max of three numbers using
// ternary operator.
public class operators {
public static void main(String[] args)
{
int a = 20, b = 10, c = 30, result;
Output
Max of three numbers = 30
7. Bitwise Operators
&, Bitwise AND operator: returns bit by bit AND of input values.
|, Bitwise OR operator: returns bit by bit OR of input values.
^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
~, Bitwise Complement Operator: This is a unary operator which
returns the one’s complement representation of the input value,
i.e., with all bits inverted.
Java
// Java Program to implement
// bitwise operators
import java.io.*;
// Driver class
class GFG {
// main function
public static void main(String[] args)
{
// Bitwise operators
int d = 0b1010;
int e = 0b1100;
System.out.println("d & e: " + (d & e));
System.out.println("d | e: " + (d | e));
System.out.println("d ^ e: " + (d ^ e));
System.out.println("~d: " + (~d));
System.out.println("d << 2: " + (d << 2));
System.out.println("e >> 1: " + (e >> 1));
System.out.println("e >>> 1: " + (e >>> 1));
}
}
Output
d & e: 8
d | e: 14
d ^ e: 6
~d: -11
d << 2: 40
e >> 1: 6
e >>> 1: 6
8. Shift Operators
These operators are used to shift the bits of a number left or right,
thereby multiplying or dividing the number by two, respectively.
They can be used when we have to multiply or divide a number by
two. General format-
<<, Left shift operator: shifts the bits of the number to the left
and fills 0 on voids left as a result. Similar effect as multiplying
the number with some power of two.
>>, Signed Right shift operator: shifts the bits of the number to
the right and fills 0 on voids left as a result. The leftmost bit
depends on the sign of the initial number. Similar effect to
dividing the number with some power of two.
>>>, Unsigned Right shift operator: shifts the bits of the number
to the right and fills 0 on voids left as a result. The leftmost bit is
set to 0.
Java
// Java Program to implement
// shift operators
import java.io.*;
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
int a = 10;
Output
a<<1 : 20
a>>1 : 5
9. instanceof operator
class operators {
public static void main(String[] args)
{
class Person {
}
interface MyInterface {
}
Output
obj1 instanceof Person: true
obj1 instanceof Boy: false
obj1 instanceof MyInterface: false
obj2 instanceof Person: true
obj2 instanceof Boy: true
obj2 instanceof MyInterface: true
Control statements
Decision-Making statements:
1) If Statement:
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
1) Simple if statement:
It is the most basic statement among all control flow statements in
Java. It evaluates a Boolean expression and enables the program to
enter a block of code if the expression evaluates to true.
if(condition) {
2) if-else statement
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
3) if-else-if ladder:
Switch Statement:
The case variables can be int, short, byte, char, or enumeration. String
type is also supported since version 7 of Java
Cases cannot be duplicate
Default statement is executed when any of the case doesn't match the
value of expression. It is optional.
Break statement terminates the switch block when the condition is
satisfied.
It is optional, if not used, next case is executed.
While using switch statements, we must notice that the case expression
will be of the same type as the variable. However, it will also be a
constant value.
Loop Statements
1. for loop
2. while loop
3. do-while loop
In Java, for loop is similar to C and C++. It enables us to initialize the loop
variable, check the condition, and increment/decrement in a single line of
code. We use the for loop only when we exactly know the number of times,
we want to execute the block of code.
//block of statements
do
{
//statements
} while (condition);
The flow chart of the do-while loop is given in the following image.
Jump Statements
Jump statements are used to transfer the control of the program to the
specific statements. In other words, jump statements transfer the
execution control to the other part of the program. There are two types of
jump statements in Java, i.e., break and continue.
Method in Java
In general, a method is a way to perform some task. Similarly, the
method in Java is a collection of instructions that performs a specific
task. It provides the reusability of code. We can also easily modify
code using methods.
Method Declaration
Method Declaration
1. Modifier: It defines the access type of the method i.e. from where
it can be accessed in your application. In Java, there 4 types of
access specifiers.
2. The return type: The data type of the value returned by the method or
void if does not return a value. It is Mandatory in syntax.
3. Method Name: the rules for field names apply to method names as
well, but the convention is a little different. It is Mandatory in syntax.
5. Exception list: The exceptions you expect by the method can throw;
you can specify these exception(s). It is Optional in syntax.
1. Predefined Method
2. User-defined Method
The method written by the user or programmer is known as a user-
defined method. These methods are modified according to the
requirement.
Java Constructors
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.
1. <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.
Output:
Bike is created
Output:
111 Karan
222 Aryan
Static Members
In Java, static members are variables or methods that belong to the class rather than to any
specific instance of the class. Here's an overview of static members in Java:
- Definition: Static variables are declared using the `static` keyword within a class but outside any
method, constructor, or block.
-Scope: These variables are associated with the class, not instances. All instances of the class
share the same static variable.
- Memory Allocation: Static variables are stored in the class area of memory. They are initialized
when the class is first loaded, even before any instance of the class is created.
-Access: You can access static variables using the class name directly (`ClassName.variableName`),
and they can also be accessed through an object reference, though this is not recommended as it
can be misleading.
Example:
class Example {
static int count = 0; // static variable
Example() {
count++; // increment the static variable
}
2. Static Methods
- Definition: Static methods are methods that can be called on the class itself, without needing an
instance of the class. They are declared with the `static` keyword.
-Access:Like static variables, static methods can be called using the class name
(`ClassName.methodName()`).
- Restrictions:
- Static methods cannot access instance variables or methods directly; they can only access
static variables and other static methods.
- Static methods cannot use the `this` or `super` keywords because they do not belong to any
specific instance.
- Example:
class Example {
static int count = 0;
static void displayCount() {
System.out.println("Count: " + count);
}
3. Static Blocks
- Definition: Static blocks are used to initialize static variables. They are executed when the class is
loaded, before any object of the class is created and before any static methods are called.
- Usage: Static blocks can be useful for complex static variable initialization or for executing code
that needs to run once at the start.
- Example:
class Example {
static int count;
// Static block
static {
count = 10;
System.out.println("Static block executed");
}
4. Static Import
- Definition: Static import allows you to import static members (fields and methods) from other
classes so that you can use them without class qualification.
-Example:
Java Arrays
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where
we store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.
In Java, array is an object of a dynamically generated class. Java array inherits the Object
class, and implements the Serializable as well as Cloneable interfaces. We can store primitive
values or objects in an array in Java. Like C/C++, we can also create single dimentional or
multidimentional arrays in Java.
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in Java which grows
automatically.
1. arrayRefVar=new datatype[size];
dataType []arrayRefVar[];
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
STRINGS IN JAVA
Strings are the type of objects that can store the character of values and in Java,
every character is stored in 16 bits i,e using UTF 16-bit encoding. A string acts the
same as an array of characters in Java.
Example:
1. Serializable Interface
Definition: The String class implements the Serializable interface, which means
that its objects can be converted into a byte stream, making it possible to save
strings to a file or send them over a network.
Example:
import java.io.*;
} catch (IOException e) {
e.printStackTrace();
2. Comparable Interface
Example:
if (result < 0) {
} else {
}
3. CharSequence Interface
Example:
java
Copy code
System.out.println(cs.length()); // Output: 13
System.out.println(cs.charAt(6)); // Output: W
}
String:
StringBuffer:
It is similar to string class. But it is mutable and we can change data at any time.
It is thread safe.
String Builder:
String buider is same as string buffer. It is also mutable and we can change data
at any time But It is not Thread safe.
String Constructors
Definition: The String class provides several constructors for creating string
objects.
Common Constructors:
Example:
System.out.println(str1); // Output:
Common Methods:
length(): Returns the length of the string.
charAt(int index): Returns the character at the specified index.
substring(int beginIndex, int endIndex): Returns a substring.
toLowerCase(), toUpperCase(): Converts all characters to lower or upper
case.
trim(): Removes whitespace from both ends of the string.
replace(char oldChar, char newChar): Replaces occurrences of a
character.
equals(Object another): Compares the string to another object.
equalsIgnoreCase(String anotherString): Compares two strings ignoring
case.
indexOf(int ch): Returns the index of the first occurrence of a character.
concat(String str):The concat() method appends the specified string to the end of
the current string. It creates a new string that is a combination of both strings.
boolean equals(Object anObject): The equals() method compares the string to
the specified object. It returns true if the strings are equal (i.e., the same sequence of
characters), and false otherwise.
char charAt(int index): The charAt() method returns the character at the specified
index in the string. The index is zero-based.
int compareTo(String anotherString): The compareTo()method compares two
strings lexicographically. It returns:
0 if the strings are equal,
A negative integer if the current string is lexicographically less than the specified
string,
A positive integer if the current string is lexicographically greater than the specified
string.
String substring(int beginIndex) & String substring(int beginIndex, int
endIndex)The substring()method returns a new string that is a substring of the
current string.
substring(int beginIndex): Extracts the substring from the specified index to the
end of the string.
substring(int beginIndex, int endIndex): Extracts the substring from the specified
start index to the end index (exclusive).
Example 1:
System.out.println(str.length()); // Output: 15
System.out.println(str.charAt(7)); // Output: J
System.out.println(str.substring(2, 7)); // Output: Hello
System.out.println(str.toLowerCase()); // Output: hello, java!
System.out.println(str.trim()); // Output: Hello, Java!
System.out.println(str.replace('l', 'x')); // Output: Hexxo, Java!
System.out.println(str.equals("Hello, Java!")); // Output: false
}
}
Example 2:
public class StringMethodsDemo {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
String str3 = "Hello";
// concat()
String concatenated = str1.concat(" ").concat(str2);
System.out.println("Concatenated String: " + concatenated); // Output:
Hello World
// equals()
System.out.println("str1 equals str3: " + str1.equals(str3)); // Output: true
System.out.println("str1 equals str2: " + str1.equals(str2)); // Output: false
// charAt()
System.out.println("Character at index 1 in str1: " + str1.charAt(1)); //
Output: e
// compareTo()
System.out.println("str1 compared to str2: " + str1.compareTo(str2)); //
Output: -15
System.out.println("str1 compared to str3: " + str1.compareTo(str3)); //
Output: 0
// substring()
System.out.println("Substring from index 6 in concatenated: " +
concatenated.substring(6)); // Output: World
System.out.println("Substring from index 0 to 5 in concatenated: " +
concatenated.substring(0, 5)); // Output: Hello
}
}
Example 3:
public class StringFunctions {
StringBuffer Class
THANK YOU