You are on page 1of 90

CORE JAVA - sriRAM

JAVA:

 Java is a high-level, object-oriented programming language that was developed


by Sun Microsystems (now owned by Oracle Corporation) in the mid-1990s. It
was designed to be platform-independent, secure, robust, and easy to use. Java
has gained widespread popularity and is widely used for developing a wide range
of applications, including desktop software, mobile apps, web applications,
enterprise systems, embedded systems, and more.
 Java is a high-level, object-oriented programming language that provides a
platform-independent environment for developing software applications.
 It offers a rich set of features, including garbage collection, exception handling,
multi-threading, and a vast standard library, making it a versatile and widely-used
language in the software development industry.
 Java is a computing platform that consists of the Java Virtual Machine (JVM) and
the Java Development Kit (JDK).
 The JVM is a runtime environment that interprets and executes Java bytecode,
while the JDK is a set of tools, compilers, and libraries used for developing Java
applications.
 Together, they provide a cross-platform runtime environment for executing Java
programs on different operating systems.

History of JAVA:

 Java was conceived in the early 1990s by a team of engineers at Sun


Microsystems, led by James Gosling. Originally called "Oak," it was designed as a
language for programming consumer electronic devices. However, the focus
shifted to developing a platform-independent language for internet applications.
 In 1995, Sun Microsystems officially announced Java to the public. It was
presented as a language with the ability to run on any platform, with the slogan
"Write Once, Run Anywhere" (WORA). This platform independence was achieved
through the use of the Java Virtual Machine (JVM) and the concept of bytecode.
 In 2010, Oracle Corporation acquired Sun Microsystems, becoming the new
steward of the Java platform. Oracle has continued to develop and support Java.
 Continued Popularity and Expansion: Java remains one of the most popular
programming languages worldwide, powering a wide range of applications,
including desktop software, mobile apps, web development, enterprise systems,
scientific research, and more. Its robustness, security, platform independence,
and extensive ecosystem contribute to its continued success.

Features of JAVA (BUZZ WORDS):

These buzzwords reflect the key features and strengths of Java as a programming
language, highlighting its platform independence, object-oriented nature, memory
management, concurrency support, robust exception handling, extensive standard

Thopstech.com 1 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
library, security measures, open-source community, scalability, and backward
compatibility.

 Simple: Java's syntax is derived from C and C++, which are widely known and used
programming languages. This familiarity makes it easier for developers who are
already familiar with these languages to transition to Java and understand its
syntax.OOP allows for modular and reusable code through the use of classes,
objects, and inheritance. This approach makes it easier to manage and maintain
code over time.

 Platform Independent: Java's "Write Once, Run Anywhere" (WORA) concept


allows Java programs to be compiled into bytecode, which can run on any
platform with a Java Virtual Machine (JVM). This platform independence is a key
feature of Java and enables developers to write code that can be executed on
various operating systems without recompilation.

 Object-Oriented Programming (OOP): Java is an object-oriented language,


emphasizing the use of objects that encapsulate data and behavior. OOP
concepts such as encapsulation, inheritance, and polymorphism are integral to
Java programming and enable modular and reusable code.

 Distributed: Java is often considered a distributed programming language


because it provides a range of features, frameworks, and APIs that facilitate the
development of distributed applications.

 Interpreted: java uses a combination of compilation and interpretation to execute


programsJava source code is first compiled into bytecode by the Java compiler
(javac). The bytecode is a platform-independent representation of the code and
is saved in .class files.The Java Virtual Machine (JVM) executes the bytecode. The
JVM is an interpreter for Java bytecode

 Robust: Java is often regarded as a robust programming language.Java enforces


strong type checking, which helps catch errors at compile-time rather than at
runtime.Java has a built-in exception handling mechanism that allows developers
to handle and recover from runtime errors and exceptional conditions.Java
incorporates automatic memory management through garbage collection. The
garbage collector identifies and frees up memory occupied by objects that are no
longer referenced, eliminating manual memory management errors such as
memory leaks and dangling pointers.

 Security: Java incorporates several features and mechanisms to enhance security


and protect against various threats.Java's bytecode verifier checks the integrity
and safety of compiled bytecode before execution. It verifies that the bytecode
adheres to the language's rules and does not violate security constraints.Java's
class loading mechanism ensures that classes are loaded securely from trusted
sources. The class loading process verifies the integrity and authenticity of classes
to prevent the execution of tampered or malicious code.

Thopstech.com 2 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
 Portable: Java is known for its portability, meaning that Java programs can run on
different platforms without the need for modification.Java source code is
compiled into platform-independent bytecode rather than machine code specific
to a particular operating system or hardware architecture.Java's "Write Once,
Run Anywhere" principle enables Java programs to be developed on one platform
and run on any platform with a compatible JVM. Once the bytecode is generated,
it can be executed on Windows, macOS, Linux, or any other platform that
supports Java, as long as the corresponding JVM is available.

 Dynamic: Java is considered a dynamic programming language in several


aspects.Java incorporates automatic memory management through the use of a
garbage collector. It dynamically allocates memory for objects at runtime and
automatically reclaims memory for objects that are no longer referenced.Java
supports dynamic binding, which allows the determination of the appropriate
method implementation at runtime. This enables polymorphism and late binding,
where the specific method to be executed is determined based on the actual
type of the object at runtime.

 High Performance: Java is designed to deliver high performance in several


ways.The JVM interprets the bytecode initially, but as the code is executed, the
JVM identifies hotspots—sections of code that are frequently executed—and
dynamically compiles them into highly optimized native machine code.

First JAVA Program:

The main method in Java is the entry point for a Java program. It has a specific
signature that must be followed for the program to execute correctly. Here's an
explanation of the main method signature:

 public: This keyword is an access modifier that indicates the visibility of the
method. In the case of the main method, it needs to be public so that it can be
accessed from outside the class.

Thopstech.com 3 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
 static: This keyword indicates that the method belongs to the class itself and can
be called without creating an instance of the class. The main method is static
because it is called by the JVM before any objects of the class are created.
 void: This keyword specifies the return type of the method, which indicates that
the main method does not return any value.
 main: This is the name of the method. It is fixed and cannot be changed. It serves
as the entry point for the Java program.
 String[] args: This is the parameter of the main method. It is an array of strings
(String[]) named args. The args parameter allows command-line arguments to be
passed to the program. These arguments can be accessed within the main
method using the args parameter.

-> The main method signature, as shown above, is required for a Java program to run
successfully. It allows the JVM to identify and execute the starting point of the
program

JDK - JRE - JVM:


JDK (Java Development Kit): The JDK, or Java Development Kit, is a software
development kit that provides tools, libraries, and documentation for developing Java
applications. It includes the Java compiler, which translates Java source code into
bytecode, as well as other tools such as the Java debugger, Java documentation
generator, and various utility programs. The JDK is required for developing Java
applications and consists of the Java Development Kit (JDK) and the Java Runtime
Environment (JRE).

JRE (Java Runtime Environment): The JRE, or Java Runtime Environment, is a runtime
environment that allows the execution of Java applications. It provides the necessary
libraries, Java Virtual Machine (JVM), and other components required to run Java
programs. The JRE does not include the development tools like the compiler and
debugger, which are part of the JDK. If you only need to run Java applications and
don't plan on developing them, you can install the JRE.

JVM (Java Virtual Machine): The JVM, or Java Virtual Machine, is the runtime
environment in which Java bytecode is executed. It is an essential component of both
the JDK and the JRE. The JVM is responsible for translating bytecode into machine-
specific instructions that can be understood and executed by the underlying
operating system and hardware. It provides memory management, garbage collection,
and various optimizations to ensure efficient execution of Java programs. The JVM
also provides platform independence, allowing Java programs to run on any system
that has a compatible JVM installed.

Thopstech.com 4 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM

Keywords :
Keywords are particular words that act as a key to a code. These are predefined words
by Java so they cannot be used as a variable or object name or class name.
Here are some keywords in Java along with their explanations:

public: It is an access modifier keyword that allows a class, method, or variable to be


accessed from any other part of the program.
class: It is used to declare a class in Java, which is a blueprint for creating objects that
encapsulate data and behavior.
static: It is used to define a static member (variable or method) that belongs to the
class itself rather than to individual instances of the class.
void: It is a keyword used to indicate that a method does not return any value.
main: It is the entry point method for a Java program. It is executed when the
program starts and serves as the starting point for the execution of the program.
new: It is used to create a new instance of a class or to dynamically allocate memory
for an array or object.
this: It is a reference variable that refers to the current object within a method or
constructor.
super: It is a reference variable that refers to the superclass (parent class) of the
current object.
if: It is used to specify conditional statements. It executes a block of code only if the
specified condition is true.

Thopstech.com 5 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
else: It is used in conjunction with the if statement to specify an alternative block of
code to execute if the condition of the if statement is false.
for: It is used to create a loop that iterates a specific number of times. It consists of an
initialization, condition, and increment/decrement expression.
while: It is used to create a loop that executes a block of code as long as a specified
condition is true. The condition is evaluated before each iteration.
do: It is used in conjunction with the while statement to create a loop that executes a
block of code at least once, and then repeatedly as long as the specified condition is
true.
break: It is used to terminate the execution of a loop or a switch statement and
transfers control to the next statement after the loop or switch.
continue: It is used to skip the remaining code in the current iteration of a loop and
proceed to the next iteration.
return: It is used to exit from a method, optionally returning a value to the caller of
the method.
try/catch/finally: They are used together to handle exceptions in Java. The try block
contains the code that may throw an exception, the catch block catches and handles
the exception, and the finally block contains code that is always executed, regardless
of whether an exception occurs or not.

These are just a few of the keywords in Java. Understanding these keywords is
essential for writing Java programs and utilizing the language's features effectively.

Data Types:
In Java, a data type defines the kind of data that a variable can hold. It specifies the
range of values the variable can take and the operations that can be performed on it.
Java provides several built-in data types, which can be classified into the following
categories:

-> Primitive Data Types:

 byte: Represents integer values from -128 to 127.


 short: Represents integer values from -32,768 to 32,767.
 int: Represents integer values from -2,147,483,648 to 2,147,483,647.
 long: Represents integer values from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807.
 float: Represents single-precision floating-point numbers.
 double: Represents double-precision floating-point numbers.
 boolean: Represents the boolean values true or false.
 char: Represents a single character using the Unicode encoding scheme.

-> Reference Data Types:

 String: Represents a sequence of characters.

Thopstech.com 6 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
 Classes: User-defined classes can be used as reference data types. They are
created using class definitions and can hold complex data structures and
behaviors.

-> Arrays:

Arrays are used to store multiple values of the same data type. They can be created
using any of the primitive or reference data types, such as int[], String[], or double[],
among others.

-> Enumerations (Enums):

Enums are special data types used to define a set of named constants. They provide a
way to represent a fixed set of values, such as days of the week or colors.

These data types have different sizes, ranges, and operations associated with them.
They determine the amount of memory allocated to store values of that type and the
operations that can be performed on the values. In addition to the built-in data types,
Java also allows the creation of custom data types through classes and interfaces.

By using different data types, you can efficiently manage and manipulate data in your
Java programs, ensuring that variables are correctly defined to hold the appropriate
values and perform the desired operations.

Variable:
In programming, a variable is a named storage location that holds a value. It acts as a
container for storing and manipulating data during the execution of a program. Here's
an explanation of variables in Java:

Declaration: To use a variable in Java, you must declare it first. The declaration
specifies the name of the variable and its data type.
For example:

int age;

In this case, age is the name of the variable, and int is the data type representing
integer values.

Initialization: After declaring a variable, you can assign an initial value to it. This
process is called initialization.
For example:

int age = 25;

Thopstech.com 7 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
Here, the variable age is declared and initialized with the value 25.

Data Types: Variables in Java have specific data types that define the kind of values
they can hold. Some common data types include int (integers), double (floating-point
numbers), boolean (true/false), char (single characters), and String (sequences of
characters), among others. The data type determines the size, range, and operations
that can be performed on the variable.

Assignment: Once a variable is declared and initialized, its value can be changed or
updated using the assignment operator (=).
For example: age = 30;
This statement assigns the value 30 to the age variable, replacing the previous value.

Scope: Variables have a scope, which defines the portion of the program where the
variable is visible and can be accessed. In Java, variables can have local scope, where
they are limited to a specific block of code (e.g., within a method), or they can have
broader scope, such as instance variables (belonging to an object) or class variables
(shared among all instances of a class).

Naming Conventions: Variables in Java follow certain naming conventions. They


should start with a letter, underscore (_), or dollar sign ($) and can contain letters,
digits, underscores, and dollar signs. It is good practice to choose meaningful and
descriptive names for variables to improve code readability.

Usage: Variables are used to store and manipulate data during program execution.
They can be involved in calculations, used as parameters in methods, passed as
arguments, and used in decision-making statements and loops, among other
operations.

By using variables, you can store and manipulate data dynamically in your Java
programs, making them adaptable and capable of performing complex tasks.

TYPES OF VARIABLES:
In Java, variables can be classified into several types based on their scope and
lifetime. Here are the main types of variables in Java:

Local Variables: Local variables are declared within a method, constructor, or a block
of code and are accessible only within that specific scope. They are created when the
block of code is entered and cease to exist once the block is exited. Local variables
must be explicitly initialized before they can be used.

Instance Variables: Instance variables, also known as member variables or object


variables, are declared within a class but outside any method, constructor, or block.
Each instance of the class has its own copy of instance variables. These variables are
initialized with default values when the object is created unless explicitly assigned
different values.

Thopstech.com 8 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
Class Variables: Class variables, also known as static variables, are declared with the
static keyword within a class but outside any method, constructor, or block. Unlike
instance variables, class variables are shared among all instances of a class.

They are associated with the class itself rather than any specific instance. Class
variables are initialized with default values when the class is loaded unless explicitly
assigned different values.

It's important to note that local variables are stored on the stack, whereas instance
variables and class variables are stored in the heap and static memory area,
respectively.

Here's an example that demonstrates the different types of variables in Java:

In this example, localVariable is a local variable within the method() method,


instanceVariable is an instance variable associated with each object of the class, and
classVariable is a class variable shared among all instances of the class.

Understanding the types of variables in Java is essential for proper data management
and access control within your programs.

Thopstech.com 9 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
Operators:
operators are symbols or special characters that perform specific operations on
operands (variables, constants, or expressions). They are classified into several
categories based on their functionality. Here are the main categories of operators in
Java along with examples and explanations:

Arithmetic Operators:

 + (Addition): Adds two operands together. Example: int result = 10 + 5; (result will
be 15).
 - (Subtraction): Subtracts the right operand from the left operand. Example: int
result = 10 - 5; (result will be 5).
 * (Multiplication): Multiplies two operands. Example: int result = 10 * 5; (result
will be 50).
 / (Division): Divides the left operand by the right operand. Example: int result = 10
/ 5; (result will be 2).
 % (Modulus): Returns the remainder of the division operation. Example: int result
= 10 % 5; (result will be 0)

Assignment Operators:

 = (Assignment): Assigns the value on the right to the variable on the left.
Example: int x = 10; (assigns the value 10 to the variable x).
 +=, -=, *=, /=, %= (Compound Assignment): Performs the operation on the right
and assigns the result to the variable on the left. Example: x += 5; (adds 5 to the
value of x and assigns the result back to x).

Comparison Operators:

 == (Equality): Checks if two operands are equal. Example: boolean result = (x ==


y); (result will be true if x is equal to y).
 != (Inequality): Checks if two operands are not equal. Example: boolean result =
(x != y); (result will be true if x is not equal to y).
 <, <=, >, >= (Relational): Compares the values of two operands. Example: boolean
result = (x < y); (result will be true if x is less than y).

Logical Operators:

 && (Logical AND): Returns true if both operands are true. Example: boolean result
= (x > 0 && y < 10); (result will be true if x is greater than 0 and y is less than 10).
 || (Logical OR): Returns true if either operand is true. Example: boolean result =
(x > 0 || y < 10); (result will be true if x is greater than 0 or y is less than 10).
 ! (Logical NOT): Negates the boolean value of the operand. Example: boolean
result = !flag; (result will be true if flag is false).

Thopstech.com 10 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
Increment and Decrement Operators:

 ++ (Increment): Increases the value of the operand by 1. Example: x++; (increases


the value of x by 1).
 -- (Decrement): Decreases the value of the operand by 1. Example: x--; (decreases
the value of x by 1).

Bitwise Operators:

 & (Bitwise AND): Performs a bitwise AND operation on the operands.


 | (Bitwise OR): Performs a bitwise OR operation on the operands.
 ^ (Bitwise XOR): Performs a bitwise XOR (exclusive OR) operation on the
operands.
 ~ (Bitwise Complement): Inverts the bits of the operand.

These are some of the main categories of operators in Java, along with their examples
and explanations. Understanding and utilizing these operators allows you to perform
various computations, comparisons, and logical operations within your Java programs.
Scanner:
The Scanner class in Java is a part of the java.util package and provides various
methods for reading input from different sources, such as the console, files, or
streams. It is commonly used to obtain user input from the console. Here's a
comprehensive explanation of the Scanner class, along with sample programs and
explanations:

Importing the Scanner class: To use the Scanner class, you need to import it at the top
of your Java file:

import java.util.Scanner;

Creating a Scanner object: To read input, you need to create an instance of the
Scanner class. Here's the syntax:

Scanner scanner = new Scanner(System.in);

Reading different types of input:

Reading integers: The Scanner class provides the nextInt() method to read integer
values.
int number = scanner.nextInt();

Reading floating-point numbers: The Scanner class provides the nextFloat() or


nextDouble() methods to read floating-point values.
float number = scanner.nextFloat();
double number = scanner.nextDouble();

Thopstech.com 11 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
Reading strings: The Scanner class provides the next() method to read a single word as
a string, and the nextLine() method to read a whole line of text.
String word = scanner.next();
String line = scanner.nextLine();

Sample Program 1: Reading User Input Here's an example that demonstrates reading
user input using the Scanner class:
import java.util.Scanner;

public class UserInputExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter your name: ");


String name = scanner.nextLine();

System.out.print("Enter your age: ");


int age = scanner.nextInt();

System.out.println("Hello, " + name + "! You are " + age + " years old.");

scanner.close();
}
}

In this program, the user is prompted to enter their name and age. The nextLine()
method is used to read the name, and the nextInt() method is used to read the age.
The entered values are then displayed as part of a greeting message.

Sample Program 2: Calculating Sum Here's an example that demonstrates using the
Scanner class to calculate the sum of two numbers:

Thopstech.com 12 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM

In this program, the user is prompted to enter two numbers, which are then added
together to calculate the sum. The sum is displayed as the output.

The Scanner class is a versatile tool for reading user input and can be used to handle
various data types and input sources. It simplifies the process of interacting with the
user and enables dynamic input processing in Java programs.

Conditionals:
Conditional statements in Java allow you to execute specific blocks of code based on
certain conditions. There are three main types of conditional statements: if, if-else,
and nested if, if else if ladder.

If Statement: The if statement allows you to execute a block of code if a condition


evaluates to true. If the condition is false, the block is skipped. The syntax is as
follows:

if (condition) {

// Code to be executed if condition is true

Thopstech.com 13 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
}

Example:

If-Else Statement: The if-else statement extends the if statement by providing an


alternative block of code to be executed when the condition evaluates to false. The
syntax is as follows:

if (condition) {

// Code to be executed if condition is true

} else {

// Code to be executed if condition is false

Example:

Nested if :

A nested if statement is an if statement that is nested within another if statement or


within an else block. It allows for more complex decision-making by providing a way
to test multiple conditions within a conditional block.

Syntax:

if (condition1) {

Thopstech.com 14 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
// Code to be executed if condition1 is true

if (condition2) {

// Code to be executed if condition2 is true

} else {

// Code to be executed if condition2 is false

} else {

// Code to be executed if condition1 is false

Explanation:

 The outer if statement checks the condition1. If it is true, the corresponding block
of code is executed.
 If the condition1 is true, the nested if statement within the outer if block is
evaluated. If condition2 is true, the code inside the nested if block is executed.
 If condition2 is false, the code inside the else block of the nested if statement is
executed.
 If condition1 is false, the code inside the else block of the outer if statement is
executed.

Example:

Thopstech.com 15 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM

In this example, the program checks the age variable. If the age is greater than or
equal to 18, it prints "You are eligible for voting." It then checks the isStudent variable
using a nested if statement. If isStudent is true, it prints "You are also a student." If
isStudent is false, it prints "You are not a student." If the initial condition of age >= 18
is false, it prints "You are not eligible for voting." The nested if statement allows for
additional conditions and actions to be tested within the outer condition.

Nested if statements are useful when you need to perform more complex branching
and condition checking in your Java programs. They allow for multiple levels of
decision-making and provide flexibility in handling different scenarios.

if-else if ladder:

The "if-else if ladder" is a series of if and else if statements that allow you to test
multiple conditions and execute different blocks of code based on those conditions. It
provides a way to choose among multiple options and perform specific actions
depending on which condition is true.

Syntax:

if (condition1) {

// Code to be executed if condition1 is true

} else if (condition2) {

// Code to be executed if condition2 is true

Thopstech.com 16 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
} else if (condition3) {

// Code to be executed if condition3 is true

} else {

// Code to be executed if all conditions are false

Explanation:

 The if statement checks the first condition. If the condition is true, the
corresponding block of code is executed, and the rest of the ladder is skipped.
 If the first condition is false, the else if statement checks the next condition. If it is
true, the corresponding block of code is executed, and the rest of the ladder is
skipped.
 The else if statements can be repeated any number of times to test additional
conditions.
 If none of the conditions in the if or else if statements are true, the else block is
executed. This block acts as a default option if all conditions fail.

Example:

In this example, the program checks the value of the number variable using an "if-else
if ladder". If the number is greater than 0, it prints "The number is positive.". If the
number is less than 0, it prints "The number is negative.". If neither condition is true,
it prints "The number is zero.". The ladder allows the program to choose the
appropriate action based on the value of the number variable.

The "if-else if ladder" is useful when you have multiple mutually exclusive conditions
and need to perform different actions based on each condition. It provides a
structured way to handle complex decision-making scenarios in your Java programs.

Thopstech.com 17 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM

Switch:
the switch statement is a control flow statement that allows you to select one of
many code blocks to be executed based on the value of an expression. It provides an
alternative to multiple if-else statements when testing a single variable against
multiple possible values.

Syntax:

switch (expression) {
case value1:
// Code to be executed if expression matches value1
break;
case value2:
// Code to be executed if expression matches value2
break;
case value3:
// Code to be executed if expression matches value3
break;
// ...
default:
// Code to be executed if expression does not match any case
break;
}

Explanation:

 The switch statement starts by evaluating the given expression.


 The value of the expression is then compared to each case value in the switch
block.
 If a match is found between the expression and a case value, the corresponding
block of code is executed.
 The break statement is used to exit the switch block after executing the
corresponding code. Without the break statement, execution would fall through
to the next case.
 If none of the case values match the expression, the code inside the default block
is executed (optional).

Thopstech.com 18 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
Example:

Thopstech.com 19 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM

In this example, the switch statement is used to determine the name of the day based
on the value of the dayOfWeek variable. Depending on the value of dayOfWeek, the
corresponding case block is executed. If dayOfWeek is 3, the code inside the case 3
block is executed, and dayName is set to "Tuesday". The break statement ensures that
execution exits the switch block after the matching case is executed.

The switch statement is a concise and efficient way to perform multi-way branching
based on a single variable's value. It provides a cleaner alternative to multiple nested
if-else statements when you need to test against multiple possible values of a
variable.

Iterative Statements (LOOPS):

Iterative statements, also known as looping or repetitive statements, allow you to


repeatedly execute a block of code as long as a specific condition is true or until a
specific condition is met. In Java, there are three main types of iterative statements:
for loop, while loop, and do-while loop. Let's explore each of them in detail, along
with their syntaxes, example programs, outputs, and explanations:
1.For Loop:
The for loop is used to iterate a specific number of times. It consists of three parts:
initialization, condition, and update. The loop body is executed repeatedly until the
condition becomes false.

Syntax:
for (initialization; condition; update) {
// Code to be executed in each iteration

Thopstech.com 20 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
}

Example:

Output:

Explanation:
In this example, the for loop initializes i to 1. It then checks the condition i <= 5. As
long as the condition is true, the loop body is executed, and i is incremented by 1 in
each iteration. The loop stops when i becomes 6.

2.While Loop:
The while loop repeatedly executes a block of code as long as a specified condition is
true. It checks the condition before each iteration, and if the condition is false initially,
the loop is never executed.

Syntax:
while (condition) {
// Code to be executed as long as condition is true
}

Example:

Thopstech.com 21 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
Output:

Explanation:
In this example, the while loop checks the condition count < 5. If the condition is true,
the loop body is executed. Inside the loop, the value of count is printed, and then it is
incremented by 1. The loop continues until count becomes 5.

3.Do-While Loop:
The do-while loop is similar to the while loop, but with one key difference. It executes
the loop body at least once, regardless of the condition. After each iteration, it checks
the condition, and if it is true, the loop continues. If the condition is false, the loop is
terminated.

Syntax:
do {
// Code to be executed at least once
} while (condition);

Example:

Output:

Thopstech.com 22 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM

Explanation: In this example, the do-while loop executes the loop body first, printing
the value of i, and then increments i by 1. After each iteration, it checks the condition
i < 5. If the condition is true, the loop continues. The loop stops when i becomes 5.

Iterative statements provide a way to repeat a block of code, allowing for efficient
and controlled execution of repetitive tasks. Each type of loop has its own use cases
and conditions for termination, providing flexibility in handling different scenarios.

Jumping Statements :
Jump statements in Java are used to alter the normal flow of execution within a
program. They allow you to transfer control to a specific location in your code, such as
jumping out of loops or skipping code blocks. There are three main jump statements
in Java: break, continue, and return. Let's explore each of them in detail, along with
example programs and their outputs:

Break Statement:
The break statement is used to exit from a loop or switch statement. When
encountered, it immediately terminates the innermost loop or switches the execution
to the next statement outside the loop or switch.

Example Program:

Thopstech.com 23 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
Output:

Explanation:
In this example, the for loop iterates from 1 to 5. When the value of i becomes 3, the
break statement is encountered, causing an immediate termination of the loop. As a
result, the remaining iterations are skipped, and the program moves to the next
statement after the loop.

Continue Statement:

The continue statement is used to skip the current iteration of a loop and continue
with the next iteration. When encountered, it jumps to the next iteration without
executing the remaining code within the loop body.

Example Program:

Output:

Explanation:

Thopstech.com 24 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
In this example, the for loop iterates from 1 to 5. When the value of i becomes 3, the
continue statement is encountered, causing the current iteration to be skipped. As a
result, the code inside the loop body after the continue statement is not executed for
that particular iteration.

Return Statement:
The return statement is used to exit from a method and return a value (if the method
has a return type). It can be used to terminate the execution of a method prematurely
and return a specific value to the calling code.

Example Program:

Output:

Explanation: In this example, the calculateSum method calculates the sum of two
integers. If the second integer (b) is 0, the method immediately returns 0 using the
return statement, bypassing the remaining code. This allows the method to handle
the special case of division by zero or other scenarios where returning a specific value
is necessary.

Jump statements provide control over the flow of execution within a program,
allowing for more flexibility and handling of specific conditions. By using break,
continue, and return statements, you can customize the behavior of loops, skip
unnecessary iterations, and exit methods when needed.

Arrays :

In Java, an array is a data structure that allows you to store a fixed number of
elements of the same data type under a single variable name. It provides a

Thopstech.com 25 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
convenient way to group related data together and perform operations on them as a
whole.

Arrays in Java have the following characteristics:

 Homogeneous Elements: All elements in an array must be of the same data type.
For example, you can have an array of integers, an array of strings, or an array of
custom objects, but you cannot mix different data types in a single array.

 Fixed Size: Once an array is created, its size is fixed and cannot be changed. You
specify the size of the array when you declare and allocate memory for it. This
means you cannot add or remove elements from an array after it is created. If
you need a dynamically resizable collection of elements, you can consider using
other data structures like ArrayList.

 Zero-based Indexing: In Java, array indices start from 0. The first element of an
array is accessed using index 0, the second element with index 1, and so on. The
last element is accessed using the index array.length - 1.

 Contiguous Memory Allocation: Elements of an array are stored in contiguous


memory locations. This allows for efficient access to elements by their index.
However, it also means that the memory for the entire array needs to be
allocated at once, which can be a limitation for large arrays.

Here's a step-by-step explanation of working with arrays in Java:

Declare the Array: Start by declaring an array variable. The syntax is as follows:
dataType[] arrayName;

Allocate Memory: Use the new keyword to allocate memory for the array. Specify the
size of the array within square brackets. For example:
arrayName = new dataType[arraySize];

Alternatively, you can combine declaration and allocation in a single statement:


dataType[] arrayName = new dataType[arraySize];
Initialize the Array: Optionally, you can initialize the array with specific values. This can
be done using an initializer list enclosed in curly braces. For example:
dataType[] arrayName = {value1, value2, value3, ...};

Accessing Elements: You can access individual elements of the array using their index.
The index ranges from 0 to array.length - 1. For example:
dataType element = arrayName[index];

You can also modify the value of an element by assigning a new value to it:
arrayName[index] = newValue;

Thopstech.com 26 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
Array Length: The length property of an array provides the number of elements in the
array. It is accessed as follows:
int length = arrayName.length;

Iterating Over an Array: To process each element of an array, you can use a loop. The
most common loop used for iterating over an array is the for loop. For example:
for (int i = 0; i < arrayName.length; i++) {
// Access and process arrayName[i]
}

Arrays in Java are widely used in various programming tasks, such as storing
collections of data, implementing algorithms, sorting and searching elements, and
more. They provide a fundamental building block for working with structured data in
Java programs.

Here's a sample Java program that demonstrates taking dynamic input for an array
and provides an explanation of the program:

Thopstech.com 27 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM

Explanation:

The program starts by importing the necessary class Scanner from the java.util
package to facilitate user input.
The main method is declared, which serves as the entry point of the program.
An instance of the Scanner class is created to read user input from the console.
The user is prompted to enter the size of the array using System.out.print and
scanner.nextInt(). The entered value is stored in the variable size.
An integer array numbers is created with the size specified by the user.
A message is displayed to instruct the user to enter the elements of the array.
A for loop is used to iterate from 0 to size - 1. Inside the loop, the user is prompted to
enter each element using scanner.nextInt(), and the entered value is assigned to the
corresponding index of the numbers array.
After the user has entered all the elements, a message is displayed to indicate that
the array has been entered.
Another for loop is used to iterate over the array and print each element using
System.out.print.
Finally, the Scanner is closed to release any resources associated with it.

This program allows the user to dynamically input the size of the array and the
elements of the array.It then displays the entered array. For example, if the user
enters the size as 5 and the elements as 10, 20, 30, 40, and 50, the program will
output:

Thopstech.com 28 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM

This program demonstrates how to use the Scanner class to obtain user input, create
an array of the desired size, populate the array with user-provided values, and display
the contents of the array.

OOPS
Object-oriented programming (OOP) is a programming paradigm that organizes
software design around objects, which are instances of classes that encapsulate data
and behavior. Java is an object-oriented programming language that fully supports
OOP principles. Here are the key object-oriented features in Java explained in detail:

Classes and Objects: In Java, a class is a blueprint or template that defines the
structure and behavior of objects. It specifies the data (attributes) and methods
(functions) that objects of that class can have. An object, on the other hand, is an
instance of a class. It represents a specific entity or concept in the real world.

Encapsulation: Encapsulation is the process of hiding the internal details of an object


and exposing only the necessary information and functionality. In Java, this is
achieved by using access modifiers (such as public, private, and protected) to control
the visibility of class members (variables and methods). Encapsulation helps in
achieving data abstraction, security, and modularity.

Inheritance: Inheritance allows you to define a new class (called the derived class or
subclass) based on an existing class (called the base class or superclass). The derived
class inherits the attributes and methods of the base class, allowing code reuse and
creating a hierarchical relationship between classes. In Java, you can extend a class
using the extends keyword.

Polymorphism: Polymorphism allows objects of different classes to be treated as


objects of a common superclass. It enables methods to be invoked on objects without
knowing their specific type, which promotes flexibility and extensibility. Polymorphism
in Java is achieved through method overriding (redefining a method in a subclass) and
method overloading (having multiple methods with the same name but different
parameters).

Abstraction: Abstraction is the process of representing complex real-world entities as


simplified models within a program. It involves capturing only the relevant properties

Thopstech.com 29 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
and behavior of an object while hiding unnecessary details. Abstract classes and
interfaces are used in Java to create abstract types that define a common interface or
contract for a group of related objects.

TERMS in OOPS:

Association: Association represents a relationship between two or more objects. It


can be a simple one-to-one relationship, one-to-many relationship, or many-to-many
relationship. In Java, association is typically achieved by creating references between
objects, allowing them to interact and collaborate.

Composition: Composition is a strong form of association where one class is


composed of one or more objects of other classes. The composed objects cannot
exist independently and have a lifecycle tied to the lifecycle of the container class. In
Java, composition is implemented by creating instance variables of other classes
within a class.

Aggregation: Aggregation is a weak form of association where one class has a


reference to another class, but the referenced objects can exist independently. The
aggregated objects have their lifecycle and can be shared by multiple classes. In Java,
aggregation is represented by having a class hold a reference to another class.

Overloading and Overriding: Overloading refers to having multiple methods in a class


with the same name but different parameters. It allows different versions of a
method to be called based on the arguments provided. Overriding, on the other hand,
occurs when a subclass provides its own implementation of a method defined in the
superclass. It allows a subclass to modify the behavior of inherited methods.

Interfaces: An interface in Java defines a contract that a class can implement. It


specifies a set of methods that the implementing class must provide. Interfaces allow
for multiple inheritance, where a class can implement multiple interfaces. They are
useful for achieving abstraction, defining common behavior, and promoting loose
coupling.

These object-oriented features in Java provide a powerful and flexible way to model
real-world entities, create modular and reusable code, and manage complex software
systems. By leveraging these features, developers can design well-structured,
maintainable, and scalable applications.

Class & Object :


In Java, a class is a blueprint or template that defines the structure and behavior of
objects. It serves as a blueprint for creating objects that represent real-world entities
or concepts. A class encapsulates data (attributes) and behavior (methods) that
define the characteristics and actions of the objects belonging to that class.

Thopstech.com 30 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
It represents a concept or entity in the real world. An object, on the other hand, is an
instance of a class. It is a concrete representation of the class and can hold data
(attributes) and perform operations (methods).

A class consists of the following components:


 Member Variables (Attributes): These are variables that hold data and
represent the state of objects.
 Constructors: These are special methods used to initialize objects of the class.
 Methods: These are functions that define the behavior and actions that
objects can perform.
 Access Modifiers: These modifiers (e.g., public, private, etc.) control the
visibility and accessibility of class members.
 Other Modifiers: These modifiers (e.g., static, final, etc.) provide additional
characteristics to class members.

In summary, a class in Java serves as a blueprint for creating objects, defining their
attributes and behavior. Objects are instances of classes that hold the state and
perform actions according to the defined behavior. By utilizing classes and objects,
you can model real-world entities, organize code, and implement concepts such as
encapsulation, inheritance, polymorphism, and abstraction.

Syntax for Class Declaration:


In Java, a class declaration follows this syntax:

The modifiers can be access modifiers like public, private, etc., or other modifiers like
abstract, final, etc. The ClassName represents the name of the class.

Syntax for Object Creation: To create an object in Java, you use the new keyword
followed by the class name and parentheses:

ClassName objectName = new ClassName();

The objectName is a variable of type ClassName that holds the reference to the object
in memory.

Thopstech.com 31 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
Sample Program with Explanation: Here's a simple Java program that demonstrates
the usage of classes and objects:

Explanation:

In the above program, we have a class named Person. It has two member variables:
name and age, representing the attributes of a person. The class also has a
constructor that takes the name and age as parameters and initializes the member
variables.

The class has a method called displayInfo() that prints the name and age of the
person.

In the main method, an object of the Person class is created using the constructor by
providing the name and age values. The object is stored in the variable person1.

Thopstech.com 32 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
Finally, the displayInfo() method is called on the person1 object, which displays the
information of the person.

Real-World Examples:

Real-World Example - Person: Consider a scenario where you need to model a person
in a software application. The Person class can represent a person with attributes like
name, age, address, and methods like displayInfo(), calculateAge(), etc. Multiple
objects of the Person class can be created to represent different individuals.

Real-World Example - Car: In a car rental system, the Car class can define the
properties of a car, such as make, model, year, and methods like start(), stop(),
accelerate(), etc. Objects of the Car class can be created to represent different cars
available for rent.

By using classes and objects, you can effectively model and represent real-world
entities and their behavior in Java programs. Objects allow you to store data specific
to individual instances, while classes provide a blueprint for creating objects and
defining their common attributes and methods.

Methods :
Methods in Java are blocks of code that encapsulate a specific functionality or
behavior. They allow you to break down complex tasks into smaller, reusable units of
code. Here's a comprehensive explanation of methods in Java, including definitions,
examples, sample programs, syntax, control flow, and types of methods:

Definition: A method in Java is a named block of code that performs a specific task. It
has a signature that includes the method name, return type, and optional parameters.
Methods can have input parameters, perform operations, and optionally return a
value.

Syntax for Method Declaration: The syntax for declaring a method in Java is as follows:

Thopstech.com 33 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
 modifiers: These are optional keywords that define the accessibility and behavior
of the method, such as public, private, static, final, etc.
 returnType: It specifies the type of value returned by the method. Use void if the
method doesn't return any value.
 methodName: It is the name of the method, following the Java naming
conventions.
 parameterList: It defines the input parameters (arguments) passed to the
method. Multiple parameters are separated by commas.

Example of a Method: Here's a simple example of a method that calculates the sum of
two numbers:

In this example, the method name is calculateSum, and it takes two integer
parameters a and b. It calculates the sum of a and b and returns the result as an
integer.

Sample Program with Method: Here's a sample Java program that demonstrates the
usage of a method:

Thopstech.com 34 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
In this program, the main method is the entry point of the program. It calls the
calculateSum method, passing 5 and 3 as arguments. The returned value is stored in
the result variable and displayed using System.out.println().

Control Flow in Methods: Methods in Java follow a sequential control flow. The
statements within the method are executed one after another, from top to bottom.
Control flow can also be altered using control structures such as loops (for, while, do-
while) and conditional statements (if, else, switch).

Types of Methods in Java:

Methods in Java can be classified into two categories: predefined methods and user-
defined methods. Predefined methods are provided by the Java language itself as part
of the Java API, while user-defined methods are created by the programmers. Let's
explore both types with example programs:

Predefined Methods: Predefined methods are built-in methods provided by Java


through its standard libraries. These methods are part of the Java API and can be used
directly in your programs. They offer a wide range of functionality for performing
common tasks.

Example Program 1: Math Class Methods The Math class in Java provides various
mathematical operations. Here's an example that demonstrates the usage of
predefined methods from the Math class:

Thopstech.com 35 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
In this program, the Math.max() method is used to find the maximum of two numbers
(x and y), the Math.pow() method calculates x raised to the power of y, and the
Math.sqrt() method finds the square root of x.

User-defined Methods: User-defined methods are created by the programmers to


perform specific tasks that are not provided by the predefined methods. They allow
you to encapsulate reusable code into a separate method, improving code
organization and reusability.

User-defined methods in Java can be categorized based on their parameters and


return types. Let's explore the different types of user-defined methods with
examples:

1. Method without Parameters and Return Type: These methods do not accept any
parameters and do not return a value. They perform a specific action or task.

Example:

In this example, the greet() method does not take any parameters and does not
return anything. It simply prints "Hello, World!" when invoked.

2. Method with Parameters and Return Type: These methods accept one or more
parameters and return a value after performing a specific computation or operation.

Example:

Thopstech.com 36 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM

In this example, the add() method takes two integer parameters a and b. It returns
the sum of the two numbers when invoked.

3. Method with Parameters but without Return Type: These methods accept one or
more parameters but do not return a value. They perform operations or actions
based on the provided parameters.

Example:

In this example, the printMessage() method takes a String parameter message and
prints the message when invoked.

4. Method with Multiple Parameters and Return Type: These methods accept multiple
parameters and return a value after performing a specific computation or operation.

Example:

Thopstech.com 37 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM

In this example, the calculateAverage() method takes three integer parameters a, b,


and c. It calculates the average of the three numbers and returns the result when
invoked.

These are some common types of user-defined methods based on parameters and
return types in Java. By utilizing different combinations of parameters and return
types, you can create customized methods to cater to specific requirements in your
programs.

Other definitions:

Void Methods: These methods do not return a value. The void keyword is used as the
return type. They perform specific operations but don't return any result.

Non-void Methods: These methods return a value of a specified type. The return type
is declared explicitly. They perform operations and return a result using the return
statement.

Static Methods: These methods belong to the class rather than an instance of the
class. They can be called directly using the class name, without creating an object of
the class.

Instance Methods: These methods belong to individual objects (instances) of a class.


They are called on object references and can access instance variables and other
instance methods.

Parameterized Methods: These methods take input parameters (arguments) and use
them in their operations. The parameters provide values to the method for
processing.

Thopstech.com 38 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
Method Overloading: Method overloading allows the declaration of multiple methods
with the same name but different parameters. They provide flexibility in calling
methods with different argument combinations.

Recursive Methods: These methods call themselves directly or indirectly. They are
used for solving problems that can be divided into smaller subproblems.

These types of methods serve different purposes and enable you to write modular,
reusable, and organized code.

In summary, methods in Java are essential building blocks for organizing code and
implementing specific functionalities. They encapsulate operations, promote code
reuse, and allow for modularity and abstraction. By understanding the syntax, control
flow, and types of methods, you can effectively utilize them in your Java programs.

Constructor :
Constructors in Java are special methods that are used to initialize objects of a class.
They have the same name as the class and do not have a return type. Constructors
are invoked automatically when an object is created and can be used to set initial
values to the object's member variables or perform any necessary setup operations.
Here's a comprehensive explanation of constructors in Java, including definitions,
examples, types, and sample programs:

Definition: A constructor in Java is a special method that has the same name as the
class and is used to initialize objects. It is called automatically when an object is
created using the new keyword. Constructors are responsible for setting the initial
state of an object by initializing its member variables or performing other necessary
setup operations.

Syntax for Constructor Declaration: The syntax for declaring a constructor in Java is as
follows:

accessModifier: It specifies the accessibility of the constructor, such as public, private,


etc.
ClassName: It represents the name of the class.
parameters: These are optional parameters passed to the constructor. Multiple
parameters are separated by commas.

Thopstech.com 39 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
Example of a Constructor: Here's an example of a constructor in Java:

In this example, the Person class has a constructor that takes two parameters: name
and age. Inside the constructor, the values of the parameters are assigned to the
corresponding member variables using the this keyword.

Types of Constructors in Java:

Default Constructor: If a class does not explicitly define any constructors, a default
constructor is provided automatically. It takes no parameters and initializes member
variables with default values (e.g., 0 for numeric types, null for objects).

Parameterized Constructor: A parameterized constructor accepts one or more


parameters and allows you to initialize member variables with custom values based
on the provided arguments. It provides flexibility in setting initial values during object
creation.

Thopstech.com 40 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM

In this program, the Rectangle class has a parameterized constructor that takes length
and width as parameters. It initializes the corresponding member variables. The class
also has a method calculateArea() that calculates the area of the rectangle based on
the length and width.

Thopstech.com 41 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
In the main method, objects of the Rectangle class are created using the constructor.
The areas of the rectangles are calculated using the calculateArea() method, and the
results are displayed.

Constructors play a vital role in initializing objects and setting their initial state. By
defining constructors, you can ensure that objects are created with the required data
and perform any necessary setup operations.

Constructor Overloading :
Constructor overloading in Java allows a class to have multiple constructors with
different parameter lists. Each constructor provides a different way to initialize
objects of the class. It enables flexibility in creating objects with various initialization
options. Here's an explanation of constructor overloading with definitions, uses,
applications, an example program, and explanation:

Definition: Constructor overloading refers to having multiple constructors within a


class, each having a unique parameter list. By providing multiple constructors, you can
create objects using different combinations of arguments, allowing for different ways
to initialize objects.

Uses and Applications:

Flexibility in Object Initialization: Constructor overloading provides flexibility in object


initialization. It allows you to create objects using different sets of initial values,
accommodating different scenarios or preferences.

Convenience for Object Creation: With overloaded constructors, you can provide
convenient ways to create objects by offering various parameter combinations. This
eliminates the need to set each member variable individually after object creation.

Example Program with Explanation: Consider a Rectangle class that represents a


rectangle shape. Let's implement constructor overloading to provide different ways to
initialize rectangle objects based on the available dimensions:

Thopstech.com 42 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM

In this example, the Rectangle class has three constructors:

Thopstech.com 43 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
 The default constructor initializes both length and width to 0.
 The parameterized constructor with length and width parameters sets the
member variables based on the provided values.
 The parameterized constructor with only the length parameter initializes length
with the provided value and sets width to 0.

In the main method, we create three Rectangle objects using different constructors.
rectangle1 is created using the default constructor, rectangle2 is created with specific
length and width, and rectangle3 is created with only the length. We then calculate
the areas of the rectangles using the calculateArea() method and display the results.

Constructor overloading allows for different ways to create objects based on the
available constructors. It provides flexibility in object initialization and enhances the
usability and convenience of a class.

this :
In Java, the this keyword is a reference to the current object within a class. It can be
used to refer to the instance variables, instance methods, or constructors of the
current object. The this keyword is mainly used to eliminate ambiguity between
instance variables and parameters, as well as to invoke one constructor from another.
Here's a comprehensive explanation of the this keyword in Java:

1. Reference to Instance Variables: The this keyword can be used to refer to instance
variables of the current object. It is used to differentiate between local variables and
instance variables when they have the same name.

Example:

public class Person {


String name;

public void setName(String name) {


this.name = name;
}
}

In this example, the this.name refers to the instance variable name, whereas name
refers to the parameter of the method. It helps to avoid ambiguity and assign the
value to the correct variable.

2. Reference to Constructors: The this keyword can be used to invoke one constructor
from another constructor within the same class. This is known as constructor
chaining.

Example:

Thopstech.com 44 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
public class Rectangle {
int length;
int width;

public Rectangle() {
this(0, 0); // Invokes the parameterized constructor with length and width as 0
}

public Rectangle(int length, int width) {


this.length = length;
this.width = width;
}
}

In this example, the default constructor invokes the parameterized constructor using
this(0, 0). This way, the common initialization logic can be centralized in one
constructor.

3. Passing the Current Object as an Argument: The this keyword can be used to pass
the current object as an argument to another method or constructor.

Example:

public class Person {


String name;

public Person() {
printDetails(this);
}

public void printDetails(Person person) {


System.out.println("Name: " + person.name);
}
}

In this example, the this keyword is passed as an argument to the printDetails()


method, allowing it to access the name instance variable of the current object.

The this keyword is a powerful tool in Java that allows you to refer to the current
object within a class. It helps to avoid naming conflicts, invoke methods or
constructors, and pass the current object as an argument. By utilizing the this
keyword effectively, you can enhance the clarity and functionality of your Java code.

Thopstech.com 45 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
static :

The static keyword in Java is used to define class-level members that belong to the
class itself rather than individual objects. It can be applied to variables, methods, and
nested classes. Here's a comprehensive explanation of the static keyword in Java,
including definitions, examples, and sample programs with explanations:

1. Static Variables: Static variables, also known as class variables, are shared among all
instances of a class. They are initialized only once, at the start of the program, and
retain their values throughout the program's execution. Static variables are declared
using the static keyword.

Example:

In this example, the count variable is declared as a static variable. It is shared among
all instances of the Counter class, and each instance can access and modify its value
using the count variable.

2. Static Methods: Static methods belong to the class itself rather than individual
objects. They can be invoked directly using the class name, without creating an
instance of the class. Static methods cannot access non-static (instance) variables or
methods directly.

Example:

Thopstech.com 46 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
In this example, the add() method is declared as a static method. It can be invoked
using the class name, such as MathUtils.add(5, 3), without creating an object of the
MathUtils class.

3. Static Blocks: Static blocks are used to initialize static variables or perform other
one-time initialization tasks. They are executed only once when the class is loaded
into memory, before any object of the class is created. Static blocks are enclosed
within curly braces and preceded by the static keyword.

Example:

In this example, the static block is executed before the main method. It prints the
message "Static block executed" when the class is loaded into memory.

Sample Program with Static Members: Here's an example program that demonstrates
the usage of static variables, methods, and blocks:

Thopstech.com 47 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM

In this program, the Circle class has a static variable count that keeps track of the
number of circle objects created. The Circle class also has a static method getCount()
that returns the count value.

In the main method, two circle objects circle1 and circle2 are created. The
calculateArea() method is invoked on each object to calculate the area. The
getCount() method is used to retrieve the total count of circle objects created.

Thopstech.com 48 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
The static keyword allows you to define class-level members and access them without
creating an instance of the class. Static members are useful for sharing data among
instances, performing utility operations, and providing global access to certain
functionality.

Inheritance :

Inheritance is a fundamental concept in object-oriented programming that allows one


class to inherit the properties and behaviors of another class. It enables code reuse,
promotes modularity, and allows for the creation of class hierarchies. Inheritance in
Java is achieved using the extends keyword. Let's explore inheritance in detail,
including syntax, types, sample programs, explanations, and real-world examples:

Syntax for Inheritance: In Java, the extends keyword is used to establish an inheritance
relationship between classes. The syntax for inheritance is as follows:

class ChildClass extends ParentClass {


// Child class members and methods
}

In this syntax, the ChildClass is the subclass or derived class that inherits from the
ParentClass (also called superclass or base class). The child class inherits the members
(fields and methods) of the parent class and can add its own members or override
inherited methods.

Types of Inheritance in Java:

Single Inheritance: In single inheritance, a class extends only one superclass. It is the
most common type of inheritance.

Multilevel Inheritance: In multilevel inheritance, a class extends another class, which


in turn extends another class. This forms a hierarchical structure.

Hierarchical Inheritance: In hierarchical inheritance, multiple classes extend a single


superclass. Each subclass inherits the common properties and behaviors from the
superclass.

Multiple Inheritance (not supported in Java): Multiple inheritance refers to a class


inheriting from multiple superclasses. While Java does not support multiple
inheritance for classes, it allows multiple inheritance for interfaces.

Thopstech.com 49 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
Sample Program with Explanation:

Consider an example of an inheritance hierarchy with the Vehicle class as the


superclass and the Car and Motorcycle classes as subclasses:

class Vehicle {
protected String brand;

public void drive() {


System.out.println("Driving the vehicle");
}
}

class Car extends Vehicle {


private int numberOfDoors;

public void setNumberOfDoors(int doors) {


this.numberOfDoors = doors;
}

public void displayDetails() {


System.out.println("Brand: " + brand);
System.out.println("Number of doors: " + numberOfDoors);
}
}

class Motorcycle extends Vehicle {


private boolean hasSideCar;

public void setHasSideCar(boolean hasSideCar) {


this.hasSideCar = hasSideCar;
}

public void displayDetails() {


System.out.println("Brand: " + brand);
System.out.println("Has side car: " + hasSideCar);
}
}

public class InheritanceExample {


public static void main(String[] args) {
Car car = new Car();
car.brand = "Ford";
car.setNumberOfDoors(4);
car.displayDetails();

System.out.println();

Thopstech.com 50 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
Motorcycle motorcycle = new Motorcycle();
motorcycle.brand = "Harley-Davidson";
motorcycle.setHasSideCar(false);
motorcycle.displayDetails();
}
}

In this program, the Vehicle class is the superclass that defines the common
properties and behavior for vehicles. The Car and Motorcycle classes are subclasses
that inherit from the Vehicle class.

The Car class adds its own member numberOfDoors and methods to set the number
of doors and display the details. The Motorcycle class adds its own member
hasSideCar and methods to set whether it has a sidecar and display the details.

In the main method, objects of Car and Motorcycle are created, and their respective
methods are called to set the values and display the details.

Real-World Example: A real-world example of inheritance is the relationship between


different types of animals. For instance, consider a class hierarchy with the Animal
class as the superclass and Mammal, Bird, and Fish classes as subclasses. Each
subclass inherits common characteristics from the Animal class while adding specific
properties and behaviors. The Mammal class can have properties like fur or milk
production, the Bird class can have properties like wings or ability to fly, and the Fish
class can have properties like fins or ability to swim. In this way, inheritance models
the hierarchical relationship and code reuse between different types of animals.

In summary, inheritance in Java allows classes to inherit properties and behaviors


from other classes. It facilitates code reuse, modularity, and the creation of class
hierarchies. By utilizing inheritance, you can model real-world relationships and
create more organized and reusable code structures.

Let's provide separate examples for each type of inheritance in Java along with
explanations and real-world examples:

1. Single Inheritance: In single inheritance, a class extends only one superclass. Here's
an example:

Thopstech.com 51 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM

Explanation: In this example, the Animal class is the superclass that defines the eat()
method. The Dog class is the subclass that extends the Animal class and adds its own
method bark(). The Dog class inherits the eat() method from the Animal class. The
main method creates a Dog object and calls both the inherited eat() method and the
bark() method.

Real-World Example: In real-world scenarios, you can consider the Vehicle class as the
superclass and specific vehicle types like Car, Motorcycle, and Truck as subclasses.
Each subclass inherits common properties and behaviors from the Vehicle class and
adds its own unique properties and behaviors.

2. Multilevel Inheritance: In multilevel inheritance, a class extends another class,


which in turn extends another class. Here's an example:

Thopstech.com 52 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM

Explanation: In this example, the Animal class is the superclass, the Dog class extends
the Animal class, and the Labrador class extends the Dog class. Each class adds its own
unique method. The Labrador class inherits both the eat() method from the Animal
class and the bark() method from the Dog class. The main method creates a Labrador
object and calls all the inherited methods as well as the play() method.

Real-World Example: Multilevel inheritance can be seen in graphical user interface


(GUI) frameworks where a base class like Component is extended by classes like
Button, Label, and TextField. Further, these classes may be extended by specific
classes like Checkbox, RadioButton, etc., to provide more specialized components.

Thopstech.com 53 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
3. Hierarchical Inheritance: In hierarchical inheritance, multiple classes extend a single
superclass. Here's an example:

Explanation: In this example, the Animal class is the superclass, and both the Dog and
Cat classes are subclasses that extend the Animal class. Each subclass adds its own
unique method. Both the Dog and Cat classes inherit the eat() method from the
Animal class. The main method creates objects of both subclasses and calls the
inherited methods as well as the specific methods of each subclass.

Thopstech.com 54 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
Real-World Example: In a human resources management system, a base class like
Employee can be extended by subclasses like Manager, Developer, and Designer. Each
subclass inherits common attributes and methods from the Employee class while
adding specialized attributes and methods based on their roles.

Note: Multiple inheritance is not supported for classes in Java, but it is supported for
interfaces, allowing a class to implement multiple interfaces.

In summary, inheritance in Java provides a mechanism to create class hierarchies and


facilitates code reuse and modularity. Single inheritance allows a class to extend a
single superclass, multilevel inheritance allows chaining of subclasses, and hierarchical
inheritance allows multiple subclasses to extend a single superclass. Each type of
inheritance has its own use cases and helps in organizing and structuring code
effectively.

Here are some important terms and definitions related to inheritance in Java, along
with examples:

1. Inheritance: Inheritance is a mechanism in object-oriented programming that


allows one class to acquire the properties and behaviors of another class. It promotes
code reuse and supports the concept of "is-a" relationship.

Example:

In this example, the Dog class inherits from the Animal class, acquiring its properties
and methods.

2. Superclass/Base Class/Parent Class: A superclass, also known as a base class or


parent class, is the class from which other classes inherit properties and methods.

Example:

Thopstech.com 55 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
In this example, the Animal class is the superclass/base class.

3. Subclass/Derived Class/Child Class: A subclass, also known as a derived class or child


class, is the class that inherits properties and methods from a superclass.

Example:

In this example, the Dog class is the subclass/derived class that inherits from the
Animal class.

4. extends Keyword: The extends keyword is used to establish an inheritance


relationship between classes. It indicates that a class is inheriting from another class.

Example:

In this example, the Dog class extends the Animal class using the extends keyword.

5. Method Overriding: Method overriding occurs when a subclass provides its own
implementation of a method that is already defined in its superclass. It allows a
subclass to modify or extend the behavior of the inherited method.

Example:

Thopstech.com 56 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM

In this example, the Dog class overrides the makeSound() method defined in the
Animal class to provide its own implementation.

6. super Keyword: The super keyword is used to refer to the superclass from within a
subclass. It can be used to access the superclass's members or invoke the superclass's
constructor.

Example 1 - Accessing superclass member:

Example 2 - Invoking superclass constructor:

Thopstech.com 57 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM

In these examples, the super keyword is used to access the name member from the
superclass and to invoke the superclass's constructor.

These terms and definitions provide a foundation for understanding inheritance in


Java. Inheritance allows for code reuse, promotes modularity, and supports creating
class hierarchies in object-oriented programming.

Polymorphism :
Polymorphism in Java refers to the ability of an object to take on different forms and
behave differently based on the context. It allows objects of different classes to be
treated as objects of a common superclass. Polymorphism enables code flexibility,
reusability, and extensibility. There are two types of polymorphism in Java: compile-
time polymorphism (method overloading) and runtime polymorphism (method
overriding). Here's a detailed explanation of polymorphism along with an example
program and real-world examples:

Polymorphism Definition: Polymorphism is the ability of an object to take on multiple


forms. In Java, it allows objects of different classes to be treated as objects of a
common superclass, enabling them to exhibit different behaviors based on their
specific implementations.

Compile-Time Polymorphism (Method Overloading): Compile-time polymorphism, also


known as method overloading, occurs when multiple methods with the same name
but different parameters exist in a class. The appropriate method is determined at
compile-time based on the method invocation.

Example:

Thopstech.com 58 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM

In this example, the Calculator class has two add methods, one with two parameters
and another with three parameters. The appropriate method is selected at compile-
time based on the number and types of arguments provided during the method
invocation.

Runtime Polymorphism (Method Overriding): Runtime polymorphism, also known as


method overriding, occurs when a subclass provides its own implementation of a
method that is already defined in its superclass. The appropriate method is
determined at runtime based on the type of the object.

Example:

Thopstech.com 59 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
In this example, the Animal class has a makeSound method, which is overridden by
the Dog class to provide its own implementation. When the makeSound method is
called on a Dog object, the overridden method in the Dog class is executed.

Sample Program with Explanation: Consider an example program that demonstrates


polymorphism by treating objects of different classes as objects of a common
superclass:

Thopstech.com 60 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM

Explanation: In this example, the Shape class is the superclass, and the Circle and
Rectangle classes are the subclasses that inherit from the Shape class. Each subclass
overrides the draw method to provide its own implementation. In the main method,
objects of the subclasses are assigned to variables of the superclass type. When the
draw method is called on these objects, the appropriate overridden method is
executed based on the actual type of the object.

Real-World Examples:

Shape Hierarchy: In a graphics application, you can have a base class like Shape with
subclasses like Circle, Rectangle, and Triangle. Each subclass can override the draw
method to provide its own shape-specific drawing implementation.

Animal Hierarchy: Consider an Animal class with subclasses like Dog, Cat, and Bird.
Each subclass can override the makeSound method to provide the specific sound that
each animal makes.

Polymorphism allows for code flexibility and reusability. It enables you to write
generic code that can operate on objects of different classes, as long as they share a
common superclass. Polymorphism is a powerful feature of object-oriented

Thopstech.com 61 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
programming and is widely used in real-world applications to achieve modularity and
extensibility.

super :
The super keyword in Java is used to refer to the superclass (parent class) of a
subclass. It can be used to access the superclass's members (variables and methods)
and invoke the superclass's constructor. The super keyword is particularly useful in
scenarios where a subclass needs to inherit or override the behavior of its superclass.
Here's a detailed explanation of the super keyword in Java, along with sample
programs and explanations:

1. Accessing Superclass Members: The super keyword can be used to access the
members (variables and methods) of the superclass within the subclass.

Example 1 - Accessing Superclass Variable

In this example, the Dog class extends the Animal class and inherits the name
variable. The displayDetails method of the Dog class uses the super keyword to access
the name variable from the superclass.

Example 2 - Invoking Superclass Method:

Thopstech.com 62 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM

In this example, the Dog class overrides the makeSound method from the Animal
class. The super.makeSound() statement invokes the makeSound method of the
superclass, allowing the subclass to inherit and extend the behavior.

2. Invoking Superclass Constructor: The super keyword can be used to invoke the
constructor of the superclass from the constructor of the subclass. This is particularly
useful when the superclass has a parameterized constructor that needs to be called
explicitly.

Example:

class Animal {
protected String name;

public Animal(String name) {


this.name = name;
}
}

class Dog extends Animal {


private int age;

public Dog(String name, int age) {


super(name); // Invoking superclass constructor
this.age = age;
}

public void displayDetails() {

Thopstech.com 63 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
System.out.println("Name: " + super.name);
System.out.println("Age: " + age);
}
}

In this example, the Dog class extends the Animal class and has its own instance
variable age. The Dog class's constructor uses the super(name) statement to invoke
the parameterized constructor of the superclass, passing the name argument. This
ensures that the name variable is properly initialized in the superclass.

Sample Program with Explanation: Consider an example program that demonstrates


the usage of the super keyword to access superclass members and invoke the
superclass constructor:

class Animal {
protected String name;

public Animal(String name) {


this.name = name;
}

public void makeSound() {


System.out.println("Animal is making a sound");
}
}

class Dog extends Animal {


private int age;

public Dog(String name, int age) {


super(name); // Invoking superclass constructor
this.age = age;
}

public void displayDetails() {


System.out.println("Name: " + super.name); // Accessing superclass variable
System.out.println("Age: " + age);
}

@Override
public void makeSound() {
super.makeSound(); // Invoking superclass method
System.out.println("Dog is barking");
}
}

Thopstech.com 64 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
public class SuperKeywordExample {
public static void main(String[] args) {
Dog dog = new Dog("Buddy", 3);
dog.displayDetails();
dog.makeSound();
}
}

Explanation: In this example, the Animal class is the superclass, and the Dog class is
the subclass that extends the Animal class. The Dog class has its own instance variable
age. The Dog class's constructor uses the super(name) statement to invoke the
parameterized constructor of the Animal class, passing the name argument. This
ensures that the name variable is properly initialized in the superclass. The
displayDetails method uses the super.name expression to access the name variable
from the superclass. The makeSound method overrides the superclass method and
uses the super.makeSound() statement to invoke the makeSound method of the
superclass.

When the program is executed, it creates a Dog object with the name "Buddy" and
age 3. The displayDetails method is called to display the dog's details, and the
makeSound method is called to make the dog bark.

The super keyword is a useful tool in Java to access superclass members and invoke
the superclass constructor. It enables inheritance and facilitates code reuse and
extension in object-oriented programming.

static & instance blocks :


Static and instance blocks in Java are used to initialize the static and instance
variables, respectively, in a class. They are executed during class loading and object
creation, respectively. These blocks provide flexibility and allow you to perform
initialization tasks based on specific requirements. Here's an explanation of static and
instance blocks, along with example programs and comparisons with constructors in
inheritance:

Static Blocks: Static blocks are used to initialize static variables or perform other one-
time initialization tasks. They are executed only once when the class is loaded into
memory, before any object of the class is created.

Example:

Thopstech.com 65 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM

Explanation: In this example, the MyClass class has a static block that initializes the
count static variable to 10. The static block is executed only once, before the main
method is called. The output of the program will be:

The static block is useful for initializing static variables and performing other one-time
initialization tasks, such as reading from a configuration file or setting up a database
connection.

Instance Blocks: Instance blocks are used to initialize instance variables or perform
other initialization tasks that are specific to each object of a class. They are executed
every time an object is created, before the constructor is called.

Example:

Thopstech.com 66 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM

Explanation: In this example, the MyClass class has an instance block that initializes
the x instance variable to 5. The instance block is executed every time an object of the
class is created. The output of the program will be:

The instance block is useful for initializing instance variables and performing other
initialization tasks specific to each object, such as validating input or setting up default
values.

Comparison with Constructors in Inheritance: Constructors and blocks play different


roles in the initialization process of classes and objects in inheritance:

.
Constructors are used to create and initialize objects of a class. They are called
explicitly using the new keyword, and they can be overloaded to provide multiple
ways of initializing objects.
.
.
Blocks (static and instance) are used to perform initialization tasks before the
constructors are called. Static blocks are executed once during class loading, while
instance blocks are executed for each object created.
.

Thopstech.com 67 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
Example:

class Animal {

static {

System.out.println("Static block of Animal class");

System.out.println("Instance block of Animal class");

public Animal() {

System.out.println("Constructor of Animal class");

class Dog extends Animal {

static {

System.out.println("Static block of Dog class");

System.out.println("Instance block of Dog class");

public Dog() {

Thopstech.com 68 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
System.out.println("Constructor of Dog class");

public class InheritanceExample {

public static void main(String[] args) {

Dog dog = new Dog();

Output:

Static block of Animal class

Static block of Dog class

Instance block of Animal class

Constructor of Animal class

Instance block of Dog class

Constructor of Dog class

Explanation: In this example, the Animal class and the Dog class both have static and
instance blocks, as well as constructors. The blocks are executed in the order of class
hierarchy, with the static blocks executed once during class loading and the instance
blocks executed for each object created. The constructors are then called to complete
the object initialization.

In summary, static blocks are executed once during class loading and are useful for
initializing static variables or performing one-time initialization tasks. Instance blocks
are executed for each object created and are useful for initializing instance variables
or performing object-specific initialization tasks. Constructors are used to create and
initialize objects and are called after the execution of blocks. The combination of
constructors and blocks provides flexibility in the initialization process of classes and
objects in Java.

Thopstech.com 69 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
final:
The final keyword in Java is used to define entities that cannot be modified. It can be
applied to variables, methods, and classes. When applied to variables, it makes them
constants that cannot be reassigned. When applied to methods, it prevents them
from being overridden in subclasses. When applied to classes, it prevents inheritance,
making the class non-extendable. Here's a detailed explanation of the final keyword in
Java, along with multiple examples and explanations:

1. Final Variables: When a variable is declared as final, its value cannot be changed
once it is assigned. It behaves as a constant.

Example:

Explanation: In this example, the variable x is declared as final and assigned a value of
5. Any attempt to modify the value of x will result in a compilation error.

2. Final Methods: When a method is declared as final, it cannot be overridden in any


subclass. It maintains the same implementation throughout the class hierarchy.

Example:

Thopstech.com 70 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM

Explanation: In this example, the makeSound method in the Animal class is declared
as final. Any attempt to override this method in the Dog class will result in a
compilation error.

3. Final Classes: When a class is declared as final, it cannot be subclassed or extended.


It prevents inheritance and ensures that the class cannot have any subclasses.

Example:

Explanation: In this example, the Parent class is declared as final. Any attempt to
create a subclass of the Parent class will result in a compilation error.

4. Final Arguments: When a method parameter is declared as final, its value cannot be
changed within the method.

Example:

Thopstech.com 71 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
Explanation: In this example, the method parameters a and b are declared as final.
Any attempt to modify their values within the method will result in a compilation
error.

5. Final and Initialization: A final variable must be assigned a value either during
declaration or within the constructor of the class.

Example:

Explanation: In this example, the x variable is declared as final but not initialized
during declaration. It is assigned a value of 5 within the constructor. It is necessary to
initialize a final variable before it is used.

The final keyword has several uses and benefits in Java:

 Constants: final variables can be used to define constants that cannot be


modified.
 Security: final methods prevent subclasses from modifying the behavior, ensuring
that critical logic remains unchanged.
 Optimization: The use of final allows the compiler to perform certain
optimizations, such as inlining methods.
 Thread Safety: final variables are inherently thread-safe, as their values cannot be
changed once assigned.

In summary, the final keyword is used to declare entities that cannot be modified. It
can be applied to variables, methods, and classes. final variables behave as constants,
final methods cannot be overridden, and final classes cannot be subclassed.
Understanding the appropriate usage of final helps in designing robust and secure
Java programs.

packages:

Packages in Java are a way to organize and structure classes and interfaces into
different namespaces. They provide a mechanism for modularizing code, preventing
naming conflicts, and enhancing code readability and maintainability. Packages help in
grouping related classes together and provide a hierarchical structure to organize

Thopstech.com 72 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
classes at different levels. Let's explore packages in Java, including their types and
example programs:

1. Default Package: When no package is specified for a class, it belongs to the default
package. Classes in the default package are not explicitly placed in any named
package.

Example:

class MyClass {
// Class implementation
}

Explanation: In this example, the MyClass does not belong to any named package. It is
part of the default package. However, it is recommended to always use named
packages rather than the default package.

2. Named Packages: Named packages are user-defined packages that provide a way to
organize and group related classes together. They follow the standard naming
conventions and use a hierarchical structure with periods (.) as separators.

Example:

package com.mycompany.mypackage;

class MyClass {
// Class implementation
}

Explanation: In this example, the MyClass belongs to the com.mycompany.mypackage


package. The package name reflects the organization's domain name or reverse
domain name convention.

3. Importing Packages: To use classes from other packages, you need to import them
using the import statement. Importing eliminates the need to use the fully qualified
name of the class.

Example:

package com.mycompany.mypackage;

import java.util.ArrayList;

class MyClass {
// Class implementation
}

Thopstech.com 73 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM

Explanation: In this example, the ArrayList class from the java.util package is imported
using the import statement. It allows using the ArrayList class without specifying the
fully qualified name.

4. Accessing Classes from Different Packages: To access classes from different


packages without importing them, you need to use the fully qualified name of the
class, which includes the package name along with the class name.

Example:

package com.mycompany.mypackage;

class MyClass {
public static void main(String[] args) {
java.util.ArrayList<String> list = new java.util.ArrayList<>();
// Use the ArrayList from java.util package with fully qualified name
list.add("Hello");
}
}

Explanation: In this example, the ArrayList class from the java.util package is used
without importing it. The fully qualified name of the class is used to access and
instantiate the ArrayList object.

Benefits of Using Packages:

 Organization: Packages help in organizing classes and interfaces into logical


groups based on their functionality or purpose.
 Namespace Management: Packages prevent naming conflicts by providing
separate namespaces for classes with the same name.
 Modularity: Packages allow for modular development and code reuse by
encapsulating related classes within a package.
 Access Control: Packages provide access control mechanisms like access
modifiers (public, protected, private) to restrict the visibility of classes and
members.
 Readability and Maintenance: Packages improve code readability and
maintainability by providing a structured and hierarchical organization of classes.

Example Program: Consider an example program that demonstrates the usage of


packages:

package com.mycompany.mypackage;

import com.mycompany.util.Utility;

Thopstech.com 74 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
class MyClass {
public static void main(String[] args) {
int result = Utility.add(5, 3);
System.out.println("Result: " + result);
}
}

Explanation: In this example, the MyClass belongs to the com.mycompany.mypackage


package. It imports the Utility class from the com.mycompany.util package. The Utility
class provides a static add method that is used in the main method of MyClass.

By using packages and importing classes, the program maintains a well-organized


structure, avoids naming conflicts, and enhances code readability.

In summary, packages in Java provide a way to organize and structure classes and
interfaces into different namespaces. They facilitate modularity, prevent naming
conflicts, and enhance code organization and maintenance. Using packages improves
code reusability and readability in Java applications.

Access Modifiers:
Access modifiers in Java are keywords that define the accessibility or visibility of
classes, methods, variables, and constructors within a Java program. They control the
level of access that other parts of the program have to these entities. Java provides
four access modifiers: public, protected, private, and the default (no modifier). Let's
explore each access modifier in detail:

1. Public: The public access modifier allows unrestricted access to a class, method,
variable, or constructor. It provides the highest level of visibility, allowing other
classes from any package to access the public entity.

Example:

Thopstech.com 75 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
Explanation: In this example, the MyClass is declared with the public access modifier.
The publicMethod() is also declared with the public access modifier, allowing other
classes to access and invoke this method from any package.

2. Protected: The protected access modifier allows access within the same package
and in subclasses, even if they belong to a different package. It provides more
accessibility than the default modifier but less accessibility than public.

Example:

Explanation: In this example, the MyClass is declared with the public access modifier.
The protectedMethod() is declared with the protected access modifier, allowing
classes within the same package and subclasses to access and invoke this method,
even if they belong to a different package.

3. Private: The private access modifier restricts access to only within the same class. It
provides the most restricted access, ensuring encapsulation and data hiding.

Example:

Thopstech.com 76 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
Explanation: In this example, the privateVariable and privateMethod() are declared
with the private access modifier. These entities can only be accessed within the same
class, and other classes cannot access or modify them directly.

4. Default (No Modifier): When no access modifier is specified, it is considered the


default access modifier. The default access allows access within the same package but
restricts access from outside the package.

Example:

Explanation: In this example, the MyClass is declared without any access modifier. The
defaultMethod() is also declared without any access modifier, making it accessible
within the same package but inaccessible from outside the package.

Access Modifiers Comparison:

Subclass Other Classes


Access Same Same (Different (Different
Modifier Class Package Package) Package)
public Yes Yes Yes Yes
protected Yes Yes Yes No
private Yes No No No
Default Yes Yes No No

The access modifiers apply to classes, methods, constructors, and variables (fields).
Class-level access modifiers (public and default) control the accessibility of the class
itself.
Method-level and variable-level access modifiers control the accessibility of methods
and variables within the class.
Constructors can have access modifiers to control their accessibility.

Using access modifiers appropriately is crucial for encapsulation, information hiding,


and ensuring the integrity of the program. It allows you to control the visibility and
accessibility of entities, helping to maintain code organization, security, and
maintainability.

Thopstech.com 77 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
Encapsulation:
Encapsulation in Java is a principle of object-oriented programming that combines
data and methods (behaviors) into a single unit called a class. It promotes the idea of
hiding the internal details of an object and providing access to its properties and
functionalities through well-defined interfaces. Encapsulation ensures data integrity,
improves code maintainability, and enhances code reusability. Let's explore
encapsulation in detail, along with an example program and a real-world application:

Encapsulation Definition: Encapsulation is the process of wrapping data (variables)


and methods into a single unit called a class. It restricts direct access to the internal
data of an object and provides controlled access through methods. Encapsulation
helps in achieving data hiding, abstraction, and information security.

Example Program:

class BankAccount {
private double balance;

public void deposit(double amount) {


// Perform validation and update balance
balance += amount;
}

public void withdraw(double amount) {


// Perform validation and update balance
if (amount <= balance) {
balance -= amount;
} else {
System.out.println("Insufficient balance");
}
}

public double getBalance() {


return balance;
}
}

public class EncapsulationExample {


public static void main(String[] args) {
BankAccount account = new BankAccount();
account.deposit(1000);
account.withdraw(500);
System.out.println("Account balance: " + account.getBalance());
}
}

Thopstech.com 78 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
Explanation: In this example, the BankAccount class encapsulates the balance variable
as private, preventing direct access to it from outside the class. The deposit and
withdraw methods provide controlled access to update the balance variable by
performing necessary validations. The getBalance method allows read-only access to
retrieve the value of the balance variable. The main method demonstrates the usage
of the BankAccount class by creating an object, depositing and withdrawing amounts,
and retrieving the balance.

Benefits of Encapsulation:

Data Hiding: Encapsulation hides the internal data and implementation details of an
object, preventing direct access and manipulation. It promotes information hiding,
reducing the risk of data corruption or unauthorized access.

Access Control: Encapsulation allows fine-grained control over access to the data and
methods of an object. By using access modifiers like private, public, protected, and
the default modifier, you can restrict or grant access as needed.

Code Maintainability: Encapsulation improves code maintainability by localizing the


impact of changes. As the internal implementation details are hidden, modifications
can be made to the class without affecting other parts of the program that use the
class.

Code Reusability: Encapsulation promotes code reusability by encapsulating common


functionalities into reusable classes. These classes can be used in different parts of
the program without duplicating code.

Abstraction: Encapsulation helps in achieving abstraction by exposing only the


essential methods and hiding the internal complexities. Users of the class only need
to know how to interact with the exposed methods, abstracting away the
implementation details.

Fully Encapsulated Class: A fully encapsulated class is a class in which all the data
members (variables) are declared as private and access to them is provided only
through public methods.
class Person {
private String name;
private int age;

public void setName(String name) {


// Perform validation and update name
this.name = name;
}

public void setAge(int age) {


// Perform validation and update age
this.age = age;

Thopstech.com 79 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
}

public String getName() {


return name;
}

public int getAge() {


return age;
}
}

public class FullyEncapsulatedClassExample {


public static void main(String[] args) {
Person person = new Person();
person.setName("John");
person.setAge(25);
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}

Explanation: In this example, the Person class is fully encapsulated. The name and age
variables are declared as private, ensuring direct access is restricted. The public setter
methods setName and setAge provide controlled access to update the private
variables by performing necessary validations. The public getter methods getName
and getAge allow read-only access to retrieve the values of the private variables.

Real-World Example: A real-world example of encapsulation can be found in a car


object. The internal details of the car, such as the engine, fuel tank, and braking
system, are encapsulated within the car class. The car class provides public methods
like start, accelerate, brake, and refuel to interact with the car's functionalities. Users
of the car object don't need to know the inner workings or complexities of these
systems, as they interact with the car through the public methods provided by
encapsulation.

Encapsulation is a fundamental principle of object-oriented programming that


promotes data integrity, code maintainability, and code reusability. It provides a way
to control access to the internal state of an object and present a well-defined
interface for interaction. By encapsulating data and methods within a class, Java
programs become more robust, secure, and modular.

In encapsulation, important terms include setters and getters, which are methods
used to provide controlled access to private variables (data members) of a class. They
are also known as accessor and mutator methods, respectively. Let's dive into the
explanation of setters and getters in encapsulation:

Thopstech.com 80 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
Setters (Mutator Methods): Setters are methods used to set the value of a private
variable. They provide a controlled way to update the state of an object by
performing necessary validations or transformations.

Syntax of a Setter:

public void setVariableName(DataType variableName) {


// Perform validations or transformations
this.variableName = variableName;
}

Explanation:

public: The access modifier determines the visibility of the setter method.
void: The setter does not return any value.
setVariableName: The name of the setter method, usually following the naming
convention of "set" followed by the name of the variable it sets.
DataType: The data type of the variable being set.
variableName: The name of the private variable.

Example:

public class Person {


private String name;

public void setName(String name) {


// Perform validation
if (name != null && !name.isEmpty()) {
this.name = name;
}
}
}

In this example, the setName setter method allows updating the private name
variable of the Person class. It performs a validation check to ensure that the name
being set is not null or empty before assigning it to the private variable.

Getters (Accessor Methods): Getters are methods used to retrieve the value of a
private variable. They provide controlled access to the state of an object without
directly exposing the private variable.

Syntax of a Getter:

public DataType getVariableName() {


// Perform additional logic if needed
return variableName;

Thopstech.com 81 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
}

Explanation:

public: The access modifier determines the visibility of the getter method.
DataType: The data type of the variable being retrieved.
getVariableName: The name of the getter method, usually following the naming
convention of "get" followed by the name of the variable it gets.
variableName: The name of the private variable.

Example:

public class Person {


private String name;

public String getName() {


return name;
}
}

In this example, the getName getter method allows retrieving the value of the private
name variable of the Person class. It simply returns the value of the private variable
without any additional logic.

By using setters and getters, encapsulation provides controlled access to private


variables, ensuring data integrity and allowing validation or transformation logic to be
applied. It encapsulates the internal state of an object and provides a well-defined
interface for interacting with the object's properties. Setters and getters are essential
in encapsulation to maintain the principle of information hiding and to achieve secure
and maintainable code.

Abstraction:
In general, abstraction refers to the process of simplifying complex systems by
focusing on the essential aspects and hiding unnecessary details. It allows us to
represent real-world entities and concepts in a simplified and generalized manner.
Abstraction helps in managing complexity, improving modularity, and facilitating code
maintenance. In the context of Java, abstraction is a fundamental concept of object-
oriented programming. It involves creating abstract classes and interfaces to define
common behaviors and properties that can be inherited by subclasses. Let's explore
the meaning of abstraction in Java in detail:

Abstraction in Java: In Java, abstraction is a mechanism that allows you to define


abstract classes and interfaces. Abstract classes cannot be instantiated and serve as
blueprints for subclasses. They may contain both abstract and non-abstract methods.
Abstract methods are declared without implementation and must be implemented by

Thopstech.com 82 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
the subclasses. Interfaces, on the other hand, define a contract of behaviors that a
class must adhere to. They can contain only abstract methods and constants.

Syntax for Abstract Class:

Explanation:

 The abstract keyword is used to declare an abstract class.


 Abstract methods are declared without a body and are followed by a semicolon.
They must be implemented by the subclasses.
 Non-abstract methods can also be present in an abstract class. They have a
method body and can be used directly by the class or overridden by the
subclasses.

Syntax for Interface:

Thopstech.com 83 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
Explanation:

 The interface keyword is used to declare an interface.


 Abstract methods in interfaces are implicitly public and abstract. They do not
have a method body and must be implemented by classes that implement the
interface.
 Interfaces can also define constants, which are implicitly public, static, and final.

Example Program:

abstract class Shape {


public abstract void draw();
}

class Circle extends Shape {


@Override
public void draw() {
System.out.println("Drawing a circle");
}
}

class Rectangle extends Shape {


@Override
public void draw() {
System.out.println("Drawing a rectangle");
}
}

public class AbstractionExample {


public static void main(String[] args) {
Shape circle = new Circle();
Shape rectangle = new Rectangle();

circle.draw(); // Output: Drawing a circle


rectangle.draw(); // Output: Drawing a rectangle
}
}

Explanation: In this example, the Shape class is an abstract class that declares an
abstract method draw(). The Circle and Rectangle classes extend the Shape class and
provide the implementation for the draw() method. The main method demonstrates
the abstraction by creating objects of the Circle and Rectangle classes and invoking
the draw() method on them. The specific implementation of the draw() method is
determined by the actual class being instantiated.

Thopstech.com 84 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
Real-World Examples:

Database Connectivity: When interacting with a database, you use an abstract class or
an interface to define common database operations like connecting, querying, and
updating data. Different database providers can implement these interfaces or extend
the abstract class with their specific implementation.

Remote Control: In a television remote control, the buttons provide an abstraction of


the underlying functions such as power on/off, volume control, and channel selection.
Users don't need to know the internal circuitry details; they interact with the remote
control using the provided abstraction.

Abstraction in Java enables the creation of generalized types and behaviors, allowing
code to be written in a more modular and extensible manner. It helps in managing
complexity, promoting code reuse, and facilitating the implementation of complex
systems. By abstracting away unnecessary details, Java programs become more
flexible and maintainable.

String:
The String class in Java is used to represent a sequence of characters. It is one of the
most commonly used classes in Java and provides various methods for manipulating
and working with strings. Here's an explanation of the String class, along with
syntaxes, definitions, sample programs, and examples of string methods:

Definition and Syntax: The String class represents an immutable sequence of


characters in Java. It is part of the java.lang package and does not require an import
statement. Here's the syntax for declaring a String variable:

String variableName;

Example:
String name = "John";

In this example, the name variable is declared as a String and assigned the value
"John".

String Methods and Examples: The String class provides various methods for
performing operations on strings. Here are some commonly used methods and their
explanations:

length() - Returns the length of the string.

Example:

String str = "Hello, World!";

Thopstech.com 85 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
int length = str.length(); // length = 13

charAt(int index) - Returns the character at the specified index in the string.

Example:

String str = "Hello";


char ch = str.charAt(1); // ch = 'e'

concat(String str) - Concatenates the specified string at the end of the current string.

Example:

String str1 = "Hello";


String str2 = "World";
String result = str1.concat(str2); // result = "HelloWorld"

substring(int beginIndex) - Returns a substring from the specified index to the end of the
string.

Example:

String str = "Hello, World!";


String substr = str.substring(7); // substr = "World!"

substring(int beginIndex, int endIndex) - Returns a substring from the specified begin
index (inclusive) to the specified end index (exclusive).

Example:

String str = "Hello, World!";


String substr = str.substring(7, 12); // substr = "World"

toUpperCase() - Converts the string to uppercase.

Example:

String str = "hello";


String uppercase = str.toUpperCase(); // uppercase = "HELLO"

toLowerCase() - Converts the string to lowercase.

Example:

String str = "HELLO";


String lowercase = str.toLowerCase(); // lowercase = "hello"

trim() - Removes leading and trailing whitespace from the string.

Thopstech.com 86 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
Example:

String str = " Hello ";


String trimmed = str.trim(); // trimmed = "Hello"

equals(Object obj) - Checks if the string is equal to the specified object.

Example:

String str1 = "Hello";


String str2 = "Hello";
boolean isEqual = str1.equals(str2); // isEqual = true

startsWith(String prefix) - Checks if the string starts with the specified prefix.

Example:

String str = "Hello, World!";


boolean startsWithHello = str.startsWith("Hello"); // startsWithHello = true

These are just a few examples of the methods provided by the String class. The class
offers many more methods for string manipulation, searching, replacing, and more.

Additional Note: Since strings are immutable in Java, any modification to a string
creates a new string object. Therefore, it is advisable to use the StringBuilder or
StringBuffer classes for more efficient string manipulation when extensive
modifications are required.

The String class in Java provides a wide range of methods for working with strings. It
simplifies string manipulation and makes it easier to perform common string
operations. Understanding and utilizing these methods effectively can greatly
enhance your ability to work with strings in Java programs.

Inner class:
In Java, an inner class is a class defined within another class. It allows you to logically
group classes that are only used in one place and provides a way to achieve better
encapsulation and organization of code. Inner classes have access to the members
(including private members) of the enclosing class. Let's explore inner classes in Java,
including syntax, example programs, and explanations:

Syntax for Inner Class:

class OuterClass {
// Outer class members and methods

class InnerClass {

Thopstech.com 87 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
// Inner class members and methods
}
}

Explanation:

 The OuterClass is the enclosing or outer class that contains the inner class.
 The InnerClass is the inner class defined within the outer class.
 The inner class has access to the members and methods of the outer class.

Example Program:

class Outer {
private int outerVariable = 10;

void outerMethod() {
System.out.println("Outer Method");

// Creating an instance of Inner class


Inner inner = new Inner();
inner.innerMethod();
}

class Inner {
private int innerVariable = 20;

void innerMethod() {
System.out.println("Inner Method");
System.out.println("Accessing outerVariable: " + outerVariable);
System.out.println("Accessing innerVariable: " + innerVariable);
}
}
}

public class InnerClassExample {


public static void main(String[] args) {
Outer outer = new Outer();
outer.outerMethod();
}
}

Explanation: In this example, the Outer class defines an inner class called Inner. The
Outer class has a private variable outerVariable and a method outerMethod(). The
Inner class has a private variable innerVariable and a method innerMethod(). The
innerMethod() accesses both the outerVariable and innerVariable. The main() method

Thopstech.com 88 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
creates an instance of the Outer class and invokes the outerMethod(), which in turn
creates an instance of the Inner class and invokes the innerMethod().

The output of the above example will be:

Outer Method
Inner Method
Accessing outerVariable: 10
Accessing innerVariable: 20

Types of Inner Classes:

Member Inner Class: It is a non-static inner class defined at the member level of the
outer class. It has access to the members of the outer class.

Local Inner Class: It is an inner class defined within a method or a code block. It has
access to the final variables and effectively final variables of the method or code
block.

Anonymous Inner Class: It is an inner class without a name. It is declared and


instantiated at the same time and is used when you need to override a method or
define a class without explicitly creating a separate class file.

Static Nested Class: It is a static class defined within the outer class. It does not have
access to the instance variables and methods of the outer class, but can access the
static members of the outer class.

Example Program: Member Inner Class:

class Outer {
private int outerVariable = 10;

void outerMethod() {
System.out.println("Outer Method");

class Inner {
private int innerVariable = 20;

void innerMethod() {
System.out.println("Inner Method");
System.out.println("Accessing outerVariable: " + outerVariable);
System.out.println("Accessing innerVariable: " + innerVariable);
}
}

Inner inner = new Inner();

Thopstech.com 89 +91-7989764438 +91-7989751956


CORE JAVA - sriRAM
inner.innerMethod();
}
}

public class MemberInnerClassExample {


public static void main(String[] args) {
Outer outer = new Outer();
outer.outerMethod();
}
}

Explanation: In this example, the Outer class defines a member inner class called
Inner within the outerMethod(). The innerMethod() of the Inner class accesses both
the outerVariable and innerVariable. The main() method creates an instance of the
Outer class and invokes the outerMethod(), which creates an instance of the Inner
class and invokes the innerMethod().

The output of the above example will be the same as the previous example:

Outer Method
Inner Method
Accessing outerVariable: 10
Accessing innerVariable: 20

Inner classes provide a way to logically group related classes and enhance code
organization and encapsulation. They are particularly useful when a class is used only
in one place or closely related to the enclosing class. Inner classes have access to the
members of the enclosing class, allowing for more convenient and readable code.

Thopstech.com 90 +91-7989764438 +91-7989751956

You might also like