0% found this document useful (0 votes)
19 views

JAVA MATERIAL

The document explains how Java code is executed on a machine, detailing the processes of writing, compiling, and running code through the Java Virtual Machine (JVM). It also distinguishes between compilers and interpreters, discusses Java's platform independence, and covers various programming concepts such as data types, control structures, and functions. Additionally, it provides examples of Java syntax and patterns for loops and conditionals.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

JAVA MATERIAL

The document explains how Java code is executed on a machine, detailing the processes of writing, compiling, and running code through the Java Virtual Machine (JVM). It also distinguishes between compilers and interpreters, discusses Java's platform independence, and covers various programming concepts such as data types, control structures, and functions. Additionally, it provides examples of Java syntax and patterns for loops and conditionals.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 138

JAVA

How a Code Runs on a Machine?


When you write code, it's like giving instructions to a computer. But computers only
understand machine language (0s and 1s). So, the code needs to be translated.

1. Writing Code: You write in a language like Java, which is human-readable.


2. Compiling: A tool called a compiler converts your code into a form called
bytecode (a simpler code that the computer can understand).
3. JVM (Java Virtual Machine): The JVM takes this bytecode and turns it into
machine language (0s and 1s), specific to your computer’s hardware.
4. Execution: Finally, the machine runs the translated code, following your
instructions.

So, the process is: Write > Compile > Translate > Run.
What is the difference between Compiler
and Interpreter?
A compiler and an interpreter both convert code into something a computer can
understand, but they do it differently:

● Compiler: It translates the entire program at once into machine code before
running it. This makes running faster, but you have to fix all errors first.
○ Example: C++ uses a compiler.
● Interpreter: It translates and runs the code line by line. This makes it easier to fix
errors as you go, but it runs slower.
○ Example: Python uses an interpreter.

So, compiler = translate all at once, interpreter = translate one line at a time.
What is the meaning of WORD LENGTH in
Computers?

Word length in computers refers to the number of bits (binary digits) that a computer
can process at one time. It defines how much data the CPU can handle in a single
operation.

For example:

● A computer with a 16-bit word length can process 16 bits of data at once.
● A computer with a 32-bit word length can process 32 bits.
Java Architecture
Java architecture is designed to provide platform independence and efficiency. It consists of
several key components:

1. Java Development Kit (JDK): This is the tool you use to write Java programs. It
includes a compiler, libraries, and tools needed for development.

2. Java Runtime Environment (JRE): This is what you need to run Java programs. It
contains the Java Virtual Machine (JVM) and the libraries required for executing Java
applications.

3. Java Virtual Machine (JVM): The heart of Java architecture. It takes Java bytecode
(compiled Java code) and translates it into machine code that the computer's
processor can execute. The JVM allows Java programs to run on any device that has a
JRE, making Java platform-independent.
How It Works:
● Write Code: You write Java code using the JDK.
● Compile Code: The JDK compiles the code into bytecode using the Java
compiler.
● Run Code: The JVM reads and executes the bytecode on any platform with a
JRE.

So, the flow is: JDK (Write) → Compiler (Compile) → Bytecode → JVM (Run).
This architecture makes Java versatile and allows it to run on different devices
without modification.
How java is Platform Independent language?
A platform-independent language is one that can run on any operating system
or device without needing modification. This means you can write code on one
system, and it will work on others without changes.

How Java Achieves Platform Independence:

Compilation to Bytecode: When you write Java code, it is compiled into an


intermediate form called bytecode by the Java compiler. This bytecode is not tied
to any specific machine or operating system.

Java Virtual Machine (JVM): The JVM is available for various platforms
(Windows, Mac, Linux, etc.). It takes the bytecode and translates it into machine
code specific to the underlying hardware when you run the program.
So, Java is platform-independent because it uses bytecode and the JVM,
allowing the same Java program to run on any device that supports Java,
regardless of the operating system.
Is Java a compiled or interpreted language,
and how does its architecture support both?
Java is both a compiled and an interpreted language. Here’s how it works:

1. Compilation:
● Source Code to Bytecode: When you write Java code, it is compiled by the Java
compiler (javac) into an intermediate form called bytecode. This bytecode is not
machine-specific and can run on any platform that has a Java Virtual Machine (JVM).

2. Interpretation:
● Bytecode Execution: When you run a Java program, the JVM interprets the bytecode.
It can either interpret the bytecode line by line or use the Just-In-Time (JIT) compiler
to compile frequently executed bytecode into native machine code at runtime.
JIT (Just in Time) Compiler
JIT stands for Just-In-Time Compiler. It is a part of the Java Virtual Machine
(JVM) that improves the performance of Java applications by compiling
bytecode into native machine code at runtime.
JIT Compiler: Compiles bytecode into machine code for faster execution.

Interpreting Capability: Initially interprets bytecode line by line and then


optimizes frequently used code by compiling it to native code during runtime.
Explain each part of
public static void main (String args[])
1. public:
● This is an access modifier. It means that the main method can be accessed from
anywhere, allowing the Java Virtual Machine (JVM) to call it when starting the program.

2. static:
● This keyword means that the main method belongs to the class itself, not to any specific
instance of the class. You can call this method without creating an object of the class.
The JVM needs to call main before any objects are created.

3. void:
● This indicates the return type of the method. void means that the main method does
not return any value. It simply executes the code inside it.
4. main:
● This is the name of the method. The JVM looks for this specific method name as the
starting point for executing a Java application. It is a standard convention.

5. String args[]:
● This part defines the parameter for the main method allowing the program to accept
command-line arguments. When you run a Java program, you can pass arguments to
it, which can be accessed through this array.

Summary:

Putting it all together, public static void main(String args[]) is a public method that:

● Can be called without creating an instance of the class (static).


● Does not return any value (void).
● Serves as the entry point of the program (main).
● Accepts command-line arguments in the form of a String array (String args[]).
Datatypes in Java
Datatype Size
*64 bit
Byte 1 byte Machine
short 2 bytes

int 4 bytes

long 8 bytes

float 4 bytes

Double 8 bytes

boolean 1 byte

char 2 bytes
Type Casting

Widening Casting
Byte -> short -> char -> int -> long -> float -> double

*Automatic

int num1 = 9;
double num2 = num1;
Type Casting
Narrowing Casting
Double -> float -> long -> int -> char -> short -> Byte

*Manual

*Manual
double num1 = 9.8d;
int num2 = (int) num1;
What is a Wrapper Class?
A wrapper class in Java is a class that encapsulates (or "wraps") a primitive data type in an
object.

Common Wrapper Classes:


1. Integer: Wraps the primitive int type.
2. Double: Wraps the primitive double type.
3. Boolean: Wraps the primitive boolean type.

Wrapper classes can be used in Java's collection framework (like ArrayList, HashMap),
which requires objects.

Example:
int num = 10; // Primitive type
Integer wrappedNum = Integer.valueOf(num); // Wrapper class
Difference between print, println
& printf
1. print():
● Usage: Outputs text to the console without adding a newline character at the end.
(cursor remains in the same line)

Example:

System.out.print("Hello");
System.out.print(" World");

Output: Hello World (on the same line)


2. println():

● Usage: Outputs text to the console and adds a newline character at the end, moving the cursor to the
next line.

Example:
System.out.println("Hello");
System.out.println("World");

Output:
Hello
World

3. printf():

● Usage: Outputs formatted text. It allows you to specify the format of the output using format specifiers
(like %d for integers, %s for strings, etc.). Unlike print and println, printf does not automatically
add a newline at the end unless specified.

Example:
System.out.printf("Hello %s, your score is %d%n", "Alice", 90);

Output: Hello Alice, your score is 90 (with %n for a new line)


Basic Input Functions
import java.util.Scanner;

Scanner sc = new Scanner (system.in);

sc.next() //Takes a single input String (only one word)


sc.nextLine() //Takes many input strings (takes complete sentence
sc.nextInt() //Takes an integer value
sc.nextFloat() //Takes an Float Value
Math Functions
Math.max(a,b); - Returns the larger of two values.
Eg. Math.max(5, 10); // Returns 10
Math.min(a,b); - Returns the smaller of two values.
Eg. Math.min(5, 10); // Returns 5
Math.sqrt(num); - Returns the square root of the specified number.
Eg. Math.sqrt(16); // Returns 4.0
Math.abs(-a); - It converts negative numbers to positive.
Eg- Math.abs(-4.7); // Returns 4.7
Math.random(); - Returns a random double value between 0.0 - 0.99
Conditional Statements
if - else statement
if (condition) {
statement1;


} else if (condition) {
statement1;


}
Switch-case statement
switch (expression){
case expression1:statement1;
statement2;
break;
case expression2:statement1;
statement2;
break;
}
Loops
For loop
The for loop is used when you know in advance how many times you want to
execute a statement or a block of statements.

Syntax:

for (initialization; condition; update) {


// Statements to be executed
}

Example:

for (int i = 0; i < 5; i++) {


System.out.println("Iteration: " + i);
}
While loop
The while loop is used when you want to execute a block of statements as long as a
specified condition is true.

Syntax:

while (condition) {
// Statements to be executed
}

Example:

int i = 0;
while (i < 5) {
System.out.println("Iteration: " + i);
i++;
}
Do-while loop
The do-while loop is similar to the while loop, but it guarantees that the block of statements
will be executed at least once, even if the condition is false.

Syntax:

do {
// Statements to be executed
} while (condition);

Example:

int i = 0;
do {
System.out.println("Iteration: " + i);
i++;
} while (i < 5);
Patterns
Solid Rectangle

*****
*****
*****
*****
for (int row = 0; row < 4; row++) { // Loop for 4 rows
for (int col = 0; col < 5; col++) { // Loop for 5 stars in each row
System.out.print("* "); // Draw a star
}
System.out.println(); // Move to the next line after each row
}
Hollow Rectangle

*****
* *
* *
*****
for (int i = 1; i <= 4; i++) { // Loop through rows
for (int j = 1; j <= 5; j++) { // Loop through columns
// print star only when following condition is met
if (i == 1 || i == 4 || j == 1 || j == 5) {
System.out.print("*"); // Print a star
} else {
System.out.print(" "); // Print a space
}
}
System.out.println(); // Move to the next line after
each row
}
Half Pyramid

*
**
***
****
*****
for(int i=1; i<=4; i++){
for(int j=1; j<=i; j++){
System.out.print(“*”);
}
System.out.println();
}
Half Pyramid

*
**
***
****
*****
for(int i=1; i<=4; i++){
for(int j=1; j<= n-i; j++){
System.out.print(“ ”);
}
for(int j=1; j<= i; j++){
System.out.print(“*”);
}
System.out.println();
}
Buttery Pattern
* *
** **
*** ***
********
********
*** ***
** **
* *
//upper half
for(int i=1; i<=4; i++){
for(int j=1; j<= i; j++){
System.out.print(“x”);
}
int spaces = 2*(n-i);
for(int j=1; j<= spaces; j++){
System.out.print(“ ”);
}
for(int j=1; j<= i; j++){
System.out.print(“x”);
}
System.out.println();
}
//upper half
for(int i=4; i>=1; i--){
//same code as the above
}
Functions

return_type function_name(arguments)
{
//operations or logic
}
WAP to print first n natural numbers
import java.util.Scanner;

public class NaturalNumbers {


public static void main(String[] args) {
// Create a scanner object for user input
Scanner sc= new Scanner(System.in);

// Ask the user for the value of n


System.out.print("Enter the value of n: ");
int n = sc.nextInt();

// Print the first n natural numbers


System.out.println("The first " + n + " natural numbers
are:");
for (int i = 1; i <= n; i++) {
System.out.print(i + " ");
}
}
}
WAP to print first n odd numbers
int j=1;
for(int i=0;i<n;i++)
{
system.out.print(j+“ ”);
j=j+2;
}
WAP to print sum of first n natural numbers
int sum=0;
for(i=1;i<=n;i++)
{
sum+=i;
}
system.out.println(sum);
WAP to reverse a number and check if it is a
palindrome
int number = sc.nextInt();

// Store the original number to compare later


int originalNumber = number;
int reversedNumber = 0;

// Reverse the number


while (number != 0) {
int digit = number % 10;
reversedNumber = reversedNumber * 10 + digit;
number = number / 10;
}

// Check if the original number is equal to the reversed number


if (originalNumber == reversedNumber) {
System.out.println(originalNumber + " is a palindrome.");
} else {
System.out.println(originalNumber + " is not a palindrome.");
}
WAP to find the first n numbers of a Fibonacci
Series
// Initialize the first two numbers of the Fibonacci
series
int first = 0, second = 1;

// Print the first n Fibonacci numbers


System.out.println("The first " + n + " numbers of the
Fibonacci Series are:");
for (int i = 1; i <= n; i++) {
System.out.print(first + " ");

// Calculate the next Fibonacci number


int next = first + second;
first = second;
second = next;
}
WAP to SWAP 2 numbers
import java.util.*;
class Swap_With {
public static void main(String[] args) {
int x, y, t;// x and y are to swap
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of X and Y");
x = sc.nextInt();
y = sc.nextInt();
System.out.println("before swapping numbers: "+x +" "+
y);
/*swapping */
t = x;
x = y;
y = t;
System.out.println("After swapping: "+x +" " + y);
System.out.println( );
}
}
WAP to swap 2 numbers without using 3rd
variable.
import java.util.*;
class Swap
{
public static void main(String a[])
{
System.out.println("Enter the value of x and y");
Scanner sc = new Scanner(System.in);
/*Define variables*/
int x = sc.nextInt();
int y = sc.nextInt();
System.out.println("before swapping numbers: "+x +" "+ y);
/*Swapping*/
x = x + y;
y = x - y;
x = x - y;
System.out.println("After swapping: "+x +" " + y);
}
}
WAP to print prime numbers between m-n
import java.util.Scanner;
public class PrimeExample4 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the first number : ");
int start = s.nextInt();
System.out.print("Enter the second number : ");
int end = s.nextInt();
System.out.println("List of prime numbers between " + start + " and " + end);
for (int i = start; i <= end; i++) {
if (isPrime(i)) {
System.out.println(i);
}
}
}
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i <= n/2 ; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
WAP to print factorial of a number
public static void main(String args[]){
int i,fact=1;
int number=5;//It is the number to calculate factorial
for(i=1;i<=number;i++){
fact=fact*i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
Arrays
An array is a collection of data items of the same type that
are stored in contiguous memory locations.
Declaration
Datatype[] arrayname = new datatype[size];

Eg. int[] marks = new int[20];

Initialization

arrayname[index] = value;

Eg. mark[2] = 98;


Datatype[] arrayname = new datatype[size];

Datatype arrayname[] = new datatype[size];

int marks[] = {40, 55, 63, 17, 22, 68, 89, 97, 89}
Default values in an Array in Java are
int Type - 0
float type - 0.0
String type - “ ”

Size of an array:
arrayname.length;

Eg. int length = marks.length;

Sort an array:
Arrays.sort(arrayname);

Eg. Arrays.sort(marks);
2D Arrays:

Datatype[][] arrayname = new datatype[rowsize][colsize];

Eg. int[][] matrix = new int[3][4];


WAP to Search an element in an unsorted
array
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Ask the user for the size of the array


System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();

// Initialize the array


int[] array = new int[size];

// Input elements in the array


System.out.println("Enter " + size + " elements:");
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}
// Ask the user for the element to search
System.out.print("Enter the element to search: ");
int target = scanner.nextInt();

// Search the element in the array


for (int i = 0; i < size; i++) {
if (array[i] == target) {
System.out.println("Element " + target + " found at index "
+ i);
return; // Exit if found
}
}

// If the element is not found


System.out.println("Element " + target + " not found in the
array.");

}
}
WAP to find maximum and minimum in an
Array
// Initialize max and min with the first element of the array
int max = array[0];
int min = array[0];

// Traverse the array to find max and min


for (int i = 1; i < size; i++) {
if (array[i] > max) {
max = array[i]; // Update max
}
if (array[i] < min) {
min = array[i]; // Update min
}
}

// Print the maximum and minimum values


System.out.println("Maximum value in the array: " + max);
System.out.println("Minimum value in the array: " + min);
WAP to find the largest and the second
largest in an Array.
int size = 10;

// Initialize the array


int[] array = {12,25,24,1,6,8,95,4,35,10};

// Initialize variables to hold the largest and second largest


int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;

// Traverse the array to find the largest and second largest


for (int i = 0; i < size; i++) {
if (array[i] > largest) {
secondLargest = largest; // Update second largest
largest = array[i]; // Update largest
}
else if (array[i] > secondLargest && array[i] != largest) {
secondLargest = array[i]; // Update second largest
}
}
WAP to find the missing number in a given
integer array of 1 to 100?
int n = 100;
// Calculate the expected sum of numbers from 1 to 100
int totalSum = n * (n + 1) / 2; // formula for sum of n numbers

// Calculate the sum of the numbers in the array


int arraySum = 0;
for (int num : array) {
arraySum += num;
}

// The missing number is the difference between the expected sum


and the actual sum
int missingNumber = totalSum - arraySum;

// Print the missing number


System.out.println("The missing number is: " + missingNumber);
WAP to find duplicates from an unsorted
array?
int[] array = {4, 3, 2, 7, 8, 2, 3, 1}; // Example array

System.out.println("Duplicate elements:");

// Outer loop picks each element one by one


for (int i = 0; i < array.length; i++) {
// Inner loop compares the picked element with the rest of
the elements
for (int j = i + 1; j < array.length; j++) {
if (array[i] == array[j]) {
System.out.println(array[i]); // Print duplicate
element
break; // Break after finding a duplicate for the
current element
}
}
}
WAP to reverse an Array
int[] array = {1, 2, 3, 4, 5}; // Example array

int start = 0; // Start index


int end = array.length - 1; // End index

while (start < end) {


// Swap the elements at the start and end
int temp = array[start];
array[start] = array[end];
array[end] = temp;

// Move the pointers towards the center


start++;
end--;
}
String
Strings are the type of objects that can store the character
of values

Strings are immutable

Declaration
String strname = "value";

Eg. String name = “KVGCE”;

String strname= new String("value")

Eg. String name = new String("KVGCE")


String str= "geeks";
Input String

Scanner sc = new Scanner(System.in);


String name = sc.next();
String name = sc.nextLine();

Concatenation
String firstName = “Akash”;
String lastname = “Patil”;

String fullName = firstName + “ “ + lastName //Akash Patil


String str = “My college is KVGCE”;

Length of String

int len = strname.length();

int len = str.length(); //19

Char at index
char chr = str.charAt(index);

Char c = str.charAt(5); //o


Sub - String

String substr = strname.subString(beg_idx, end_idx);

//if any one parameter is not specified,by default it


will take the extreme value

Eg. String name = “TonyStark”;

String fname = name.subString(0,4); //Tony


String name = name.subString(4); //Stark
parseInt - convert String to int

String str = “123”;

int num = Integer.parseInt(str); //123

toString - convert integer to String

int num = 123;

String str = Integer.toString(num); //”123”


toUpperCase() / toLowerCase()

String Ustr = str.toUpperCase();

String Lstr = str.toLowerCase();


StringBuilder
String datatype is immutable
StringBuilder class provides an alternative to String Class,
as it creates a mutable sequence of characters.

StringBuilder are mutable

Declaration

StringBuilder strname = new StringBuilder(“value”);

Eg. StringBuilder sb = new StringBuilder(“KVGCE”);


Eg. StringBuilder sb = new StringBuilder(“Tonystark”);

Char at index
char chr = sb.charAt(index);

Char c = sb.charAt(5); //t

Set Char at index


strname.setCharAt(index, “value”);

sb.setCharAt(0, “P”); //sb = Ponystark

//setCharAt replaces the char at that specific index


Length of StringBuilder

int len = sb.length();

Insert function
strname.insert(index, 'char');

Eg: sb.insert(0, 'S');

//inserts the item at the specific index and shifts


the remaining ones
Delete Function

strname.delete(beg_idx, end_idx);

Eg: sb.delete(2,3);

Append Function
strname.append("value");

Eg: sb.append("y");
WAP to count the occurrence of a given
character in a string?
String str = "programming";
char ch = 'm';

int count = 0;

// Loop through the string and count occurrences


of the character
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ch) {
count++;
}
}
System.out.println(count);
WAP to count the number of vowels and
consonants in a given string?
String str = "Hello World";
str = str.toLowerCase();
int vowelCount = 0, consonantCount = 0;

for (int i = 0; i < str.length(); i++) {


char ch = str.charAt(i);

if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch ==


'u') {
vowelCount++;
}
else if (ch >= 'a' && ch <= 'z') {
consonantCount++;
}
}

System.out.println("Number of vowels: " + vowelCount);


System.out.println("Number of consonants: " + consonantCount);
WAP to print duplicate characters from a
string?
String str = "programming";

int[] charCount = new int[256]; // ASCII character set

// Loop through the string and count occurrences of each


character
for (int i = 0; i < str.length(); i++) {
charCount[str.charAt(i)]++;
}

System.out.println("Duplicate characters in the string:");


for (int i = 0; i < 256; i++) {
if (charCount[i] > 1) {
System.out.println((char) i + " appears " +
charCount[i] + " times");
}
}
WAP to reverse a given string and check for
palindrome
String name = "KVGCE";
String revname = "";

for(int i=name.length()-1; i>=0;i--){


revname+=name.charAt(i);
}
System.out.println(revname);

if(name.equals(revname))
System.out.println("Palindrome");
else
System.out.println("Not a Palindrome");
Sorting
Bubble Sort

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping
the adjacent elements if they are in the wrong order.

It compares the adjacent elements and shifts the largest element in the last
position of the array

Time complexity = O(n^2)


int arr[] = {7,8,3,12};
int temp;
int n = arr.length;

for(int i=0; i<n; i++){


for(int j=0; j<n-i-1; j++){
if(arr[j]>arr[j+1]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
Selection Sort

It sorts an array by repeatedly selecting the smallest element from the unsorted
portion and swapping it with the first unsorted element

It finds the smaller element and swaps it with the front most element

Time complexity = O(n^2)


int arr[] = {7,8,3,1,2};
int n = arr.length;

for(int i=0; i<n-1; i++){


int smallest = i;
for(int j=i+1; j<n; j++){
if(arr[smallest]>arr[j]){
smallest = j;
}
}
int temp = arr[smallest];
arr[smallest] = arr[i];
arr[i] = temp;
}
Insertion Sort

Insertion sort is a simple sorting algorithm that works by iteratively inserting each
element of an unsorted list into its correct position in a sorted portion of the list.

Each element in the unsorted part is compared with each element in the sorted
part and place in its right position by shifting the sorted elements.

Time complexity = O(n^2)


int arr[] = {7,8,3,1,2};
int n = arr.length;

for(int i=1; i<n; i++){


int current = arr[i];
int j = i-1;

while(j>=0 && current<arr[j]){


arr[j+1] = arr[j];
j--;
}
arr[j+1] = current;
}
OOP
Object Oriented Programming
Class: A blueprint or template that defines the properties
(attributes) and behavior (methods) of a particular kind of
object. It specifies what a certain type of object would look
like and how it behaves.

Object: An instance of a class. It is a concrete realization


of the class, containing the actual values for the properties
defined by the class.
class Pen {
// Properties (attributes)
String color;
String type;

// Method (behavior)
public void write() {
System.out.println("Writing something...");
}

// Method to print the color of the pen


public void printColor() {
System.out.println(this.color);
}
}
public class OOPS {
public static void main(String[] args) {
// Creating the first Pen object
Pen pen1 = new Pen();
pen1.color = "blue";
pen1.type = "gel";

// Creating the second Pen object


Pen pen2 = new Pen();
pen2.color = "black";
pen2.type = "ballpoint";

// Printing the colors of the pens


pen1.printColor(); // Output: blue
pen2.printColor(); // Output: black
}
}
this keyword:
The this keyword is used to refer to the current class instance variable,
meaning it refers to the current object.

new keyword:
The new keyword is used to create an instance (object) of a class. It
allocates memory for the object on the heap and returns a reference to it.
Constructor
A constructor is a special method used to initialize objects. It is called when an
object is created. Constructors can also initialize object attributes with values.

Types of Constructors

1. Default Constructor:
A constructor with no parameters. It initializes the object with default values.
2. Parameterized Constructor:
A constructor with parameters, used to initialize objects with specific values.
3. Copy Constructor:
A constructor that takes another object of the same class as a parameter and
copies its values.
Properties of Constructors

1. The constructor has the same name as the class.


2. It does not have a return type (not even void).
3. A constructor is called only once for an object when it is created.
Destructor in Java

● A destructor is a method that automatically gets called when an object is no


longer needed, and its life cycle is finished.
● It is responsible for deallocating and freeing memory.
● In Java, we cannot explicitly define destructors. Java automatically
handles memory management through garbage collection.

Garbage Collection

● Garbage Collection is a feature in Java that automatically manages memory


by identifying and removing unused or unreachable objects in the heap
memory.
● The garbage collector runs in the background and ensures that memory is
freed when objects are no longer in use, thus preventing memory leaks.
Pillars of OOP (Object-Oriented Programming)

1. Abstraction

2. Encapsulation

3. Inheritance

4. Polymorphism
Polymorphism
● Polymorphism: The word "poly" means many, and "morphism" means forms.
Polymorphism allows a single action to be performed in different ways.
○ It enables a single interface to have multiple implementations.
○ Polymorphism allows methods or objects to take on many forms.

Types of Polymorphism

1. Compile-Time Polymorphism (Static Polymorphism):


2. Run-Time Polymorphism (Dynamic Polymorphism):
1. Compile-Time Polymorphism (Static Polymorphism):

● This type of polymorphism is resolved at compile time, and it is achieved


through method overloading (function overloading).

● Operator overloading is also a form of static polymorphism, but operator


overloading is not supported in Java.
Method Overloading:

● Method overloading occurs when multiple methods have the same name but
differ in parameters (number or type of arguments).
● These methods are said to be "overloaded."

Rules for Method Overloading:

Overloading can be achieved by:

1. Changing the number of arguments.


2. Changing the type of arguments.
3. Different return types (only when combined with other rules, return types
alone cannot overload a method).
class Calculator {
// Method with two integer parameters
public int add(int a, int b) {
return a + b;
}

// Overloaded method with three integer parameters


public int add(int a, int b, int c) {
return a + b + c;
}

// Overloaded method with two double parameters


public double add(double a, double b) {
return a + b;
}
}
2. Run-Time Polymorphism (Dynamic Polymorphism):
● This type of polymorphism is resolved during runtime and is achieved through
method overriding.
● It allows a subclass to provide a specific implementation of a method that is
already defined in its parent class.

Method Overriding:

● When a subclass has a method with the same signature (same name, return
type, and parameters) as a method in its parent class, it overrides the
method from the parent class.
● Run-time polymorphism enables dynamic method dispatch, where the
method to be executed is determined at runtime based on the object’s type.
class Animal {
public void sound() {
System.out.println("The animal makes a sound");
}
}

class Dog extends Animal {


@Override
public void sound() {
System.out.println("The dog barks");
}
}
Inheritance
● Inheritance is a mechanism in which one object acquires all the properties
and behaviors of a parent object.
● It allows you to create a new class that is built upon an existing class.

Why Use Inheritance?

1. Code Reusability: You can reuse the fields and methods of an existing class
without writing them again.
2. Method Overriding: You can modify or override the parent class methods in
the child class to provide specific implementations.
// Parent class
class Animal {
String name;

public void eat() {


System.out.println("This animal eats food");
}
}

// Child class inheriting from Animal class


class Dog extends Animal {
public void bark() {
System.out.println("The dog barks");
}
}
Types of inheritance in java
Access Modifiers in Java
Access modifiers in Java specify the accessibility or scope of a field, method,
constructor, or class. They help control how much access other classes and code
have to the members of a class, providing security and defining the boundaries for
accessibility in your code.

Types of Access Modifiers

1. Default (No Modifier):


○ Scope: The default access level is package-private, meaning it is
accessible only within the same package.
○ If no access modifier is specified, it will be considered as default.
○ Cannot be accessed from outside its package.
2. Private:

○ Scope: The private modifier restricts access to the fields, methods, or


constructors to the same class only.
○ Cannot be accessed from any other class, even subclasses.
○ This is useful for encapsulation, ensuring that sensitive data is hidden from
external classes.

3. Protected:
● Scope: The protected modifier allows access within the same package and by
subclasses (through inheritance) even if they are in different packages.
● Cannot be accessed from outside the package unless it's through a subclass.

4. Public:

● Scope: The public modifier allows fields, methods, constructors, or classes to be


accessed from anywhere.
● Can be accessed both within the package and outside the package, across different
classes and subclasses.
Encapsulation
Encapsulation is the process of wrapping data (fields) and methods (functions) together
into a single unit, which is typically a class in Java.

By bundling these components, encapsulation allows for data hiding, meaning the
internal details of an object are protected from unauthorized access and modification by
external classes.

Key Points of Encapsulation:

1. Data Hiding: The internal state of the object is hidden from the outside world, and
only specific methods can access or modify the data.
2. Control over Data: Encapsulation allows control over how data is accessed or
modified by using getters and setters.
3. Achieved through Classes: Encapsulation is implemented through classes in
Java, where private variables are defined and accessed through public methods.
Abstraction

Abstraction is the process of hiding the implementation details and exposing only
the functionality to the user. It focuses on what an object can do rather than how it
does it.

Abstraction can be achieved in two ways:

1. Abstract Classes
2. Interfaces
Abstract Class in Java

An abstract class is a class that is declared with the abstract keyword. It


provides partial abstraction, meaning it can have both abstract (without
implementation) and non-abstract (with implementation) methods.

In simple terms, abstraction in Java is a concept that allows you to define a


blueprint for other classes without creating an object of the abstract class itself.

Note: Using abstract classes, we cannot achieve 100% abstraction, as they can
contain non-abstract methods. For full abstraction, interfaces are used.
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void sound();

// Non-abstract method (has a body)


public void sleep() {
System.out.println("The animal is sleeping");
}
}

// Subclass inheriting from the abstract class


class Dog extends Animal {
public void sound() {
System.out.println("The dog barks");
}
}
Interface in Java

An interface in Java is a blueprint of a class that contains only abstract methods


by default. Using interfaces, we can achieve 100% abstraction because
interfaces do not contain any implementation, just method declarations.
// Interface
interface Animal {
// Abstract method (by default)
void sound();

// Abstract method (by default)


void sleep();
}

// Class implementing the interface


class Dog implements Animal {
public void sound() {
System.out.println("The dog barks");
}

public void sleep() {


System.out.println("The dog is sleeping");
}
}
In Java, multiple inheritance is not directly supported with classes, but it
can be achieved using interfaces. This is because a class can implement
multiple interfaces, allowing it to inherit behavior from more than one
source.
// Interface 1
interface Animal {
void eat();
}

// Interface 2
interface Pet {
void play();
}

// Class implementing both interfaces


class Dog implements Animal, Pet {
// Implementing method from Animal interface
public void eat() {
System.out.println("The dog is eating");
}

// Implementing method from Pet interface


public void play() {
System.out.println("The dog is playing");
}
}
static Keyword in Java
The static keyword in Java indicates that the member (variable, method, block, or
nested class) belongs to the class rather than the instance of the class. It is primarily
used for memory management and to refer to common properties shared by all objects
of the class.

Key Points:

1. static Variables:
○ A static variable is shared across all instances of the class.
○ It gets memory only once when the class is loaded.
○ It is often used for common properties like a college name for all students.
2. static Methods:
○ A static method belongs to the class and can be called without creating an
object of the class.
○ It can access only static variables and cannot directly refer to instance
variables (non-static).

You might also like