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

java unit 1

This document provides an introduction to Java, including its definition as a high-level, object-oriented programming language, its applications, and its history. It covers Java's data types, variables, and constants, detailing primitive and non-primitive types, variable scopes, and how to declare and initialize variables. Additionally, it explains the use of comments and enumerations in Java programming.

Uploaded by

sakethvemula2328
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

java unit 1

This document provides an introduction to Java, including its definition as a high-level, object-oriented programming language, its applications, and its history. It covers Java's data types, variables, and constants, detailing primitive and non-primitive types, variable scopes, and how to declare and initialize variables. Additionally, it explains the use of comments and enumerations in Java programming.

Uploaded by

sakethvemula2328
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 71

UNIT –I

I. INTRODUCTION TO JAVA
What is Java
Java is a high Level programming language and it is also called as
a platform. Java is a secured and robust high level object-oriented
programming language.
Platform: Any software or hardware environment in which a
program runs is known as a platform. Java has its own runtime
environment (JRE) and API so java is also called as platform.
Java fallows the concept of Write Once, Run Anywhere.
Application of java
1. Desktop Applications
2. Web Applications
3. Mobile
4. Enterprise Applications
5. Smart Card
6. Embedded System
7. Games
8. Robotics etc

History of Java
The history of Java starts with the Green Team. Java team members (also
known as Green Team), initiated this project to develop a language for digital
devices such as set-top boxes, televisions, etc. However, it was best suited
for internet programming. Later, Java technology was incorporated by
Netscape.

The principles for creating Java programming were "Simple, Robust, Portable,
Platform-independent, Secured, High Performance, Multithreaded,
Architecture Neutral, Object-Oriented, Interpreted, and Dynamic". Java was
developed by James Gosling, who is known as the father of Java, in 1995.
James Gosling and his team members started the project in the early '90s.
Currently, Java is used in internet programming, mobile devices,
games, e-business solutions, etc. Following are given significant
points that describe the history of Java.

1) James Gosling, Mike Sheridan, and Patrick


Naughton initiated the Java language project in June 1991.
The small team of sun engineers called Green Team.

2) Initially it was designed for small, embedded systems in


electronic appliances like set-top boxes.

3) Firstly, it was called "Greentalk" by James Gosling, and the


file extension was .gt.

4) After that, it was called Oak and was developed as a part of


the Green project.

5) Why Oak? Oak is a symbol of strength and chosen as a


national tree of many countries like the U.S.A., France,
Germany, Romania, etc.
6) In 1995, Oak was renamed as "Java" because it was already
a trademark by Oak Technologies.

Why Java Programming named "Java"?


According to James Gosling, "Java was one of the top choices
along with Silk". Since Java was so unique, most of the team
members preferred Java than other names.
9) Notice that Java is just a name, not an acronym.

10) Initially developed by James Gosling at Sun


Microsystems (which is now a subsidiary of Oracle Corporation)
and released in 1995.

11) In 1995, Time magazine called Java one of the Ten Best
Products of 1995.

Java Comments
The java comments are statements that are not executed by the
compiler and interpreter. The comments can be used to provide
information or explanation about the variable, method, class or
any statement. It can also be used to hide program code for
specific time.
Types of Java Comments
There are 3 types of comments in java.
1. Single Line Comment
2. Multi Line Comment
3. Documentation Comment

1) Java Single Line Comment


The single line comment is used to comment only one line.
Syntax:
1. //This is single line comment
Example:
1. public class Sample{
2. public static void main(String[] args) {
3. int j=10;//Here, i is a variable
4. System.out.println(j);
5. }
6. }

2) Java Multi Line Comment


The multi line comment is used to comment multiple lines of
code.
Syntax:
1. /*
2. This
3. is
4. multi line
5. comment
6. */

Example:
1. public class CommentExample2 {
2. public static void main(String[] args) {
3. /* Let's declare and
4. print variable in java. */
5. int j=10;
6. System.out.println(j);
7. }
8. }

3) Java Documentation Comment


The documentation comment is used to create documentation
API. To create documentation API, you need to use javadoc tool.
Syntax:
1. /**
2. This
3. is
4. documentation
5. comment
6. */
DATA TYPES
There are two data types available in Java −
 Primitive Data Types
 Non Primitive Types

Primitive Data Types


There are eight primitive data types supported by Java. Primitive
data types are predefined by the language and named by a
keyword. Let us now look into the eight primitive data types in
detail.
byte
 Byte data type is an 8-bit signed two's complement integer
 Minimum value is -128
 Maximum value is 127
 Default value is 0
 Byte data type is used to save space in large arrays, mainly
in place of integers, since a byte is four times smaller than
an integer.
 Example: byte a = 100, byte b = -50

short
 Short data type is a 16-bit signed two's complement integer
 Minimum value is -32,768
 Maximum value is 32,767
 Short data type can also be used to save memory as byte
data type. A short is 2 times smaller than an integer
 Default value is 0.
 Example: short s = 10000, short r = -20000
int
 Int data type is a 32-bit signed two's complement integer.
 Minimum value is - 2,147,483,648
 Maximum value is 2,147,483,647
 Integer is generally used as the default data type for integral
values unless there is a concern about memory.
 The default value is 0
 Example: int a = 100000, int b = -200000
long
 Long data type is a 64-bit signed two's complement integer
 Minimum value is -9,223,372,036,854,775,808
 Maximum value is 9,223,372,036,854,775,807
 This type is used when a wider range than int is needed
 Default value is 0L
 Example: long a = 100000L, long b = -200000L

float
 Float data type is a single-precision 32-bit IEEE 754 floating
point
 Float is mainly used to save memory in large arrays of
floating point numbers
 Default value is 0.0f
 Float data type is never used for precise values such as
currency
 Example: float f1 = 234.5f

double
 double data type is a double-precision 64-bit IEEE 754
floating point
 This data type is generally used as the default data type for
decimal values, generally the default choice
 Double data type should never be used for precise values
such as currency
 Default value is 0.0d
 Example: double d1 = 123.4

boolean
 boolean data type represents one bit of information
 There are only two possible values: true and false
 This data type is used for simple flags that track true/false
conditions
 Default value is false
 Example: boolean one = true
char
 char data type is a single 16-bit Unicode character
 Minimum value is '\u0000' (or 0)
 Maximum value is '\uffff' (or 65,535 inclusive)
 Char data type is used to store any character
 Example: char letterA = 'A'

DataType DefaultValue Defaultsize

boolean False 1bit

char '\u0000' 2byte

byte 0 1byte

short 0 2byte

int 0 4byte

long 0L 8byte

float 0.0f 4byte

double 0.0d 8byte

Java Variables
A variable is a container which holds the value while the Java
program is executed. A variable is assigned with a data type.

Variable is a name of memory location.

Every variable has a:


 Data Type – The kind of data that it can hold. For example,
int, string, float, char, etc.
 Variable Name – To identify the variable uniquely within the
scope.
 Value – The data assigned to the variable.
Types of Variables
There are three types of variables in Java:

o local variable
o instance variable
o static variable
o Example:
o int age = 27; // integer
variable having value 27

String name = "gfg" // string variable

How to Declare Java Variables?


We can declare variables in Java as pictorially depicted below:

DataType Name;
Int count;
From the image, it can be easily perceived that while
declaring a variable, we need to take care of two things that are:
1. datatype: Type of data that can be stored in this variable.
2. data_name: Name was given to the variable.
In this way, a name can only be given to a memory location. It
can be assigned values in two ways:
 Variable Initialization
 Assigning value by taking input

How to Initialize Java Variables?


It can be perceived with the help of 3 components explained above:

Int age=20; reserve memory for variable


Data type variable name value
Example:
// Declaring float variable
float simpleInterest;

// Declaring and initializing integer variable


int time = 10, speed = 20;

// Declaring and initializing character variable


char var = 'h';
Variables are the basic units of storage in Java.

The Scope of Variables in Java


Variables are an essential part of data storage and manipulation in the
realm of programming. In addition to making values available within a

There are four scopes for variables in Java:

1) local,
2) instance,
3) Static variable and

1) Local Variable
You can use this variable only within that method and the other
methods in the class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

Example of Local Variable

public class Test


{
void method1()
{
// Local variable (Method level scope)
int x;
}
}
Example:

1. public SumExample
2. {
3. public void calculateSum() {
4. int a = 5; // local variable
5. int b = 10; // local variable
6. int sum = a + b;
7. System.out.println("The sum is: " + sum);
8. } // a, b, and sum go out of scope here
9. }
Output:

The sum is: 15

2) Instance Variable
A variable declared inside the class but outside the body of the
method, is called an instance variable. It is not declared as static.

It is called an instance variable because its value is instance-


specific and is not shared among instances.

3)Static Variables:
A variable that is declared as static is called a static variable. It
cannot be local. You can create a single copy of the static variable
and share it among all the instances of the class.

Memory allocation for static variables happens only once when


the class is loaded in the memory

class Employee {
// Static variable
static int companyCode = 12345;

// Instance variables
String name;
int id;

// Constructor
Employee(String name, int id) {
this.name = name;
this.id = id;
}

// Method to display employee details


void displayDetails() {
System.out.println("Employee ID: " + id);
System.out.println("Employee Name: " + name);
System.out.println("Company Code: " + companyCode);
}
}

public class StaticVariableExample {


public static void main(String[] args) {
// Create objects of Employee
Employee emp1 = new Employee("Alice", 101);
Employee emp2 = new Employee("Bob", 102);

// Display details of employees


emp1.displayDetails();
emp2.displayDetails();

// Change the static variable value


Employee.companyCode = 67890;

System.out.println("\nAfter changing the company code:\n");

// Display details again to see the effect of the change


emp1.displayDetails();
emp2.displayDetails();
}
}
Output:
Employee ID: 101
Employee Name: Alice
Company Code: 12345

Employee ID: 102


Employee Name: Bob
Company Code: 12345

After changing the company code:

Employee ID: 101


Employee Name: Alice
Company Code: 67890

Employee ID: 102


Employee Name: Bob
Company Code: 67890

Constants
In Java, a constant is a variable whose value cannot be changed
once it has been initialized. Constants are typically declared using
the final keyword. They are often combined with static to ensure
there is only one copy shared across all instances of a class.

How to declare constant in Java?


1. Use the final keyword.
2. Optionally, use static for class-level constants.
3. By convention, constant names are written in uppercase
letters with underscores _ separating words.
Static and Final Modifiers
o The purpose to use the static modifier is to manage the
memory.
o It also allows the variable to be available without loading any
instance of the class in which it is defined.
o The final modifier represents that the value of the variable
cannot be changed. It also makes the primitive data type
immutable or unchangeable.
The syntax to declare a constant is as follows:

1. static final datatype identifier_name=value;


For example, price is a variable that we want to make constant.

1. static final double PRICE=432.78;


Where static and final are the non-access modifiers. The double is
the data type and PRICE is the identifier name in which the value
432.78 is assigned.

When we use static and final modifiers together, the variable


remains static and can be initialized once. Therefore, to declare a
variable as constant, we use both static and final modifiers. It
shares a common memory location for all objects of its containing
class.

Let's see some examples in which we have used constants.

class ConstantsExample {
// Defining constants
static final double PI = 3.14159; // Static constant
final int MAX_VALUE = 100; // Instance-level constant

public static void main(String[] args) {


// Accessing a static constant
System.out.println("Value of PI: " + PI);

// Creating an instance to access the instance-level constant


ConstantsExample example = new ConstantsExample();
System.out.println("Max Value: " + example.MAX_VALUE);
// Uncommenting the following lines will cause an error
because constants cannot be modified
// PI = 3.14;
// example.MAX_VALUE = 200;
}
}

Output:
yaml
Copy code
Value of PI: 3.14159
Max Value: 100

Key Points About Constants:

1. final: Ensures the variable's value cannot be changed once


initialized.
2. static: Allows the constant to belong to the class rather than
an instance, meaning it is shared across all objects.
3. Naming Convention: Use uppercase letters with
underscores (e.g., MAX_SPEED, DEFAULT_TIMEOUT).
4. Initialization: Constants must be initialized when declared
or in a constructor (for instance constants).

`Using Enumeration (enum) as Constant


o It is the same as the final variables.
o It is a list of constants.
o Java provides the enum keyword to define the enumeration.
o It defines a class type by making enumeration in the class that
may contain instance variables, methods, and constructors.

Example of Enumeration
1. public class EnumExample
2. {
3. //defining the enum
4. public enum Color {Red, Green, Blue, Purple, Black, White, Pink,
Gray}
5. public static void main(String[] args)
6. {
7. //traversing the enum
8. for (Color c : Color.values())
9. System.out.println(c);
10. }
11. }
Output:

Explanation

The Java program EnumExample defines a class with a nested


enum named Color. The predefined colors Red, Green, Blue,
Purple, Black, White, Pink, and Grey are represented by this
enum.

The values() function is used in the main() method's for-each loop


to iterate over the Colour enum's values and print each color to
the console. It shows how to use an extended for loop to iterate
over the elements of an enum and how to use enums in Java to
express a fixed collection of constants
Operators in Java
Operator in Java is a symbol that is used to perform operations.
For example: +, -, *, / etc.

There are many types of operators in Java which are given below:

o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.

OperatorType Category Precedence

postfix expr++expr--
Unary
prefix ++expr--expr+expr-expr~!

multiplicative */%
Arithmetic
additive + -

Shift shift <<>>>>>

comparison <><=>= instanceof


Relational
equality ==!=

bitwiseAND &

Bitwise bitwiseexclusiveOR ^

bitwiseinclusiveOR |

logicalAND &&
Logical
logicalOR ||

Ternary ternary ? :
=+=-=*=/=%=&=^=|=<<=>>=
Assignment assignment
>>>=

Hierachy Expressions
In Java, the order in which expressions are evaluated is
determined by operator precedence. This hierarchy dictates
which operations are performed first when an expression contains
multiple operators.
Here's a breakdown of the hierarchy:
Highest Precedence (Evaluated First)
 Parentheses: ()
 Member Access: ., []
 Unary Operators: ++, --, +, -, !, ~ (pre-increment, pre-
decrement, unary plus, unary minus, logical NOT, bitwise NOT)
 Multiplicative Operators: *, /, % (multiplication, division,
modulus)
 Additive Operators: +, - (addition, subtraction)
 Shift Operators: <<, >>, >>> (left shift, signed right shift,
unsigned right shift)
 Relational Operators: <, >, <=, >=, instanceof (less than,
greater than, less than or equal to, greater than or equal to,
instance of)
 Equality Operators: ==, != (equal to, not equal to)
 Bitwise AND: &
 Bitwise XOR: ^
 Bitwise OR: |
 Logical AND: &&
 Logical OR: ||
 Ternary Operator: ?:
 Assignment Operators: =, +=, -=, *=, /=, %=, &=, |=, ^= etc.
(assignment, addition assignment, subtraction assignment,
multiplication assignment, etc.)
Lowest Precedence (Evaluated Last)
Example:
Java
int x = 2;
int y = 3;
int z = 4;

int result = x + y * z; // result = 14 (multiplication is performed


before addition)
Using Parentheses to Control Evaluation Order
 You can use parentheses to override the default precedence and
force specific operations to be performed first.
Java
int result = (x + y) * z; // result = 20 (addition is performed before
multiplication)

Type Conversion And Type Casting In Java


What is Type Conversion?
Type conversion is a process in which the data type is
automatically converted into another data type. The compiler does
this automatic conversion at compile time. The data type to which
the conversion happens is called the destination data type, and the
data type from which the conversion happens is called the source
data type. If the source and destination data types are compatible,
then automatic type conversion takes place.
For type conversion to take place, the destination data type must be
larger than the source type. In short, the below flow chart has to be
followed.
Flow chart for Type Conversion
This type of type conversion is also called Widening Type
Conversion/ Implicit Conversion/ Casting Down. In this case, as
the lower data types with smaller sizes are converted into higher
ones with a larger size, there is no chance of data loss. This makes
it safe for usage.

In type conversion, the source data type with a smaller size is


converted into the destination data type with a larger size.

Example for Type Conversion in Java:

public class ImplicitConversion {


public static void main(String[] args) {
int num = 100; // Integer (4 bytes)
double doubleNum = num; // Automatically converted to
double (8 bytes)

System.out.println("Integer value: " + num);


System.out.println("Double value: " + doubleNum);
}
}
Output:
Integer value: 100
Double value: 100.0
What is Type Casting?
Type casting is a process in which the programmer manually
converts one data type into another data type. For this the casting
operator (), the parenthesis is used. Unlike type conversion, the
source data type must be larger than the destination type in type
casting. The below flow chart has to be followed for successful type
casting.

Flow chart for Type Casting

Type casting is also called Narrowing Type Casting/ Explicit


Conversion/ Casting Up. In this case, as the higher data types
with a larger size are converted into lower ones with a smaller size,
there is a chance of data loss. This is the reason that this type of
conversion does not happen automatically.

In type casting, the source data type with a larger size is


converted into the destination data type with a smaller size.
In one of the examples covered in type conversion, you might
recollect we encountered an error while converting an int data type
to short. Now, we will see how to solve that error by using type
casting.
Example for Type Casting
public class ExplicitConversion {
public static void main(String[] args) {
double doubleNum = 123.45; // Double (8 bytes)
int num = (int) doubleNum; // Explicitly casting to int (4
bytes)

System.out.println("Double value: " + doubleNum);


System.out.println("Converted Integer value: " + num);
}
}
Output:
Double value: 123.45
Converted Integer value: 123
Key Points:

1. Implicit Conversion: Safe, automatic, no data loss (e.g., int


→ long).
2. Explicit Conversion: Requires casting, potential data loss
(e.g., double → int).
3. Wrapper Conversion: Enables easy conversion between
primitive and wrapper types.
4. String Conversion: Useful for parsing input or working with
data formats.

Difference Between Type Casting and Type Conversion


Parameter Type Casting Type Conversion

Type casting is a process


in which the programmer Type conversion is a process in which
Definition manually converts one the data type is automatically converted
data type into another data into another data type
type.

Explicitly done by the


Can be implicit or explicit, depending
Method programmer using casting
on the language and context.
operators.

Function calls, constructors, or other


Syntax (newType) variable
conversion methods.

Must be compatible data Can involve conversions between


Compatibility
types. incompatible data types.
The result may involve data loss or
Immediate change in the
Change rounding errors, depending on the
data type of the variable.
conversion m

Enumerated types
In Java, enumerated types (enums) are a special data type that
allows you to define a set of named constants. Here's how you
can use them:

enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY, SATURDAY
}

public class EnumExample {


public static void main(String[] args) {
Day today = Day.THURSDAY;

switch (today) {
case MONDAY:
System.out.println("It's Monday!");
break;
case THURSDAY:
System.out.println("It's Thursday!");
break;
default:
System.out.println("It's another
day.");
}
}
}

Explanation:
 enum keyword: This keyword is used to define an enum type.
 Day: This is the name of the enum type.
 SUNDAY, MONDAY, ...: These are the enum constants, which
are named values that represent the possible values of the enum
type.
 today: This variable is declared to be of type Day.
 switch statement: This statement is used to check the value of
the today variable and execute the corresponding code block.

Block Scope
A block of code refers to all of the code between curly braces {}.

Variables declared inside blocks of code are only accessible by


the code between the curly braces, which follows the line in which
the variable was declared:

Example
public class Main {
public static void main(String[] args) {

// Code here CANNOT use x

{ // This is a block

// Code here CANNOT use x

int x = 100;

// Code here CAN use x


System.out.println(x);

} // The block ends here

// Code here CANNOT use x

}
}
A block of code may exist on its own or it can belong to
an if, while or for statement. In the case of for statements,
variables declared in the statement itself are also available inside
the block's scope.

Java condition statements


Java has the following conditional statements:

 Use if to specify a block of code to be executed, if a specified


condition is true
 Use else to specify a block of code to be executed, if the
same condition is false
 Use else if to specify a new condition to test, if the first
condition is false
 Use switch to specify many alternative blocks of code to be
executed

IF Statement
 The Java if statement tests the condition. It executes the if
block if condition is true. The following is the
syntax
 1. if(condition){
 2. //code to be executed
 3. }
Example
1. public class Example {
 2. public static void main(String[] args) {
 3. int k=35;
 4. if(k>18){ System.out.print("Hello");
 5. } } }

IF-else Statement
 The if-else statement in java tests the condition. It executes
the if block if condition is true otherwise else block is
executed.
Syntax:
 1. if(condition){
 2. //code if condition is true
 3. }else{
 4. //code if condition is false
 5. }
Example
 public class Sample {
 public static void main(String[] args) {
 int n=23;
 if(number%2==0){
 System.out.println("even ");
 }else{
 System.out.println("odd ");
 }}
 }

IF-else-if ladder Statement


 The if-else-if ladder statement executes one condition from
multiple statements.
Syntax:
 1. if(condition1){
 2. //code to be executed if condition1 is true
 3. }else if(condition2){
 4. //code to be executed if condition2 is true
 5. }
 6. else if(condition3){
 7. //code to be executed if condition3 is true
 8. }
 9. ...
 10. else{
 11. //code to be executed if all the conditions are false
 12. }
Example
 1. public class Simple {
 2. public static void main(String[] args) {
 3. int marks=70;
 4.
5. if(marks<40){
6. System.out.println("FAIL");
7. }
8. else if(marks>=40 && marks<50){
9. System.out.println("D grade");
10. }
11. else if(marks>=50 && marks<60){
12. System.out.println("C grade");
13. }
14. else if(marks>=60 && marks<70){
15. System.out.println("B grade");
16. }
17. else if(marks>=70 && marks<80){
18. System.out.println("A grade");
19. }else if(marks>=80 && marks<100){
20. System.out.println("A+ grade");
21. }else{
22. System.out.println("Invalid!");
23. }
24. }
25. }
Switch Statement
The switch statement in java executes one statement from
multiple conditions. It is like if-else-if ladder statement.
Syntax:
1. switch(expression){
2. case value1:
3. //code to be executed;
4. break; //optional
5. case value2:
6. //code to be executed;
7. break; //optional
8. ......
9.
10. default:
11. code to be executed if all cases are not matched;
12. }

Example:
1. public class Sample {
2. public static void main(String[] args) {
3. int k=20;
4. switch(k){
5. case 10: System.out.println("10");break;
6. case 20: System.out.println("20");break;
7. case 30: System.out.println("30");break;
8. default:System.out.println("Not in 10, 20 or 30");
9. } }
10. }

Java For Loop


The Java for loop is used to iterate a part of the program several
times. If the number of iteration is fixed, it is recommended to use
for loop.
There are three types of for loop in java.
 Simple For Loop
 For-each or Enhanced For Loop
 Labeled For Loop
Java Simple For Loop
The simple for loop is same as C/C++. We can initialize variable,
check condition and increment/decrement value.
Syntax:
1. for(initialization;condition;incr/decr){
2. //code to be executed
3. }

Example:
1. public class Sample {
2. public static void main(String[] args) {
3. for(int i=1;i<=20;i++){
4. System.out.println(i);
5. }
6. }
7. }

Java While Loop


The Java while loop is used to iterate a part of the program
several times. If the number of iteration is not fixed, it is
recommended to use while loop.
Syntax:
1. while(condition){
2. //code to be executed
3. }
1. public class Sample {
2. public static void main(String[] args) {
3. int j=1;
4. while(j<=10){
5. System.out.println(j);
6. j++;
7. }
8. } }

Java do-while Loop


The Java do-while loop is used to iterate a part of the program
several times. If the number of iteration is not fixed and you must
have to execute the loop at least once, it is recommended to use
do-while loop.The Java do-while loop is executed at least once
because condition is checked after loop body.
Syntax: do{ /code to be executed
}while(condition);
public class Example {
public static void main(String[] args) {
int j=1;
do{ System.out.println(j);
j++;
}while(j<=10);
}}
Java Break Statement
The Java break is used to break loop or switch statement. It
breaks the current flow of the program at specified condition. In
case of inner loop, it breaks only inner loop.
Example:
1. public class Simple {
2. public static void main(String[] args) {
3. for(int i=1;i<=10;i++){
4. if(i==5){
5. break;
6. }
7. System.out.println(i);
8. }
9. }
10. }

Java Continue Statement


The Java continue statement is used to continue loop. It continues
the current flow of the program and skips the remaining code at
specified condition. In case of inner loop, it continues only inner
loop.
Example:
1. public class Sample {
2. public static void main(String[] args) {
3. for(int k=1;k<=10;k++){
4. if(k==5){
5. continue;
6. }
7. System.out.println(k);
8. }
9. }
10. }

Simple standalone program in java


• class Simple
• {
• public static void main(String args[])
• {
• System.out.println("Hello Java");
• }
• }
Save the above file as Simple.java.
To compile:
javac Simple.java
To execute:
java Simple
Output: Hello Java

Compilation Flow:
• When we compile Java program using javac tool, the Java
compiler converts the source code into byte code.
Parameters used in First Java Program:
• Let's see what is the meaning of class, public, static, void,
main, String[], System.out.println().
• class keyword is used to declare a class in Java.
public keyword is an access modifier that represents
visibility. It means it is visible to all.
• static is a keyword. If we declare any method as static, it is
known as the static method.
• The core advantage of the static method is that there is no
need to create an object to invoke the static method.
• The main() method is executed by the JVM, so it doesn't
require creating an object to invoke the main() method. So,
it saves memory.
• void is the return type of the method. It means it doesn't
return any value.
• main represents the starting point of the program.
• String[] args or String args[] is used for command line
argument.
• System.out.println() is used to print statement. Here,
System is a class, out is an object of the PrintStream class,
println() is a method of the PrintStream class.
• To write the simple program, you need to open notepad
by start menu -> All Programs -> Accessories ->
Notepad and write a simple program as we have shown
below:

Some of the Standalone programs in java

2) Addition of Two Numbers:

public class AddNumbers {


public static void main(String[] args) {
int num1 = 5, num2 = 10, sum;
sum = num1 + num2;
System.out.println(“Sum of ” + num1 + ” and ” + num2 + ” is: ” +
sum);
}
}
Output:
Sum of 5 and 10 is: 15
3) Find Maximum of Three Numbers:

public class MaxOfThreeNumbers {


public static void main(String[] args) {
int num1 = 10, num2 = 20, num3 = 15, max;
max = (num1 > num2) ? (num1 > num3 ? num1 : num3) : (num2 >
num3 ? num2 : num3);
System.out.println(“Maximum of ” + num1 + “, ” + num2 + “, and ” +
num3 + ” is: ” + max);
}
}
Output:
Maximum of 10, 20, and 15 is: 20
4) Check Even or Odd Number:

public class EvenOdd {


public static void main(String[] args) {
int num = 5;
if(num % 2 == 0)
System.out.println(num + ” is even.”);
else
System.out.println(num + ” is odd.”);
}
}
Output:
5 is odd.
5) Factorial of a Number:

public class Factorial {


public static void main(String[] args) {
int num = 5, factorial = 1;
for(int i = 1; i <= num; ++i) {
factorial *= i;
}
System.out.println(“Factorial of ” + num + ” is: ” + factorial);
}
}
Output:
Factorial of 5 is: 120

Arrays in Java
• Normally, an array is a collection of similar type of elements
which has contiguous memory location.
• Java array is an object which contains elements of a similar
data type.
• Additionally, The elements of an array are stored in a
contiguous memory location.
• It is a data structure where we store similar elements. We
can store only a fixed set of elements in a Java array.

• Arrays are used to store multiple values in a single


variable, instead of declaring separate variables for each
value.
• To declare an array, define the variable type with square
brackets:

• String[] cars;

• We have now declared a variable that holds an array of


strings. To insert values to it, you can place the values in a
comma-separated list, inside curly braces:

• String[] cars = {"Volvo", "BMW", "Ford",


"Mazda"};

• To create an array of integers, you could write:

• int[] myNum = {10, 20, 30, 40};

Access the Elements of an Array


• You can access an array element by referring to the index
number.
• This statement accesses the value of the first element in
cars:
• String[] cars = {"Volvo", "BMW", "Ford",
"Mazda"};

• System.out.println(cars[0]);

• // Outputs Volvo

Change an Array Element


• To change the value of a specific element, refer to the
index number:

Example
cars[0] = "Opel";

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
// Now outputs Opel instead of Volvo

Array Length
To find out how many elements an array has, use
the length property:

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
// Outputs 4
Advantages:
• Code Optimization: It makes the code optimized, we can
retrieve or sort the data efficiently.
• Random access: We can get any data located at an index
position.
Disadvantages:
Size Limit: We can store only the fixed size of elements in
the array. It doesn't grow its size at runtime. To solve this
problem, collection framework is used in

Types of Array in java:


There are two types of array.
• Single Dimensional Array
• Multidimensional Array
Single Dimensional Array in Java:
Syntax to Declare an Array in Java:
dataType[] arr; (or)
dataType arr[];
Instantiation of an Array in Java:
• arrayRefVar=new datatype[size];

Example of Single Dimensional Array:


• Let's see the simple example of java array, where we are
going to declare, instantiate, initialize and traverse an array.

//Java Program to illustrate how to declare, instantiate, initiali


ze and traverse the
• Java array.
• class SDArray
• {
• public static void main(String args[])
• {
• int a[]=new int[5];//declaration and instantiation
• a[0]=10;//initialization
• a[1]=20;
• a[2]=70;
• a[3]=40;
• a[4]=50;
• //traversing array
• for(int i=0;i<a.length;i++)
//length is the property of array
• System.out.println(a[i]);
• }
• }
• Output: 10 20 70 40 50

Declaration, Instantiation and Initialization of Java


Array:
• We can declare, instantiate and initialize the java array
together by:

int a[]={33,3,4,5};//declaration, instantiation and initializati


on
//Java Program to illustrate the use of declaration, instantiati
on and initialization of Java array in a single line
class TestArray
{
public static void main(String args[])
{
int a[]={33,3,4,5};//declaration, instantiation and initializati
on
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Output: 33 3 4 5
Multidimensional Array in Java:
• In such case, data is stored in row and column based index
(also known as matrix form).
Syntax to Declare Multidimensional Array in Java:
dataType[][] arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in Java:
int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in Java
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
//Java Program to illustrate the use of multidimensional array

class MDArray
{
public static void main(String args[])
{
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
Output:
123
245
445
Java Console
Console Input
For console input, Java provides multiple methods. The most common is using the
Scanner class from the java.util package.

a) Using Scanner

The Scanner class provides methods to read different types of input (e.g.,
nextInt(), nextDouble(), nextLine()).

Example:
java
Copy code
import java.util.Scanner;

public class ConsoleInput {


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

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


String name = scanner.nextLine(); // Reads a
line of text

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


int age = scanner.nextInt(); // Reads an
integer

System.out.printf("Hello, %s! You are %d years


old.%n", name, age);

scanner.close(); // Close the scanner to


prevent resource leaks
}
}
b) Reading Different Data Types

Data Method Example


Type

String input =
String nextLine()
scanner.nextLine();

Integer nextInt() int num = scanner.nextInt();

Float nextFloat() float num = scanner.nextFloat();

double num =
Double nextDouble()
scanner.nextDouble();

boolean flag =
Boolean nextBoolean()
scanner.nextBoolean();

Read as String and use char ch =


Character
charAt(0) scanner.nextLine().charAt(0);

c) Using BufferedReader (For More Advanced Input)

The BufferedReader class reads text from the console more efficiently but
requires explicit conversion for numeric input.

Example:
java
Copy code
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class BufferedReaderExample {


public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter your name: ");
String name = reader.readLine(); // Reads a line of text

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


int age = Integer.parseInt(reader.readLine()); // Converts
string to integer

System.out.printf("Hello, %s! You are %d years old.%n",


name, age);
}
}

Formatting output
In Java, you can format output using
the System.out.printf() method, which is similar to
the printf() function in C.
Here's how to use it:

Basic Formatting:

int age = 25;


String name = "John";

System.out.printf("My name is %s and I am %d years old.%n",


name, age);
Output:
My name is John and I am 25 years old.
Explanation:
 %s is a placeholder for a string value (name in this case).
 %d is a placeholder for a decimal integer value (age in this case).
 %n is a platform-independent newline character.

Common Format Specifiers:


 %s: String
 %d: Decimal integer
 %f: Floating-point number
 %c: Character
 %b: Boolean
 %x: Hexadecimal integer

Controlling Width and Precision:


double pi = 3.14159265;

System.out.printf("Pi to 2 decimal places: %.2f%n", pi);


Output:
Pi to 2 decimal places: 3.14

Explanation:
%.2f specifies that the floating-point number (pi) should be
formatted with 2 decimal places.

Constructors in java
• In Java, a constructor is a block of codes similar to the
method. It is called when an instance of the class is created.
At the time of calling constructor, memory for the object is
allocated in the memory.

• It is a special type of method which is used to initialize the


object.

• Every time an object is created using the new() keyword, at


least one constructor is called.

• It calls a default constructor if there is no constructor


available in the class. In such case, Java compiler provides a
default constructor by default.

• Note: It is called constructor because it constructs the values


at the time of object creation. It is not necessary to write a
constructor for a class. It is because java compiler creates a
default constructor if your class doesn't have any.

Rules for creating Java constructor:


There are two rules defined for the constructor.

• Constructor name must be the same as its class name

• A Constructor must have no explicit return type

Types of Java constructors:

There are two types of constructors in Java:

• Default constructor (no-arg constructor)

• Parameterized constructor

Java Default Constructor:


• A constructor is called "Default Constructor" when it doesn't
have any parameter.

• Syntax of default constructor:

<class_name>( )

What is the purpose of a default constructor?

• The default constructor is used to provide the default values


to the object like 0, null, etc., depending on the type

Example of default constructor:

• In this example, we are creating the no-arg constructor in


the Bike class. It will be invoked at the time of object
creation.

//Java Program to create and call a default constructor

class Bike1

Bike1() //creating a default constructor

System.out.println("Bike is created");

public static void main(String args[]) //main method

Bike1 b=new Bike1(); //calling a default constructor


}

Output: Bike is created

Rule: If there is no constructor in a class, compiler automatically


creates a default constructor.

Java Parameterized Constructor:

• A constructor which has a specific number of parameters is


called a parameterized constructor.

Why use the parameterized constructor?

• The parameterized constructor is used to provide different


values to distinct objects. However, you can provide the
same values also.

Example of parameterized constructor:

In this example, we have created the constructor of Student class


that have two parameters.

We can have any number of parameters in the constructor.

//Java Program to demonstrate the use of the parameterized const


ructor.

class Student2

int id;

String name;

//creating a parameterized constructor

Student2(int i,String n)
{

id = i;

name = n;

//method to display the values

void display()

System.out.println(id+" "+name);

public static void main(String args[])

//creating objects and passing values

Student2 s1 = new Student2(111,"Karan");

Student2 s2 = new Student2(222,"Aryan");

//calling method to display the values of object

s1.display();

s2.display();

Output:

111 Karan
222 Aryan

Methods
A method is a block of code which only runs when it is called.

You can pass data, known as parameters, into a method.

Methods are used to perform certain actions, and they are also
known as functions.

Why use methods? To reuse code: define the code once, and use
it many time

Create a Method
A method must be declared within a class. It is defined with the
name of the method, followed by parentheses (). Java provides
some pre-defined methods, such as System.out.println(),
but you can also create your own methods to perform certain
actions:

Example
Create a method inside Main:
public class Main {
static void myMethod() {
// code to be executed
}
}

Example Explained
 myMethod() is the name of the method
 static means that the method belongs to the Main class
and not an object of the Main class. You will learn more
about objects and how to access methods through objects
later in this tutorial.
 void means that this method does not have a return
value. You will learn more about return values later in this
chapter

Call a Method
To call a method in Java, write the method's name followed by
two parentheses () and a semicolon;

In the following example, myMethod() is used to print a text


(the action), when it is called:

Example
Inside main, call the myMethod() method:
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod();
}
}
// Outputs "I just got executed!"
Parameter Passing Techniques in Java with
Examples
Parameter passing in Java refers to the mechanism of transferring data
between methods or functions. Java supports two types of parameters
passing techniques.

1. Call-by-value.
2. Call-by-reference.

Types of Parameters:
1. Formal Parameter:
A variable and its corresponding data type are referred to as formal
parameters when they exist in the definition or prototype of a function or
method. As soon as the function or method is called and it serves as a
placeholder for an argument that will be supplied. The function or
method performs calculations or actions using the formal parameter.

Syntax:

1. returnType functionName(dataType parameterName)


2. {
3. // Function body
4. // Use the parameterName within the function
5. }
In the above syntax:

o returnType represents the return type of the function.


o functionName represents the name of the function.
o dataType represents the data type of the formal parameter.
o parameterName represents the name of the formal parameter.
2. Actual Parameter:
The value or expression that corresponds to a formal parameter and is
supplied to a function or method during a function or method call is
referred to as an actual parameter is also known as an argument. It
offers the real information or value that the method or function will work
with.

Syntax:

functionName(argument)

In the above syntax:

o functionName represents the name of the function or method.


o argument represents the actual value or expression being
passed as an argument to the function or method.

1. Call-by-Value:
In Call-by-value the copy of the value of the actual parameter is passed
to the formal parameter of the method. Any of the modifications made to
the formal parameter within the method do not affect the actual
parameter.

1. import java.util.*;
2. public class CallByValueExample
3. {
4. public static void main(String[] args)
5. {
6. int num = 10;
7. System.out.println("Before calling method:"+num);
8. modifyValue(num); // Calling the method and passing the value
of 'num'
9. System.out.println("After calling method:"+num);
10. }
11.
12. public static void modifyValue(int value) {
13.
14. // Modifying the formal parameter
15. value=20; // Assigning a new value to the formal paramet
er as value
16. System.out.println("Inside method:"+value);
17. }
18. }
Output:

Before calling method: 10


Inside method: 20
After calling method: 10
Complexity Analysis:

Time Complexity is O(1).

Space Complexity is O(1).

Call-by-Reference:
call by reference" is a method of passing arguments to functions or
methods where the memory address (or reference) of the variable is
passed rather than the value itself. This means that changes made to
the formal parameter within the function affect the actual parameter in
the calling environment.

In "call by reference," when a reference to a variable is passed, any


modifications made to the parameter inside the function are transmitted
back to the caller. This is because the formal parameter receives a
reference (or pointer) to the actual data.

CallByReferenceExample.java

1. import java.util.*;
2.
3. // Callee
4. class CallByReference
5. {
6. int a,b;
7.
8. // Constructor to assign values to the class variables
9. CallByReference(int x,int y)
10. {
11. a=x;
12. b=y;
13. }
14.
15. // Method to change the values of class variables
16. void changeValue(CallByReference obj)
17. {
18. obj.a+=10;
19. obj.b+=20;
20. }
21. }
22.
23. // Caller
24. public class CallByReferenceExample
25. {
26. public static void main(String[] args)
27. {
28. // Create an instance of CallByReference and assign values using the constructor
29. CallByReference object=new CallByReference(10, 20);
30.
31. System.out.println("Value of a: "+object.a +" & b: " +object.b);
32.
33. // Call the changeValue method and pass the object as an argument
34. object.changeValue(object);
35.
36. // Display the values after calling the method
37. System.out.println("Value of a:"+object.a+ " & b: "+object.b);
38. }
39. }
Output:

Value of a: 10 & b: 20
Value of a: 20 & b: 40
Complexity Analysis:

Time Complexity is O(1).

Space Complexity is O(1).

Static fields and Methods


The static keyword is used to construct methods that will exist
regardless of whether or not any instances of the class are
generated. Any method that uses the static keyword is referred
to as a static method.
Features of static method:
 A static method in Java is a method that is part of a class
rather than an instance of that class.
 Every instance of a class has access to the method.
 Static methods have access to class variables (static
variables) without using the class’s object (instance).
 Only static data may be accessed by a static method. It is
unable to access data that is not static (instance variables).
 In both static and non-static methods, static methods can be
accessed directly.

Syntax to declare the static method:

Access_modifier static void methodName()


{
// Method body.
}
The name of the class can be used to invoke or access static
methods.

Syntax to call a static method:

className.methodName();

static variable
If you declare any variable as static, it is known as a static
variable.
The static variable can be used to refer to the common
property of all objects (which is not unique for each object),
for example, the company name of employees, college name
of
students, etc.
The static variable gets memory only once in the class area
at the time of class loading.
Advantages of static variable
It makes your program memory efficient (i.e., it saves
memory).
static method
If you apply static keyword with any method, it is known as
static method.
 A static method belongs to the class rather than the
object of a class.
 A static method can be invoked without the need for
creating an instance of a class.
 A static method can access static data member and can
change the value of it.

class Student
{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change()
{
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n)
{
rollno = r;
name = n;
}
//method to display values
void display()
{
System.out.println(rollno+" "+name+" "+college);
}
}
//Test class to create and display the values of object
public class TestStaticMethod
{
public static void main(String args[])
{
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
Output:
111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
static block
 Is used to initialize the static data member.
 It is executed before the main method at the time of
classloading.
class A2
{
static
{
System.out.println("static block is invoked");
}
public static void main(String args[])
{
System.out.println("Hello main");
}

}
Output:
static block is invoked
Hello main
Access Controls
Modifiers
By now, you are quite familiar with the public keyword that
appears in almost all of our examples:

public class Main

The public keyword is an access modifier, meaning that it is


used to set the access level for classes, attributes, methods
and constructors.

We divide modifiers into two groups:

 Access Modifiers - controls the access level


 Non-Access Modifiers - do not control access level, but
provides other functionality

Access modifiers
Public The code is accessible for all classes
Private The code is only accessible within the declared
class
Default The code is only accessible in the same package.
This is used when you don't specify a modifier.
Protected The code is accessible in the same package
and subclasses.

Non Access modifiers


Final The class cannot be inherited by other
class
Abstract The class cannot be used to create
objects (to acess the abstract class it must be
inheritance from the abstract class)
this keyword
There can be a lot of usage of java this
keyword. In java, this is a reference variable
that
refers to the current object.

Usage of java this keyword


Here is given the 6 usage of java this keyword.
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the
method.
The this keyword can be used to refer current class instance
variable. If there is ambiguity between the instance variables and
parameters, this keyword resolves the problem of ambiguity.

Let's understand the problem if we don't use this keyword by the


example given below:
class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
rollno = rollno;
name = name;
fee = fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
}
class TestThis1
{
public static void main(String args[])
{
Student s1 = new Student(111, "ankit", 5000f);
Student s2 = new Student(112, "sumit", 6000f);
s1.display();
s2.display();
}
}
Output: 0 null 0.0
0 null 0.0

In the above example, parameters (formal arguments) and


instance variables are same. So, we are
using this keyword to distinguish local variable and instance
variable.
Solution of the above problem by this keyword
class Student
{
int rollno;
String name;
float fee;
Student(int rollno, String name, float fee)
{
this.rollno = rollno;
this.name = name;
this.fee = fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
}
class TestThis2
{
public static void main(String args[])
{
Student s1 = new Student(111, "ankit", 5000f);
Student s2 = new Student(112, "sumit", 6000f);
s1.display();
s2.display();
}
}
Output:
111 ankit 5000
112 sumit 6000

Overloading Methods and Constructors


In Java, overloading allows you to define multiple methods or
constructors with the same name but different parameters. This
enables you to provide different implementations depending on
the input provided.
Method Overloading:
public class Calculator {

public int add(int a, int b) {


return a + b;
}

public double add(double a, double b) {


return a + b;
}

public int add(int a, int b, int c) {


return a + b + c;
}
}
In this example, we have three add methods with different
parameter types. The compiler determines which method to call
based on the arguments passed during invocation.
Constructor Overloading:
public class Person {

private String name;


private int age;

public Person(String name) {


this.name = name;
}

public Person(String name, int age) {


this.name = name;
this.age = age;
}
}
Here, we have two constructors for the Person class. One takes
only the name, while the other takes both the name and age.
Key Points:
 Overloading is resolved at compile time, based on the method or
constructor signature (name, number, and types of parameters).
 The return type of the method is not considered for overloading.
 Constructors cannot be overridden, but they can be overloaded.

Recursion in Java
Recursion in Java (or any programming language) is a technique
where a method calls itself in order to solve a problem. A
recursive method typically has two main parts:

1. Base case: A condition that stops the recursion, preventing


infinite recursion.
2. Recursive case: The part where the method calls itself with
a different argument, bringing it closer to the base case.

Here’s a breakdown and an example of recursion in Java:


Simple Example: Factorial of a Number

The factorial of a number n, denoted as n!, is the product of all


positive integers from 1 to n. For example, 5! = 5 * 4 * 3 * 2 * 1 =
120.

Recursive Formula for Factorial:

 n! = n * (n - 1)!
 Base case: 0! = 1 and 1! = 1

Java Code for Factorial Using Recursion


java
Copy code
public class Factorial {
// Recursive method to calculate factorial
public static int factorial(int n) {
// Base case: when n is 0 or 1, return 1
if (n == 0 || n == 1) {
return 1;
}
// Recursive case: n * factorial of (n - 1)
return n * factorial(n - 1);
}

public static void main(String[] args) {


int num = 5; // Example input
System.out.println("Factorial of " + num + " is: " +
factorial(num));
}
}
Explanation of the Code:

 Base case: if (n == 0 || n == 1)—if the input n is either 0 or


1, the factorial is 1 because by definition 0! = 1 and 1! = 1.
 Recursive case: return n * factorial(n - 1);—the method
calls itself with the value n - 1 and multiplies it by n. This
process continues until it reaches the base case.

Output for factorial(5):


csharp
Copy code
Factorial of 5 is: 120

Key Concepts in Recursion:

1. Base Case: Every recursive method needs a base case to


stop the recursion; otherwise, the method will keep calling
itself indefinitely and cause a stack overflow error.
2. Recursive Case: This is the case where the method calls
itself with modified parameters. Each recursive call should
bring the problem closer to the base case.
3. Stack Memory: Recursion uses the call stack to store
method calls. Each recursive call pushes a new frame onto
the stack. If there are too many recursive calls (e.g., in cases
where the base case is never reached), it can result in a
StackOverflowError.

Java Garbage Collection


In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused


memory automatically. In other words, it is a way to destroy the
unused objects.

To do so, we were using free() function in C language and delete()


in C++. But, in java it is performed automatically. So, java
provides better memory management.
Advantage of Garbage Collection
o It makes java memory efficient because garbage collector
removes the unreferenced objects from heap memory.
o It is automatically done by the garbage collector(a part of
JVM) so we don't need to make extra efforts.

How can an object be unreferenced?


There are many ways:

o By nulling the reference


o By assigning a reference to another
o By anonymous object etc.

1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage c
ollection
3) By anonymous object:
new Employee();

finalize() method
The finalize() method is invoked each time before the object is garbage
collected. This method can be used to perform cleanup processing. This
method is defined in Object class as:

1. protected void finalize(){}


Note: The Garbage collector of JVM collects only those
objects that are created by new keyword. So if you have
created any object without new, you can use finalize
method to perform cleanup processing (destroying
remaining objects).

gc() method
The gc() method is used to invoke the garbage collector to perform
cleanup processing. The gc() is found in System and Runtime classes.

1. public static void gc(){}


Note: Garbage collection is performed by a daemon
thread called Garbage Collector(GC). This thread calls
the finalize() method before object is garbage collected.

Simple Example of garbage collection in java


1. public class TestGarbage1{
2. public void finalize(){System.out.println("object is garbage collecte
d");}
3. public static void main(String args[]){
4. TestGarbage1 s1=new TestGarbage1();
5. TestGarbage1 s2=new TestGarbage1();
6. s1=null;
7. s2=null;
8. System.gc();
9. }
10. }
Out put:
object is garbage collected
object is garbage collected

Note: Neither finalization nor garbage collection


is guaranteed.

Java String
In Java, the String class is a widely used class that represents a
sequence of characters. It is part of the java.lang package and
provides a variety of methods to manipulate and work with strings
effectively.
Key Features of Strings in Java

1. Immutable: Strings are immutable in Java, meaning once a


String object is created, its value cannot be changed. Any
modification creates a new String object.
2. Stored in String Pool: Java maintains a special memory area called
the String Pool to store string literals, which optimizes memory
usage.
3. Support for Unicode: Java strings support Unicode, allowing them
to handle international characters.

CharSequence Interface

The CharSequence interface is used to represent sequence of


characters. It is implemented by String, StringBuffer and
StringBuilder classes. It means, we can create string in java by
using these 3 classes
String vs StringBuilder vs StringBuffer

 String: Immutable, creates a new object for every modification.


 StringBuilder: Mutable, not synchronized, faster for single-threaded
operations.
 StringBuffer: Mutable, synchronized, thread-safe but slower.

There are two ways to create String object:


1. By stringliteral
2. By newkeyword

1.String Literal
String str = "Hello, World!";

 Stored in the String Pool.

2.Using the new Keyword:


String str = new String("Hello, World!");

 Creates a new object in the heap memory.

Here are some of the most commonly used methods of the String class:

Method Description
length() Returns the length of the string.
charAt(index) Returns the character at the specified index.
substring(start, end) Extracts a substring from the string.
equals(str) Compares two strings for equality.
Method Description
equalsIgnoreCase(str) Compares two strings, ignoring case
differences.
compareTo(str) Compares two strings lexicographically.
toUpperCase() Converts all characters to uppercase.
toLowerCase() Converts all characters to lowercase.
trim() Removes leading and trailing whitespaces.
replace(oldChar, Replaces all occurrences of a character with
newChar) another character.
contains(substring) Checks if the string contains the specified
sequence of characters.
startsWith(prefix) Checks if the string starts with the specified
prefix.
endsWith(suffix) Checks if the string ends with the specified
suffix.
split(delimiter) Splits the string into an array based on the
specified delimiter.
indexOf(char) Returns the index of the first occurrence of a
character or substring.
lastIndexOf(char) Returns the index of the last occurrence of a
character or substring.
isEmpty() Checks if the string is empty.
concat(str) Concatenates the specified string to the end of
the current string.
valueOf(data) Converts other data types to strings (e.g.,
integers, floats, etc.).

public class StringExample {

public static void main(String[] args) {

String str = "Hello, Java!";

System.out.println("Length: " + str.length()); // Output: 12

System.out.println("Character at index 1: " + str.charAt(1)); // Output: e


System.out.println("Substring: " + str.substring(7)); // Output: Java!

System.out.println("Uppercase: " + str.toUpperCase()); // Output: HELLO, JAVA!

Immutable String in Java


In java, string objects are immutable. Immutable simply means unmodifiable or
unchangeable. Once string object is created its data or state can't be changed but a
new string object is created. Let's try to understand the immutability concept by the
example given below:
public class StringImmutable {
public static void main(String[] args) {
String str = "Hello";
String newStr = str.concat(", World!");
System.out.println("Original String: " + str); // Output: Hello
System.out.println("Modified String: " + newStr); // Output: Hello
World!
}
}

You might also like