0% found this document useful (0 votes)
4 views53 pages

Java Unit-1 Notes

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, including definitions and examples of objects, classes, inheritance, polymorphism, abstraction, and encapsulation. It also explains the Java Virtual Machine (JVM) architecture, data types, variables, and operators in Java. Key components such as class loaders, memory areas, and execution engines are discussed to illustrate how Java executes programs.

Uploaded by

hinatabi13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views53 pages

Java Unit-1 Notes

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, including definitions and examples of objects, classes, inheritance, polymorphism, abstraction, and encapsulation. It also explains the Java Virtual Machine (JVM) architecture, data types, variables, and operators in Java. Key components such as class loaders, memory areas, and execution engines are discussed to illustrate how Java executes programs.

Uploaded by

hinatabi13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

JAVA PROGRAMMING

CGB1201

OOPs Concepts:
Object means a real-world entity such as a pen, chair, table, computer,
watch, etc. Object-Oriented Programming is a methodology or paradigm
to design a program using classes and objects. It simplifies software
development and maintenance by providing some concepts:

Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation

Object:

Any entity that has state and behavior is known as an object. For example,
a chair, pen, table, keyboard, bike, etc. It can be physical or logical.

An Object can be defined as an instance of a class. An object contains an


address and takes up some space in memory. Objects can communicate
without knowing the details of each other's data or code. The only
necessary thing is the type of message accepted and the type of response
returned by the objects.
Example: A dog is an object because it has states like color, name, breed,
etc. as well as behaviors like wagging the tail, barking, eating, etc.

Class

Collection of objects is called class. It is a logical entity.

A class can also be defined as a blueprint from which you can create an
individual object. Class doesn't consume any space.

Inheritance

When one object acquires all the properties and behaviors of a parent
object, it is known as inheritance. It provides code reusability. It is used to
achieve runtime polymorphism.

Definition: Inheritance allows a new class (child class) to inherit the


properties and behavior of an existing class (parent class). The child class
can use, modify, or extend the functionality of the parent class.

Purpose: It promotes code reusability and establishes a relationship


between classes.

Example: In Java, you use the “extends” keyword to create a subclass.

Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to
convince the customer differently, to draw something, for example, shape, triangle, rectangle,
etc.

In Java, we use method overloading and method overriding to achieve polymorphism.


Purpose: It enables a single interface to be used for different data types, making the code
more flexible and extensible.

Another example can be to speak something; for example, a cat speaks meow, dog barks woof,
etc.

Abstraction:
Hiding internal details and showing functionality is known as abstraction. For example phone
call, we don't know the internal processing.

In Java, we use abstract class and interface to achieve abstraction.

Encapsulation:

Binding (or wrapping) code and data together into a single unit are known as encapsulation.
For example, a capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.

Java Virtual Machine (JVM):


The Java Virtual Machine is an engine that provides a runtime environment
to execute Java bytecode. It is platform-independent, meaning Java code can
run on any device or operating system that has a JVM.

Key Components:

Class Loader: Loads classes into memory.


Memory Area: Includes the Method Area, Heap, Stack, PC Register, and
Native Method Stack.
Execution Engine: Executes the bytecode.
Java Native Interface (JNI): Allows the JVM to call native applications and
libraries.
Java Runtime Environment (JRE): A package that provides the JVM and
libraries to run Java applications.
1) Classloader
Classloader is a subsystem of JVM which is used to load class files. Whenever we run
the java program, it is loaded first by the classloader. There are three built-in
classloaders in Java.

1. Bootstrap ClassLoader: This is the first classloader which is the super class of
Extension classloader. It loads the rt.jar file which contains all class files of Java
Standard Edition like java.lang package classes, java.net package classes, java.util
package classes, java.io package classes, java.sql package classes etc.
2. Extension ClassLoader: This is the child classloader of Bootstrap and parent
classloader of System classloader. It loades the jar files located inside
$JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: This is the child classloader of Extension
classloader. It loads the classfiles from classpath. By default, classpath is set to
current directory. You can change the classpath using "-cp" or "-classpath" switch.
It is also known as Application classloader.

//Let's see an example to print the classloader name

public class ClassLoaderExample

public static void main(String[] args)

// Let's print the classloader name of current class.


//Application/System classloader will load this class

Class c=ClassLoaderExample.class;

System.out.println(c.getClassLoader());

//If we print the classloader name of String, it will print null because it is an

//in-built class which is found in rt.jar, so it is loaded by Bootstrap classloader

System.out.println(String.class.getClassLoader());

Output:

sun.misc.Launcher$AppClassLoader@4e0e2f2a

null

These are the internal classloaders provided by Java. If you want to create your own
classloader, you need to extend the ClassLoader class.

2) Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool,
field and method data, the code for methods.

3) Heap
It is the runtime data area in which objects are allocated.

4) Stack
Java Stack stores frames. It holds local variables and partial results, and plays a part in
method invocation and return.

Each thread has a private JVM stack, created at the same time as thread.

A new frame is created each time a method is invoked. A frame is destroyed when its
method invocation completes.

5) Program Counter Register


PC (program counter) register contains the address of the Java virtual machine
instruction currently being executed.

6) Native Method Stack


It contains all the native methods used in the application.

7) Execution Engine
It contains:

1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles
parts of the byte code that have similar functionality at the same time, and hence
reduces the amount of time needed for compilation. Here, the term "compiler"
refers to a translator from the instruction set of a Java virtual machine (JVM) to
the instruction set of a specific CPU.

8) Java Native Interface


Java Native Interface (JNI) is a framework which provides an interface to
communicate with another application written in another language like C, C++,
Assembly etc. Java uses JNI framework to send output to the Console or interact with
OS libraries.

Data Types in Java


Data types in Java are of different sizes and values that can be stored in the
variable that is made as per convenience and circumstances to cover up all
test cases. Java has two categories in which data types are segregated

1. Primitive Data Type: such as Boolean, char, int, short, byte, long, float, and
double
2. Non-Primitive Data Type or Object Data type: such as String, Array, etc.
Primitive:
Type Descri Defaul Size Example Range of values
ption t Literals

boolean true or false 8 bits true, false true, false


false

byte twos- 0 8 bits (none) -128 to 127


compl
ement
integer

char Unicod \u000 16 ‘a’, ‘\u0041’, characters


e 0 bits ‘\101’, ‘\\’, ‘\’, representation
charac ‘\n’, ‘β’ of ASCII values
ter
0 to 255

short twos- 0 16 (none) -32,768 to


compl bits 32,767
ement
integer

int twos- 0 32 -2,-1,0,1,2 -2,147,483,648


compl bits
ement to
intger
2,147,483,647

long twos- 0 64 -2L,-1L,0L,1L, -9,223,372,036,


compl bits 2L 854,775,808
ement
integer to

9,223,372,036,8
54,775,807

float IEEE 0.0 32 1.23e100f , upto 7 decimal


754 bits -1.23e-100f , digits
floatin .3f ,3.14F
g point

double IEEE 0.0 64 1.23456e300 upto 16


754 bits d , -123456e- decimal digits
floatin 300d , 1e1d
g point
Syntax:

1. Boolean Data Type: boolean booleanVar;

2. Byte Data Type: byte byteVar;

3. Short Data Type: short shortVar;

4. Integer Data Type: int intVar;

5. Long Data Type: long longVar;

6. Float Data Type: float floatVar;

7. Double Data Type: double doubleVar;

8. Char Data Type: char charVar;

Eg:

class GFG {

public static void main(String args[])

char a = 'G';

int i = 89;

byte b = 4;

short s = 56;

double d = 4.355453532;

float f = 4.7333434f;

long l = 12121;

System.out.println("char: " + a);

System.out.println("integer: " + i);

System.out.println("byte: " + b);

System.out.println("short: " + s);


System.out.println("float: " + f);

System.out.println("double: " + d);

System.out.println("long: " + l);

Non - Primitve:
The Reference Data Types will contain a memory address of variable
values because the reference types won’t store the variable value
directly in memory. They are strings, objects, arrays, etc.

1. Strings

Strings are defined as an array of characters. The difference between a


character array and a string in Java is, that the string is designed to hold
a sequence of characters in a single variable whereas, a character array
is a collection of separate char-type entities. Unlike C/C++, Java strings
are not terminated with a null character.

Syntax: Declaring a string

<String_Type> <string_variable> = “<sequence_of_string>”;

Example:

// Declare String without using new operator


String s = "ALLWIN";
// Declare String using new operator
String s1 = new String("IT A");

2. Class
A class is a user-defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one
type. In general, class declarations can include these components, in order:

1. Modifiers : A class can be public or has default access. Refer to access


specifiers for classes or interfaces in Java
2. Class name: The name should begin with an initial letter (capitalized by
convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded
by the keyword extends. A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the
class, if any, preceded by the keyword implements. A class can implement more
than one interface.
5. Body: The class body is surrounded by braces, { }.

3. Object

An Object is a basic unit of Object-Oriented Programming and represents real-life


entities. A typical Java program creates many objects, which as you know, interact
by invoking methods. An object consists of :

1. State : It is represented by the attributes of an object. It also reflects the


properties of an object.
2. Behavior : It is represented by the methods of an object. It also reflects the
response of an object to other objects.
3. Identity : It gives a unique name to an object and enables one object to interact
with other objects.

4. Interface

Like a class, an interface can have methods and variables, but the methods
declared in an interface are by default abstract (only method signature, no body).

Interfaces specify what a class must do and not how. It is the blueprint of the
class.
An Interface is about capabilities like a Player may be an interface and any class
implementing Player must be able to (or must implement) move(). So it
specifies a set of methods that the class has to implement.
If a class implements an interface and does not provide method bodies for all
functions specified in the interface, then the class must be declared abstract.
A Java library example is Comparator Interface . If a class implements this
interface, then it can be used to sort a collection.

5. Array

A collection of elements of the same type. Can be single-dimensional (e.g., int[]) or


multi-dimensional (e.g., int[][]). The following are some important points about
Java arrays.

In Java, all arrays are dynamically allocated. (discussed below)


Since arrays are objects in Java, we can find their length using member length.
A Java array variable can also be declared like other variables with [] after the
data type.
The variables in the array are ordered and each has an index beginning with 0.
Java array can also be used as a static field, a local variable, or a method
parameter.
The size of an array must be specified by an int value and not long or short.
The direct superclass of an array type is Object.

Eg:
// Define the Student class
class Student {
// Attributes of the Student class
String name;
int age;

// Constructor to initialize Student objects


Student(String name, int age) {
this.name = name;
this.age = age;
}

// Method to display student details


void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}

// Main class to demonstrate the use of objects and arrays


public class Main {
public static void main(String[] args) {
// Create an array to hold Student objects
Student[] students = new Student[3];

// Create Student objects and store them in the array


students[0] = new Student("A", 20);
students[1] = new Student("B", 22);
students[2] = new Student("C", 19);
// Loop through the array and display details of each student
for (int i = 0; i < students.length; i++) {
students[i].display();
}
}
}

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

The variable is the name of a memory location. There are three types of
variables in Java: local, instance, and static.

1) Local Variable

A variable declared inside the body of the method is called local variable. You
can use this variable only within that method and the other methods in the class
aren't even aware that the variable exists.

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

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 variable

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.

Eg:
public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class

Operators in Java
Java provides many types of operators which can be used according to
the need. They are classified based on the functionality they provide.

Operators in Java are the symbols used for performing specific


operations in Java. Operators make tasks like addition, multiplication,
etc which look easy although the implementation of these tasks is quite
complex.

Types of Operators in Java


There are multiple types of operators in Java all are mentioned below:

1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instance of operator

1. Arithmetic Operators

They are used to perform simple arithmetic operations on primitive data


types.

* : Multiplication
/ : Division
% : Modulo
+ : Addition
– : Subtraction
2. Unary Operators

Unary operators need only one operand. They are used to


increment, decrement, or negate a value.

– : Unary minus, used for negating the values.


+ : Unary plus indicates the positive value (numbers are positive
without this, however). It performs an automatic conversion to int
when the type of its operand is the byte, char, or short. This is called
unary numeric promotion.
++ : Increment operator, used for incrementing the value by 1. There
are two varieties of increment operators.
Post-Increment: Value is first used for computing the result and
then incremented.
Pre-Increment: Value is incremented first, and then the result is
computed.
– – : Decrement operator, used for decrementing the value by 1.
There are two varieties of decrement operators.
Post-decrement: Value is first used for computing the result and
then decremented.
Pre-Decrement: The value is decremented first, and then the
result is computed.
! : Logical not operator, used for inverting a boolean value.
3. Assignment Operator

‘=’ Assignment operator is used to assign a value to any variable. It has


right-to-left associativity, i.e. value given on the right-hand side of the
operator is assigned to the variable on the left, and therefore right-hand
side value must be declared before using it or should be a constant.
The general format of the assignment operator is:

variable = value;
In many cases, the assignment operator can be combined with other
operators to build a shorter version of the statement called a
Compound Statement. For example, instead of a = a+5, we can write a +=
5.

+=, for adding the left operand with the right operand and then
assigning it to the variable on the left.
-=, for subtracting the right operand from the left operand and then
assigning it to the variable on the left.
*=, for multiplying the left operand with the right operand and then
assigning it to the variable on the left.
/=, for dividing the left operand by the right operand and then
assigning it to the variable on the left.
%=, for assigning the modulo of the left operand by the right operand
and then assigning it to the variable on the left.
4. Relational Operators

These operators are used to check for relations like equality, greater
than, and less than. They return boolean results after the
comparison and are extensively used in looping statements as well
as conditional if-else statements. The general format is,

variable relation_operator value


Some of the relational operators are-

==, Equal to returns true if the left-hand side is equal to the right-
hand side.
!=, Not Equal to returns true if the left-hand side is not equal to
the right-hand side.
<, less than: returns true if the left-hand side is less than the
right-hand side.
<=, less than or equal to returns true if the left-hand side is less
than or equal to the right-hand side.
>, Greater than: returns true if the left-hand side is greater than
the right-hand side.
>=, Greater than or equal to returns true if the left-hand side is
greater than or equal to the right-hand side.

Example:
Java
// Java Program to implement
// Relational Operators
import java.io.*;

// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// Comparison operators
int a = 10;
int b = 3;
int c = 5;

System.out.println("a > b: " + (a > b));


System.out.println("a < b: " + (a < b));
System.out.println("a >= b: " + (a >= b));
System.out.println("a <= b: " + (a <= b));
System.out.println("a == c: " + (a == c));
System.out.println("a != c: " + (a != c));
}
}

Output
a > b: true
a < b: false
a >= b: true
a <= b: false
a == c: false
a != c: true

5. Logical Operators

These operators are used to perform “logical AND” and “logical OR”
operations.

Conditional operators are:

&&, Logical AND: returns true when both conditions are true.
||, Logical OR: returns true if at least one condition is true.
!, Logical NOT: returns true when a condition is false and vice-
versa

Example:
Java
// Java Program to implemenet
// Logical operators
import java.io.*;

// Driver Class
class GFG {
// Main Function
public static void main (String[] args) {
// Logical operators
boolean x = true;
boolean y = false;

System.out.println("x && y: " + (x && y));


System.out.println("x || y: " + (x || y));
System.out.println("!x: " + (!x));
}
}

Output
x && y: false
x || y: true
!x: false

6. Ternary operator

The ternary operator is a shorthand version of the if-else statement.


It has three operands and hence the name Ternary.

The general format is:

condition ? if true : if false


The above statement means that if the condition evaluates to true,
then execute the statements after the ‘?’ else execute the
statements after the ‘:’.

Example:
Java
// Java program to illustrate
// max of three numbers using
// ternary operator.
public class operators {
public static void main(String[] args)
{
int a = 20, b = 10, c = 30, result;

// result holds max of three


// numbers
result
= ((a > b) ? (a > c) ? a : c : (b > c) ? b : c);
System.out.println("Max of three numbers = "
+ result);
}
}

Output
Max of three numbers = 30

7. Bitwise Operators

These operators are used to perform the manipulation of individual


bits of a number.

&, Bitwise AND operator: returns bit by bit AND of input values.
|, Bitwise OR operator: returns bit by bit OR of input values.
^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
~, Bitwise Complement Operator: This is a unary operator which
returns the one’s complement representation of the input value,
i.e., with all bits inverted.
Java
// Java Program to implement
// bitwise operators
import java.io.*;

// Driver class
class GFG {
// main function
public static void main(String[] args)
{
// Bitwise operators
int d = 0b1010;
int e = 0b1100;
System.out.println("d & e: " + (d & e));
System.out.println("d | e: " + (d | e));
System.out.println("d ^ e: " + (d ^ e));
System.out.println("~d: " + (~d));
System.out.println("d << 2: " + (d << 2));
System.out.println("e >> 1: " + (e >> 1));
System.out.println("e >>> 1: " + (e >>> 1));
}
}

Output
d & e: 8
d | e: 14
d ^ e: 6
~d: -11
d << 2: 40
e >> 1: 6
e >>> 1: 6

8. Shift Operators

These operators are used to shift the bits of a number left or right,
thereby multiplying or dividing the number by two, respectively.
They can be used when we have to multiply or divide a number by
two. General format-

number shift_op number_of_places_to_shift;

<<, Left shift operator: shifts the bits of the number to the left
and fills 0 on voids left as a result. Similar effect as multiplying
the number with some power of two.
>>, Signed Right shift operator: shifts the bits of the number to
the right and fills 0 on voids left as a result. The leftmost bit
depends on the sign of the initial number. Similar effect to
dividing the number with some power of two.
>>>, Unsigned Right shift operator: shifts the bits of the number
to the right and fills 0 on voids left as a result. The leftmost bit is
set to 0.
Java
// Java Program to implement
// shift operators
import java.io.*;
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
int a = 10;

// using left shift


System.out.println("a<<1 : " + (a << 1));

// using right shift


System.out.println("a>>1 : " + (a >> 1));
}
}

Output
a<<1 : 20
a>>1 : 5

9. instanceof operator

The instance of the operator is used for type checking. It can be


used to test if an object is an instance of a class, a subclass, or an
interface. General format-
object instance of class/subclass/interface
Java
// Java program to illustrate
// instance of operator

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

Person obj1 = new Person();


Person obj2 = new Boy();

// As obj is of type person, it is not an


// instance of Boy or interface
System.out.println("obj1 instanceof Person: "
+ (obj1 instanceof Person));
System.out.println("obj1 instanceof Boy: "
+ (obj1 instanceof Boy));
System.out.println("obj1 instanceof MyInterface: "
+ (obj1 instanceof MyInterface));

// Since obj2 is of type boy,


// whose parent class is person
// and it implements the interface Myinterface
// it is instance of all of these classes
System.out.println("obj2 instanceof Person: "
+ (obj2 instanceof Person));
System.out.println("obj2 instanceof Boy: "
+ (obj2 instanceof Boy));
System.out.println("obj2 instanceof MyInterface: "
+ (obj2 instanceof MyInterface));
}
}

class Person {
}

class Boy extends Person implements MyInterface {


}

interface MyInterface {
}

Output
obj1 instanceof Person: true
obj1 instanceof Boy: false
obj1 instanceof MyInterface: false
obj2 instanceof Person: true
obj2 instanceof Boy: true
obj2 instanceof MyInterface: true

Control statements

Java provides three types of control flow statements.


1. Decision-Making statements
if statements
switch statement
2. Loop statements
do while loop
while loop
for loop
for-each loop
3. Jump statements
break statement
continue statement

Decision-Making statements:

As the name suggests, decision-making statements decide which


statement to execute and when. Decision-making statements evaluate the
Boolean expression and control the program flow depending upon the
result of the condition provided. There are two types of decision-making
statements in Java, i.e., If statement and switch statement.

1) If Statement:

In Java, the "if" statement is used to evaluate a condition. The control of


the program is diverted depending upon the specific condition. The
condition of the If statement gives a Boolean value, either true or false. In
Java, there are four types of if-statements given below.

1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement

1) Simple if statement:
It is the most basic statement among all control flow statements in
Java. It evaluates a Boolean expression and enables the program to
enter a block of code if the expression evaluates to true.

Syntax of if statement is given below.

if(condition) {

statement 1; //executes when condition is true

2) if-else statement

The if-else statement is an extension to the if-statement, which uses


another block of code, i.e., else block. The else block is executed if the
condition of the if-block is evaluated as false.

Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}

3) if-else-if ladder:

The if-else-if statement contains the if-statement followed by


multiple else-if statements. In other words, we can say that it is the
chain of if-else statements that create a decision tree where the
program may enter in the block of code where the condition is true.
We can also define an else statement at the end of the chain.

Syntax of if-else-if statement is given below.


if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else
statement inside another if or else-if statement.
Syntax of Nested if-statement is given below.
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}

Switch Statement:

In Java, Switch statements are similar to if-else-if statements. The switch


statement contains multiple blocks of code called cases and a single case
is executed based on the variable which is being switched. The switch
statement is easier to use instead of if-else-if statements. It also enhances
the readability of the program.

Points to be noted about switch statement:

The case variables can be int, short, byte, char, or enumeration. String
type is also supported since version 7 of Java
Cases cannot be duplicate
Default statement is executed when any of the case doesn't match the
value of expression. It is optional.
Break statement terminates the switch block when the condition is
satisfied.
It is optional, if not used, next case is executed.
While using switch statements, we must notice that the case expression
will be of the same type as the variable. However, it will also be a
constant value.

The syntax to use the switch statement is given below.


switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}

Loop Statements

In programming, sometimes we need to execute the block of code


repeatedly while some condition evaluates to true. However, loop
statements are used to execute the set of instructions in a repeated order.
The execution of the set of instructions depends upon a particular
condition.
In Java, we have three types of loops that execute similarly. However, there
are differences in their syntax and condition checking time.

1. for loop
2. while loop
3. do-while loop

Let's understand the loop statements one by one.

Java for loop

In Java, for loop is similar to C and C++. It enables us to initialize the loop
variable, check the condition, and increment/decrement in a single line of
code. We use the for loop only when we exactly know the number of times,
we want to execute the block of code.

for(initialization, condition, increment/decrement) {

//block of statements

The flow chart for the for-loop is given below.

Java do-while loop


The do-while loop checks the condition at the end of the loop after
executing the loop statements. When the number of iteration is not known
and we have to execute the loop at least once, we can use do-while loop.

It is also known as the exit-controlled loop since the condition is not


checked in advance. The syntax of the do-while loop is given below.

do

{
//statements
} while (condition);

The flow chart of the do-while loop is given in the following image.

Jump Statements

Jump statements are used to transfer the control of the program to the
specific statements. In other words, jump statements transfer the
execution control to the other part of the program. There are two types of
jump statements in Java, i.e., break and continue.

Java break statement


As the name suggests, the break statement is used to break the current
flow of the program and transfer the control to the next statement outside
a loop or switch statement. However, it breaks only the inner loop in the
case of the nested loop.

Class and Methods

Method in Java
In general, a method is a way to perform some task. Similarly, the
method in Java is a collection of instructions that performs a specific
task. It provides the reusability of code. We can also easily modify
code using methods.

Method Declaration

Method Declaration

In general, method declarations have 6 components:

1. Modifier: It defines the access type of the method i.e. from where
it can be accessed in your application. In Java, there 4 types of
access specifiers.

public: It is accessible in all classes in your application.


protected: It is accessible within the class in which it is defined
and in its subclasses.
private: It is accessible only within the class in which it is
defined.
default: It is declared/defined without using any modifier. It is
accessible within the same class and package within which its
class is defined.

2. The return type: The data type of the value returned by the method or
void if does not return a value. It is Mandatory in syntax.

3. Method Name: the rules for field names apply to method names as
well, but the convention is a little different. It is Mandatory in syntax.

4. Parameter list: Comma-separated list of the input parameters is


defined, preceded by their data type, within the enclosed parenthesis. If
there are no parameters, you must use empty parentheses (). It is
Optional in syntax.

5. Exception list: The exceptions you expect by the method can throw;
you can specify these exception(s). It is Optional in syntax.

6. Method body: it is enclosed between braces. The code you need to be


executed to perform your intended operations. It is Optional in syntax.

Types of Methods in Java


There are two types of methods in Java:

1. Predefined Method

In Java, predefined methods are the method that is already defined in


the Java class libraries is known as predefined methods. It is also known
as the standard library method or built-in method. We can directly use
these methods just by calling them in the program at any point.

2. User-defined Method
The method written by the user or programmer is known as a user-
defined method. These methods are modified according to the
requirement.

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

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.

There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.

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

Rules for creating Java constructor


There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors


There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor


A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:

1. <class_name>(){}

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{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}

Output:

Bike is created

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 constructor.


class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(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
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}

Output:

111 Karan

222 Aryan

Static Members
In Java, static members are variables or methods that belong to the class rather than to any
specific instance of the class. Here's an overview of static members in Java:

1. Static Variables (Class Variables)

- Definition: Static variables are declared using the `static` keyword within a class but outside any
method, constructor, or block.

-Scope: These variables are associated with the class, not instances. All instances of the class
share the same static variable.

- Memory Allocation: Static variables are stored in the class area of memory. They are initialized
when the class is first loaded, even before any instance of the class is created.

-Access: You can access static variables using the class name directly (`ClassName.variableName`),
and they can also be accessed through an object reference, though this is not recommended as it
can be misleading.
Example:

class Example {
static int count = 0; // static variable

Example() {
count++; // increment the static variable
}

static void displayCount() {


System.out.println("Count: " + count);
}
}

public class Test {


public static void main(String[] args) {
Example obj1 = new Example();
Example obj2 = new Example();
Example.displayCount(); // Output: Count: 2
}
}

2. Static Methods

- Definition: Static methods are methods that can be called on the class itself, without needing an
instance of the class. They are declared with the `static` keyword.

-Access:Like static variables, static methods can be called using the class name
(`ClassName.methodName()`).

- Restrictions:

- Static methods cannot access instance variables or methods directly; they can only access
static variables and other static methods.

- Static methods cannot use the `this` or `super` keywords because they do not belong to any
specific instance.

- Example:

class Example {
static int count = 0;
static void displayCount() {
System.out.println("Count: " + count);
}

static void incrementCount() {


count++;
}
}

public class Test {


public static void main(String[] args) {
Example.incrementCount();
Example.displayCount(); // Output: Count: 1
}
}

3. Static Blocks

- Definition: Static blocks are used to initialize static variables. They are executed when the class is
loaded, before any object of the class is created and before any static methods are called.

- Usage: Static blocks can be useful for complex static variable initialization or for executing code
that needs to run once at the start.

- Example:

class Example {
static int count;

// Static block
static {
count = 10;
System.out.println("Static block executed");
}

static void displayCount() {


System.out.println("Count: " + count);
}
}

public class Test {


public static void main(String[] args) {
Example.displayCount(); // Output: Static block executed, Count: 10
}
}

4. Static Import

- Definition: Static import allows you to import static members (fields and methods) from other
classes so that you can use them without class qualification.

-Example:

import static java.lang.Math.*; // Import all static members of Math

public class Test {


public static void main(String[] args) {
System.out.println(sqrt(16)); // Direct use without Math.sqrt()
}
}

Java Arrays

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

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.

In Java, array is an object of a dynamically generated class. Java array inherits the Object
class, and implements the Serializable as well as Cloneable interfaces. We can store primitive
values or objects in an array in Java. Like C/C++, we can also create single dimentional or
multidimentional arrays in Java.

Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in Java which grows
automatically.

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

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];

Instantiation of an Array in Java

1. arrayRefVar=new datatype[size];

Example of Java 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, initialize


//and traverse the Java array.
class Testarray{
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]);
}}
Test it Now
Output:
10
20
70
40
50

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[][]; (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;

arr[1][2]=6;

arr[2][0]=7;

arr[2][1]=8;

arr[2][2]=9;

Example of Multidimensional Java Array


Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional
array.

//Java Program to illustrate the use of multidimensional array


class Testarray3{
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();
}
}} Test it Now
Output:
123
245
445

STRINGS IN JAVA

Strings are the type of objects that can store the character of values and in Java,
every character is stored in 16 bits i,e using UTF 16-bit encoding. A string acts the
same as an array of characters in Java.

Example:

String name = "Geeks";


In Java, strings are objects that represent sequences of characters. The String
class in Java is widely used and provides many methods for manipulating
strings. Let's break down each of the topics mentioned:

1. Serializable Interface

Definition: The String class implements the Serializable interface, which means
that its objects can be converted into a byte stream, making it possible to save
strings to a file or send them over a network.

Example:

import java.io.*;

public class TestSerializable {

public static void main(String[] args) {

String str = "Hello, World!";

try (FileOutputStream fos = new FileOutputStream("string.ser");

ObjectOutputStream oos = new ObjectOutputStream(fos)) {

oos.writeObject(str); // Serialize the string

} catch (IOException e) {
e.printStackTrace();

2. Comparable Interface

Definition: The String class implements the Comparable<String> interface,


which means strings can be compared to each other. The comparison is based
on lexicographical order.

Example:

public class TestComparable {

public static void main(String[] args) {

String str1 = "Apple";

String str2 = "Banana";

int result = str1.compareTo(str2);

if (result < 0) {

System.out.println(str1 + " is less than " + str2);

} else if (result > 0) {

System.out.println(str1 + " is greater than " + str2);

} else {

System.out.println(str1 + " is equal to " + str2);

}
3. CharSequence Interface

Definition: The CharSequence interface represents a readable sequence of


char values. The String class implements this interface, making it compatible
with other APIs that expect a CharSequence.

Methods: charAt(int index), length(), subSequence(int start, int end), and


toString().

Example:

java

Copy code

public class TestCharSequence {

public static void main(String[] args) {

CharSequence cs = "Hello, World!";

System.out.println(cs.length()); // Output: 13

System.out.println(cs.charAt(6)); // Output: W

System.out.println(cs.subSequence(0, 5)); // Output: Hello

}
String:

It is class and it is immutable in nature. We cannot change the data once it is


created.

StringBuffer:

It is similar to string class. But it is mutable and we can change data at any time.
It is thread safe.

String Builder:

String buider is same as string buffer. It is also mutable and we can change data
at any time But It is not Thread safe.

String Constructors

Definition: The String class provides several constructors for creating string
objects.

Common Constructors:

String(): Creates an empty string.

String(char[] value): Converts a character array to a string.

String(String original): Creates a new string that is a copy of the argument.


String(byte[] bytes): Decodes a byte array into a string using the platform's
default charset.

Example:

public class TestStringConstructor {

public static void main(String[] args) {

String str1 = new String(); // Empty string

String str2 = new String("Hello"); // Copy of string

char[] charArray = { 'J', 'a', 'v', 'a' };

String str3 = new String(charArray); // Convert char array to string

System.out.println(str1); // Output:

System.out.println(str2); // Output: Hello

System.out.println(str3); // Output: Java

Methods in String Class

Common Methods:
length(): Returns the length of the string.
charAt(int index): Returns the character at the specified index.
substring(int beginIndex, int endIndex): Returns a substring.
toLowerCase(), toUpperCase(): Converts all characters to lower or upper
case.
trim(): Removes whitespace from both ends of the string.
replace(char oldChar, char newChar): Replaces occurrences of a
character.
equals(Object another): Compares the string to another object.
equalsIgnoreCase(String anotherString): Compares two strings ignoring
case.
indexOf(int ch): Returns the index of the first occurrence of a character.
concat(String str):The concat() method appends the specified string to the end of
the current string. It creates a new string that is a combination of both strings.
boolean equals(Object anObject): The equals() method compares the string to
the specified object. It returns true if the strings are equal (i.e., the same sequence of
characters), and false otherwise.
char charAt(int index): The charAt() method returns the character at the specified
index in the string. The index is zero-based.
int compareTo(String anotherString): The compareTo()method compares two
strings lexicographically. It returns:
0 if the strings are equal,
A negative integer if the current string is lexicographically less than the specified
string,
A positive integer if the current string is lexicographically greater than the specified
string.
String substring(int beginIndex) & String substring(int beginIndex, int
endIndex)The substring()method returns a new string that is a substring of the
current string.
substring(int beginIndex): Extracts the substring from the specified index to the
end of the string.
substring(int beginIndex, int endIndex): Extracts the substring from the specified
start index to the end index (exclusive).

Example 1:

public class TestStringMethods {


public static void main(String[] args) {
String str = " Hello, Java! ";

System.out.println(str.length()); // Output: 15
System.out.println(str.charAt(7)); // Output: J
System.out.println(str.substring(2, 7)); // Output: Hello
System.out.println(str.toLowerCase()); // Output: hello, java!
System.out.println(str.trim()); // Output: Hello, Java!
System.out.println(str.replace('l', 'x')); // Output: Hexxo, Java!
System.out.println(str.equals("Hello, Java!")); // Output: false
}
}
Example 2:
public class StringMethodsDemo {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
String str3 = "Hello";

// concat()
String concatenated = str1.concat(" ").concat(str2);
System.out.println("Concatenated String: " + concatenated); // Output:
Hello World

// equals()
System.out.println("str1 equals str3: " + str1.equals(str3)); // Output: true
System.out.println("str1 equals str2: " + str1.equals(str2)); // Output: false

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

// compareTo()
System.out.println("str1 compared to str2: " + str1.compareTo(str2)); //
Output: -15
System.out.println("str1 compared to str3: " + str1.compareTo(str3)); //
Output: 0

// substring()
System.out.println("Substring from index 6 in concatenated: " +
concatenated.substring(6)); // Output: World
System.out.println("Substring from index 0 to 5 in concatenated: " +
concatenated.substring(0, 5)); // Output: Hello
}
}

Example 3:
public class StringFunctions {

public static void main(String[] args) {

String str = "Java Programming";

// Demonstrating various string functions

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

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

System.out.println("Substring: " + str.substring(5, 15)); // substring


System.out.println("Uppercase: " + str.toUpperCase()); //
toUpperCase

System.out.println("Lowercase: " + str.toLowerCase()); //


toLowerCase
System.out.println("Index of 'P': " + str.indexOf('P')); // indexOf

System.out.println("Replace 'a' with 'x': " + str.replace('a', 'x')); // replace

StringBuffer Class

Definition: StringBuffer is a mutable sequence of characters. Unlike String,


it can be modified after it is created.
Common Methods:
append(String str): Appends the specified string to this sequence.
insert(int offset, String str): Inserts the string at the specified position.
replace(int start, int end, String str): Replaces the characters in the
specified range.
delete(int start, int end): Removes the characters in the specified range.
reverse(): Reverses the sequence of characters.
capacity(): Returns the current capacity of the buffer.
Example:

public class TestStringBuffer {

public static void main(String[] args) {

StringBuffer sb = new StringBuffer("Hello");

sb.append(" World"); // Append string

System.out.println(sb); // Output: Hello World

sb.insert(6, "Java "); // Insert string

System.out.println(sb); // Output: Hello Java World

sb.replace(6, 10, "C++"); // Replace part of string

System.out.println(sb); // Output: Hello C++ World

sb.delete(6, 10); // Delete part of string

System.out.println(sb); // Output: Hello World

sb.reverse(); // Reverse the string

System.out.println(sb); // Output: dlroW olleH

THANK YOU

!ALL THE BEST!

You might also like