0% found this document useful (0 votes)
2 views48 pages

Java Notes

Java is a high-level, robust, object-oriented programming language developed by Sun Microsystems in 1995, known for its portability, security, and performance. Key features include simplicity, object-orientation, multithreading, and platform independence, allowing Java programs to run on any machine with a Java Runtime Environment. Java utilizes various data types, operators, and variable types, making it versatile for application development.
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)
2 views48 pages

Java Notes

Java is a high-level, robust, object-oriented programming language developed by Sun Microsystems in 1995, known for its portability, security, and performance. Key features include simplicity, object-orientation, multithreading, and platform independence, allowing Java programs to run on any machine with a Java Runtime Environment. Java utilizes various data types, operators, and variable types, making it versatile for application development.
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

What is Java?

Java is a programming language and a platform. Java is a high level, robust, object-oriented and secure programming
language.

Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. James Gosling is
known as the father of Java. Before Java, its name was Oak. Since Oak was already a registered company, so James
Gosling and his team changed the name from Oak to Java.

Features of Java:
The primary objective of Java programming language creation was to make it portable, simple and secure
programming language. Apart from this, there are also some excellent features which play an important role in the
popularity of this language. The features of Java are also known as Java buzzwords.
A list of the most important features of the Java language is given below.

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple:
Java is easy to learn and its syntax is quite simple, clean and easy to understand. The confusing and ambiguous
concepts of C++ are either left out in Java or they have been re-implemented in a cleaner way.

Ex: Pointers and Operator Overloading are not there in java but were an important part of C++.

Object Oriented:
In java, everything is an object which has some data and behavior. Java can be easily extended as it is based on
Object Model. Following are some basic concepts of OOP's.
i. Object
ii. Class
iii. Inheritance
iv. Polymorphism
v. Abstraction
vi. Encapsulation

Robust:
The English mining of Robust is strong. Java is robust because:
● It uses strong memory management.
● There is a lack of pointers that avoids security problems.
● Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects
which are not being used by a Java application anymore.
● There are exception handling and the type checking mechanism in Java. All these points make Java robust.

Portable:
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any
implementation.

High-performance:
Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native
code. It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted language that is why it
is slower than compiled languages, e.g., C, C++, etc.

Multi-threaded:
A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks
at once by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for
each thread. It shares a common memory area. Threads are important for multi-media, Web applications, etc.

Dynamic:
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on demand. It
also supports functions from its native languages, i.e., C and C++.

Secure:
When it comes to security, Java is always the first choice. With java secure features it enables us to develop virus
free, temper free system. Java program always runs in Java runtime environment with almost null interaction with
system OS, hence it is more secure.

Platform Independent:
Unlike other programming languages such as C, C++ etc. which are compiled into platform specific machines. Java
is guaranteed to be write-once, run-anywhere language.
On compilation Java program is compiled into bytecode. This bytecode is platform independent and can be run on
any machine, plus this bytecode format also provides security. Any machine with Java Runtime Environment can
run Java Programs.
JVM:
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't physically exist.
It is a specification that provides a runtime environment in which Java bytecode can be executed. It can also run those
programs which are written in other languages and compiled to Java bytecode.

JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform dependent because
the configuration of each OS is different from each other. However, Java is platform independent. There are three
notions of the JVM: specification, implementation, and instance.

JRE:
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime Environment is
a set of software tools which are used for developing Java applications. It is used to provide the runtime environment.
It is the implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime.

The implementation of JVM is also actively released by other companies besides Sun Micro Systems.

JDK:
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software development
environment which is used to develop Java applications and applets. It physically exists. It contains JRE +
development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:
● Standard Edition Java Platform
● Enterprise Edition Java Platform
● Micro Edition Java Platform
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an interpreter/loader (java),
a compiler (javas), an archiver (jar), a documentation generator (Javadoc), etc. to complete the development of a Java
Application.

Difference between C++ and Java:

INDEX COMPARISON C++ JAVA


PARAMETER
1 Programming model It has support for both Java has support only for
procedural programming object oriented
and object oriented programming models.
programming.
2 Platform dependence C++ is platform dependent. Java is platform
It is based on the concept of independent. It is based on
Write Once Compile the concept of Write Once
Anywhere. Run Anywhere.
3 Features supported C++ supports features like Java does not support
operator overloading, Goto features like operator
statements, structures, overloading, Goto
pointers, unions, etc. statements, structures,
pointers, unions, etc.
4 Compilation and C ++ is only compiled and Java can be both compiled
Interpretation cannot be interpreted. and interpreted.
5 Library and Code C++ has very limited Java, on the other hand, has
reusability support libraries with low level more diverse libraries with
functionalities. C++ allows a lot of support for code
direct calls to native system reusability. In Java, only
libraries. calls through the Java
Native Interface and
recently Java Native
Access are allowed
6 Memory Management In C++, memory In Java, memory
management is manual. management is System
controlled.
7 Type semantics C++ is pretty consistent In Java, semantics differs
between primitive and for primitive and object
object types. types.
8 Global Scope In C++, both global and Java has no support for
namespace scopes are global scope.
supported.
9 Access control and object In C++, a flexible model In Java, the model is
protection with constant protection is cumbersome and
available. encourages weak
encapsulation.

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. There are three types of variables in java: local, instance and static.

Variable:
A variable is the name of a reserved area allocated in memory. In other words, it is a name of the memory location. It
is a combination of "vary + able" which means its value can be changed.
Types of Variables:
There are three types of variables in Java:
● local variable
● instance variable
● static variable

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.

Ex:
public class VariableExample {
// instance variable
public String myVar="instance variable";

public void myMethod(){


// local variable
String myVar = "Inside Method";
[Link](myVar);
}
public static void main(String args[]){
// Creating object
VariableExample obj = new VariableExample();

/* We are calling the method, that changes the


* value of myVar. We are displaying myVar again after
* the method call, to demonstrate that the local
* variable scope is limited to the method itself.
*/
[Link]("Calling Method");
[Link]();
[Link]([Link]);
}
}
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.

Ex:
public class InstanceVarExample {
String myInstanceVar="instance variable";

public static void main(String args[]){


InstanceVarExample obj = new InstanceVarExample();
InstanceVarExample obj2 = new InstanceVarExample();
InstanceVarExample obj3 = new InstanceVarExample();

[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link] = "Changed Text";

[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}
}

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.

Ex:
public class StaticVarExample {
public static String myClassVar="class or static variable";

public static void main(String args[]){


StaticVarExample obj = new StaticVarExample();
StaticVarExample obj2 = new StaticVarExample();
StaticVarExample obj3 = new StaticVarExample();

//All three will display "class or static variable"


[Link]([Link]);
[Link]([Link]);
[Link]([Link]);

//changing the value of static variable using obj2


[Link] = "Changed Text";

//All three will display "Changed Text"


[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}
}

Data Types in Java:


Data types specify the different sizes and values that can be stored in the variable. There are two types of data types
in Java:

Primitive data types:


The primitive data types include Boolean, char, byte, short, int, long, float and double.

Non-primitive data types:


The non-primitive data types include Classes, Interfaces, and Arrays.

Data Type Default Value Default size

Boolean false 1 bit

char '\u0000' 2 bytes

byte 0 1 byte

short 0 2 bytes

int 0 4 bytes

long 0L 8 bytes

float 0.0f 4 bytes

double 0.0d 8 bytes

Boolean:
The Boolean data type is used to store only two possible values: true and false. This data type is used for simple flags
that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
Ex: Boolean one = false

Byte:
The byte data type is an 8-bit signed two’s complement integer. The byte data type is useful for saving memory in
large arrays.
Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is 127. Its default
value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most required. It saves space
because a byte is 4 times smaller than an integer. It can also be used in place of "int" data type.
Ex: byte a = 45, byte b = -50

Short Data Type:


The short data type is a 16-bit signed two's complement integer. Its value-range lies between -32,768 to 32,767
(inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its default value is 0.
The short data type can also be used to save memory just like byte data type. A short data type is 2 times smaller than
an integer.
Ex: short s = 10000, short r = -5000

Int Data Type:


The int data type is a 32-bit signed two's complement integer. Its value-range lies between - 2,147,483,648 (-2^31) to
2,147,483,647 (2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and maximum value is 2,147,483,647. Its
default value is 0.
The int data type is generally used as a default data type for integral values unless if there is no problem about memory.
Ex: int a = 100000, int b = -200000

Long Data Type:


The long data type is a 64-bit two's complement integer. Its value-range lies between -9,223,372,036,854,775,808(-
2^63) to 9,223,372,036,854,775,807(2^63 -1) (inclusive). Its minimum value is - 9,223,372,036,854,775,808and
maximum value is 9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a
range of values more than those provided by int.
Ex: long a = 100000L, long b = -200000L

Float Data Type:


The float data type is a single-precision 32-bit IEEE 754 floating point. Its value range is unlimited. It is recommended
to use a float (instead of double) if you need to save memory in large arrays of floating-point numbers. The float data
type should never be used for precise values, such as currency. Its default value is 0.0F.
Ex: float f1 = 234.5f

Double Data Type:


The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited. The double
data type is generally used for decimal values just like float. The double data type also should never be used for precise
values, such as currency. Its default value is 0.0d.
Ex: double d1 = 12.3

Char Data Type:


The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or 0) to '\uffff' (or 65,535
inclusive). The char data type is used to store characters.
Ex: char letter = 'A'
Operators in Java:
Operator is a symbol that instructs the compiler to perform a specific action.
Ex: a “+” operator instructs the compiler to perform addition,
a “>” operator instructs the compiler to perform comparison,
“=” for assignment and so on. In this guide, we will discuss operations in java with the help of examples.

Types of Operators in Java:

Operators in java are classified in following eight categories:


1) Arithmetic Operators
2) Assignment Operators
3) Unary Operators
4) Logical Operators
5) Relational operators
6) Bitwise Operators
7) Ternary Operator
8) Shift Operators

1. Arithmetic Operators:
Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act as basic
mathematical operations.
Ex:

2. Assignment Operators:
Java assignment operator is one of the most common operators. It is used to assign the value on its right to the
operand on its left.
Ex:

3. Unary Operators:
As the name suggests, The Unary operators in Java involve single operand. Java supports following unary operators:
Ex:
public class JavaExample {
public static void main(String args[]){
int num1=100;
int num2=200;

//minus(-) unary operator


int inverseNum = -num1;
[Link]("Opposite of num1: "+inverseNum);

//increment
num1++;

//decrement
num2--;

[Link]("num1++ is: "+num1);


[Link]("num2-- is: "+num2);

}
}

4. Logical Operators:
Logical Operators are used to evaluate the outcome of conditions. There are three logical operators: AND (&&), OR
(||) and NOT (!). The AND and OR operators are used when multiple conditions are combined and we need to
evaluate the outcome as a whole.
Ex:
public class LogicalOperatorDemo {
public static void main(String args[]) {
boolean b1 = true;
boolean b2 = false;

[Link]("b1 && b2: " + (b1&&b2));


[Link]("b1 || b2: " + (b1||b2));
[Link]("!(b1 && b2): " + !(b1&&b2));
}
}
5. Comparison (Relational) operators:
Relational operators are used to compare two operands. In this guide, we will discuss various relational operators in
java with the help of examples. Java programming language supports following relational operators.

Ex:
public class JavaExample {
public static void main(String args[]) {
int num1 = 10;
int num2 = 50;
if( num1 != num2 ){
[Link]("num1 and num2 are not equal");
}
else{
[Link]("num1 and num2 are equal");
}

if( num1 > num2 ){


[Link]("num1 is greater than num2");
}
else{
[Link]("num1 is not greater than num2");
}

if( num1 < num2 ){


[Link]("num1 is less than num2");
}
else{
[Link]("num1 is not less than num2");
}
}
}
[Link] operators:
Bitwise operators are used to perform bit-level operations. Let’s say you are performing an AND operation on two
numbers (a & b), then these numbers are converted into binary numbers and then the AND operation is performed.
Finally, the compiler returns decimal equivalent of the output binary number.
Ex:
public class BitwiseOperatorDemo {
public static void main(String args[]) {

int num1 = 11; /* 11 = 00001011 */


int num2 = 22; /* 22 = 00010110 */
int result = 0;

result = num1 & num2;


[Link]("num1 & num2: "+result);

result = num1 | num2;


[Link]("num1 | num2: "+result);

result = num1 ^ num2;


[Link]("num1 ^ num2: "+result);

result = ~num1;
[Link]("~num1: "+result);

result = num1 << 2;


[Link]("num1 << 2: "+result); result = num1 >> 2;
[Link]("num1 >> 2: "+result);
}
}
7. Ternary Operator:
Ternary operator is the only operator in java that takes three operands. This operator is frequently used as a one-line
replacement for if…else statement.
Ex:
public class TernaryOperatorDemo {

public static void main(String args[]) {


int num1, num2;
num1 = 25;
/* num1 is not equal to 10 that's why
* the second value after colon is assigned
* to the variable num2
*/
num2 = (num1 == 10) ? 100: 200;
[Link]( "num2: "+num2);

/* num1 is equal to 25 that's why


* the first value is assigned
* to the variable num2
*/
num2 = (num1 == 25) ? 100: 200;
[Link]( "num2: "+num2);
}
}
8. Shift Operators:
Shift operators are used to perform bit manipulation. In this guide, we will discuss various shift operators supported
in java with the help of examples. Java supports following shift operators
Ex:
public class JavaExample {
public static void main(String[] args) {
int num = 24;

//Left shift
[Link]("num<<2: "+(num<<2));

//Right shift
[Link]("num>>2: "+(num>>2));
}
}

Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~!

Arithmetic multiplicative */%

additive +-

Shift shift << >> >>>

Relational comparison < > <= >= instance of

equality == !=

Bitwise bitwise AND &


bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ?:

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>=


>>>=

Java Control Statements:


Java compiler executes the code from top to bottom. The statements in the code are executed according to the order
in which they appear. However, Java provides statements that can be used to control the flow of Java code. Such
statements are called control flow 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
3. Jump statements
● break statement
● continue statement
1) If Statement:
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 evaluates a Boolean expression and enables the program to enter a block of code if the expression evaluates to true.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
EX:
public class Student {
public static void main (String [] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
[Link]("x + y is greater than 20");
}} }
[Link]-else statement:

The statements inside “if” would execute if the condition is true, and the statements inside “else” would execute if
the condition is false.

Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else {
statement 2; //executes when condition is false
}
EX:
public class IfElseExample {
public static void main (String args []) {
int num=120;
if (num < 50) {
[Link]("num is less than 50");
} else {
[Link]("num is greater than or equal 50");
} }}

[Link]-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:
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
}
Ex:
public class IfElseIfExample {
public static void main (String args []) {
int num=1234;
if (num <100 && num>=1) {
[Link]("It’s a two-digit number");
} else if (num <1000 && num>=100) {
[Link]("It’s a three-digit number");
} else if (num <10000 && num>=1000) {
[Link]("It’s a four-digit number");
} else if (num <100000 && num>=10000) {
[Link]("It’s a five-digit number");
} else {
[Link]("number is not between 1 & 99999");
}}}
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:
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
}}
Ex:
public class NestedIfExample {
public static void main (String args []) {
int num=70;
if (num < 100) {
[Link]("number is less than 100");
if (num > 50) {
[Link]("number is greater than 50");
}}}}

[Link] Statement:
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.
Syntax:
switch (expression) {
case value1:
statement1;
break;
.
.
case valueN:
statementN;
break;
default:
default statement;
}
EX:
public class Switchclass {
public static void main (String [] args)
{
int day = 5;
String dayString;
switch (day) {
case 1:
dayString = "Monday";
break;
case 2:
dayString = "Tuesday";
break;
case 3:
dayString = "Wednesday";
break;
case 4:
dayString = "Thursday";
break;
case 5:
dayString = "Friday";
break;
case 6:
dayString = "Saturday";
break;
case 7:
dayString = "Sunday";
break;
// Default case
default:
dayString = "Invalid day";
} [Link](dayString);
}}

[Link] statements:

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.
we have three types of loops:

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

[Link] loop:
A for loop is used to repeat a specific block of code a known number of times. The for loop is mainly used when you
know exactly how many times the loop is about to be executed i.e., with what values will it start and with what values
it will end and what will be its test condition.

Syntax:

for (initialization, condition, increment/decrement) {


//block of statements
}
EX:
class ForLoopExample {
public static void main (String args[]){
for (int i=10; i>1; i--) {
[Link]("The value of i is: "+i);
}}}

Java Nested for Loop:

If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes completely
whenever outer loop executes.
EX:
public class NestedForExample {
public static void main (String [] args) {
for (int i=1; i<=3; i++) {
for (int j=1; j<=3; j++) {
[Link](i+" "+j);
}}}}

Java for-each Loop:

The for-each loop is used to traverse array or collection in Java. It is easier to use than simple for loop because we
don't need to increment value and use subscript notation.
It works on the basis of elements and not the index. It returns element one by one in the defined variable.
EX:
public class ForEachExample {
public static void main (String [] args) {
int arr [] = {12,23,44,56,78};
for (int i: arr) {
[Link](i);
} } }
[Link] loop:
The while loop is also used to iterate over the number of statements multiple times. However, if we don't know the
number of iterations in advance, it is recommended to use a while loop.

It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If the condition is
true, then the loop body will be executed; otherwise, the statements after the loop will be executed.

Syntax:

while(condition) {
//looping statements
}
EX:
class WhileLoopExample {
public static void main (String args []) {
int i=10;
while(i>1) {
[Link](i);
i--;
}}}

[Link]-while loop:
The do-while loop checks the condition at the end of the loop after executing the loop statements. When the number
of iterations 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.
Syntax:
do
{
//statements
} while (condition);
EX:
class DoWhileLoopExample {
public static void main (String args []) {
int i=10;
do {
[Link](i);
i--;
} while(i>1);
}}

[Link] statements:

1. Java Break Statement:

The Java break statement 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.
We can use Java break statement in all types of loops such as for loop, while loop and do-while loop.
Syntax:
break;

EX:
public class BreakExample1 {
public static void main (String args []) {
int num =0;
while(num<=100)
{[Link]("Value of variable is: "+num);
if (num==2)
{break;
}num++;
} [Link]("Out of while-loop");
}}
2. Java Continue Statement:

The Java continue statement is used to continue the loop. It continues the current flow of the program and skips the
remaining code at the specified condition. In case of an inner loop, it continues the inner loop only.
We can use Java continue statement in all types of loops such as for loop, while loop and do-while loop.
Syntax:continue;
EX:
public class ContinueExample {
public static void main (String args []){
for (int j=0; j<=6; j++)
{ if (j==4)
{continue;
}
[Link](j+" ");
}}}
Java Comments:
Comments are used to stop the execution of the particular statements and also are used to provide information
explanation about variables, methods, class are any statement.
Types of Java Comments:

There are three 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 of the code. It is the widely used and easiest way of
commenting the statements
.
Single line comments start with two forward slashes (//). Any text in front of // is not executed by Java.

Syntax:
//This is single line comment
EX:
class Scomment
{
public static void main (String args [])
{
// Single line comment here
[Link]("Single line comment above");
}}

2) Java Multi Line Comment:

The multi-line comment is used to comment multiple lines of code. It can be used to explain a complex code snippet
or to comment multiple lines of code at a time (as it will be difficult to use single-line comments there).

Multi-line comments are placed between /* and */. Any text between /* and */ is not executed by Java.
Syntax:
/*
This
is
multi line
comment
*/
EX:
class Scomment
{
public static void main (String args [])
{
[Link]("Multi line comments below");
/*Comment line 1
Comment line 2
Comment line 3*/
}}
3) Java Documentation Comment:
Documentation comments are usually used to write large programs for a project or software application as it helps to
create documentation API. These APIs are needed for reference, i.e., which classes, methods, arguments, etc., are used
in the code.
To create documentation API, we need to use the Javadoc tool. The documentation comments are placed between
/** and */.

Syntax:
/**
*
*We can use various tags to depict the parameter
*Or heading or author name
*We can also use HTML tags
*
*/
EX:
/**
*This method is used to add two numbers
*@author I hub
*@param x, y
*@return integer value
*/

Java Arrays:

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.

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.
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 Arrays in java:


There are two types of arrays.

● Single Dimensional Array


● Multidimensional Array

Single Dimensional Array:

Syntax:
type var-name [];
OR
type [] var-name;

EX:
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;
for(int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
}}

Multidimensional Array:

Multidimensional arrays are arrays of arrays with each element of the array holding the reference of other arrays.
These are also known as Jagged Arrays. A multidimensional array is created by appending one set of square
brackets ([]) per dimension.
Syntax:
data type [][] arrayrefvaribale;
or
datatype arrayrefvariable[][];
EX:
public class multiDimensional {
public static void main (String args [])
{
// declaring and initializing 2D array
int arr[][]
= {{2, 7, 9}, {3, 6, 1}, {7, 4, 2}};

// printing 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
[Link](arr[i][j] + " ");

[Link]();
}}}

Difference between Static and Non-Static method:

Static Non-static
A variable are method declare with a keyword A variable are method declare without any
static is a Static variable/method Static keyword is called a non-Static
variable/method
A static variable and static method can be used A Non-static method/variable can be used
directly in a static method with in the class. directly in a non-static method
A Non-static method/variable can’t be used
directly in a static method. They can be access
by creating a reference of the class.
Memory allocation for non-static
Memory allocation for static variable/method
variable/method is instance specific when ever
happens only one when the class is loaded in
and instance for the class is created the
the memory.
memory will be allocated.
Java OOPs Concepts:

Object-oriented programming System (OOPs) is a programming concept that is based on “objects”. The primary
purpose of object-oriented programming is to increase the readability, flexibility and maintainability of programs.

Popular programming languages that supports object oriented programming are: Java, C++, Python, C#, Perl,
JavaScript, Ruby, and Smalltalk etc.

What is OOPs Concepts in Java?

OOPs concepts include following Object oriented programming concepts:

● Object
● Class
● Abstraction
● Encapsulation
● Inheritance
● Polymorphism

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.

Let’s take few more examples of Objects:


Examples of states and behaviors
Example 1:
Class: House
State: address, color, area
Behavior: Open door, close door

The difference between state and behavior. The state of an object is a data item that can be represented in value
such as price of house, color, area; consider them as variables in programming. The behavior is like a method of the
class such as opendoor, closedoor, it is a group of actions that together can perform a task.
class House {
String address;
String color;
double area;
void openDoor() {
//Write code here
}
void closeDoor() {
//Write code here
}
...
...
}
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.

For example in the above given example House is considered as the CLASS.

Inheritance:

Acquiring the properties of a parent class by a child class by using keyword EXTENDS is called INHERITNCE

✔ Inheritance provides the idea of reusability of code and each sub class defines only those features that are
unique to it, rest of the features can be inherited from the parent class.

✔ The parent class is called the base class or super class. The child class that extends the base class is
called the derived class or sub class or child class.

✔ The biggest advantage of Inheritance is that the code in base class need not be rewritten in the child class.
The variables and methods of the base class can be used in the child class as well.

✔ Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and
methods of the existing class when you create a new class. You can use the same fields and methods already
defined in the previous class.

SYNTAX:
class A extends B
{
}

Ex:
class Teacher {
String designation = "Teacher";
String college = "Ihub";
void does() {
[Link]("Teaching");
}
}
public class TestingTeacher extends Teacher {
String main Subject = "Testing";
public static void main(String args[]) {
TestingTeacher obj = new TestingTeacher();
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]();
}
}
Types of inheritance in java:
● Single Inheritance
● Multilevel Inheritance
● Hierarchical Inheritance
● Multiple Inheritance
● Hybrid Inheritance

Single Inheritance:

Single inheritance refers to a child and parent class relationship where a class extends the another class.

Ex:

Multilevel Inheritance:
Multilevel inheritance refers to a child and parent class relationship where a class extends the child class. For
example class A extends class B and class B extends class C.
Ex;

Hierarchical Inheritance:

Hierarchical inheritance refers to a child and parent class relationship where more than one classes extends the same
class. For example, class B extends from class A and class C extends from class A.

EX:
Multiple Inheritance: Multiple inheritance refers to the concept of one class extending more than one classes,
which means a child class has two parent classes. Java doesn’t support multiple inheritance.
✔ Most of the new Oops languages like Small Talk, Java, C# do not support Multiple inheritance. Multiple
Inheritance is supported in C++.
Ex:

Hybrid Inheritance:
A hybrid inheritance is a combination of more than one types of inheritance. For example when class A and B
extends class C & another class D extends class A then this is a hybrid inheritance, because it is a combination of
single and hierarchical inheritance.

✔ It also provides the code reusability. The hybrid inheritance can be achieved by using the following
combinations:
● Single and Multiple Inheritance (not supported but can be achieved through interface)
● Multilevel and Hierarchical Inheritance
● Hierarchical and Single Inheritance
● Multiple and Multilevel Inheritance

Ex:
Polymorphism:

Polymorphism is a object oriented programming feature that allows us to perform a single action in different ways.
There are two types of Polymorphism
1. Run-time Polymorphism
2. Compile time Polymorphism
✔ In java we can achieve polymorphism by METHOD OVERLOADING, METHOD OVERRIDING.
For example, let’s say we have a class Animal that has a method animalSound(), here we cannot give
implementation to this method as we do not know which Animal class would extend Animal class. So, we make this
method abstract like this

EX: class Animal {


public void animalSound() {
[Link]("The animal makes a sound");
}
}
class Pig extends Animal {
public void animalSound() {
[Link]("The pig says: wee wee");
}
}
class Dog extends Animal {
public void animalSound() {
[Link]("The dog says: bow wow");
}
}
class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
[Link]();
[Link]();
[Link]();
}
}

Method Overloading:
If a class has multiple methods having same but different in parameters
(Or)
A method with same name or different number of parameters or type parameters with in the class is known as
Method Overloading.
Ex:
class Adder{
static int add(int a,int b) {
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1{
public static void main(String[] args) {
[Link]([Link](11,11));
[Link]([Link](11,11,11));
}
}

Method Overriding:
If subclass (child class) has the same method as declared in the parent class is known as Method
Overriding
(or)
Method with same name and same number or type of parameters of parent class is overridden in the child
class.
Usage of Java Method Overriding:
● Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
● Method overriding is used for runtime polymorphism

Ex:
class Vehicle {
void run() {
[Link]("Vehicle is running");
}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]) {
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
[Link]();
}
}

Abstraction:

Abstraction is a process of hiding the implementation details and showing only functionality to the user.
(Or)
Another way, it shows only essential things to the user and hides the internal details, For example, when you login to
your Amazon account online, you enter your user_id and password and press login, what happens when you press
login, how the input data sent to amazon server, how it gets verified is all abstracted away from the you.

Abstract class:
● An abstract class must be declared with an abstract keyword.
● It can have abstract and non-abstract methods.(method with the body)
● It cannot be instantiated.
● It can have constructors and static methods also.
● It can have final methods which will force the subclass not to change the body of the method.
● We can use 0 to 100% abstraction by using abstract class.

Ex:

//abstract class
abstract class Animal{
//abstract method
public abstract void animalSound();
}
public class Dog extends Animal{

public void animalSound() {


[Link]("Woof");
}
public static void main(String args[]) {
Animal obj = new Dog();
[Link]();
}
}

Encapsulation:
Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a capsule which
is mixed of several medicines.
Ex:

● Make the instance variables private so that they cannot be accessed directly from outside the class. You can
only set and get values of these variables through the methods of the class.
● Have getter and setter methods in the class to set and get the values of the fields.

class EmployeeCount
{
private int numOfEmployees = 0;
public void setNoOfEmployees (int count)
{
numOfEmployees = count;
}
public double getNoOfEmployees ()
{
return numOfEmployees;
}
}
public class EncapsulationExample
{
public static void main(String args[])
{
EmployeeCount obj = new EmployeeCount ();
[Link](5613);
[Link]("No Of Employees: "+(int)[Link]());
}
}

Interface:
An interface in Java is a blueprint of a class. All the methods of a interface are the abstract methods by default the
variables declared and initialized in an interface are public, static and final. It has static constants and abstract methods .
● All the methods in an interface are implemented in the implemented class by using keyword implements
● We cannot instantiate an interface.
● By using interface we can achieve 100% abstraction in java.
● Multiple Inheritance is only possible through Interfaces.
Ex:
interface printable {
void print();
}
class A6 implements printable {
public void print() {
[Link]("Hello"); }

public static void main(String args[]) {


A6 obj = new A6();
[Link]();
}
}

Access Modifiers in Java:

There are four types of Java access modifiers:

1. Private
2. Default
3. Protected
4. Public
[Link]:

A variable is a method declared as private in a class can be access with in the class only. That is, it cannot be
accessed with in the package outside the package subclass and outside the package.

EX:

class NUMBERS {
private double num = 100;
private int square (int x) {
return x*x;
}}
public class Test {
public static void main (String args []) {
NUMBERS obj = new NUMBERS ();
[Link]([Link]);
[Link](ob. Square (5));
}}

[Link]:

A variable is method without any keyword like public, private, protected is a default access modifier. It can be
accessed with in the class, with in the package only.

EX:

package default Package;


class MyClass {
public static void main (String [] args) {
[Link](“Hello World”);
}}

[Link]:
A variable is method declare as a protected can be access with in the class, with in the package outside the package
subclass only.
EX:
package j1;
public class A
{
protected void display ()
{
[Link](“Jigsaw Academy”);
}}

package j2;
import j1. *;
class B extends A
{
public static void main (String args [])
{
B obj = new B ();
obj. display ();
}}
[Link]:
A variable is a Method which is declare as a public can be access any ware in the project. That is with in the class,
with in the package, outside the package subclass only and outside package.
EX:
package s1;
public class A
{
public void display ()
{
[Link](“Jigsaw Academy”);
}}

package s2;
import s1. *;
class B
{
public static void main (String args [])
{
A obj = new A;
obj. display ();
}}

Access Modifier within class within package outside package by subclass only outside package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

Constructors in Java:
● Constructor is a special method which has same name as class name and doesn’t have any return type.
● Constructors are used to initialize the objects
● Constructors are invoke (called) whenever there is an instance of a class is created.
● If there is no constructor declared in a class the java complier by default will create a default constructor
● There are two types of Constructors:
1. Default Constructor
2. Parameterized Constructor.
● A constructor must have no explicit return type
● A java Constructor cannot be abstract, static, final and synchronized.
● Constructors can be overloaded.
Example of default constructor:

//Java Program to create and call a default constructor


class Bike1{
//creating a default constructor
Bike1() {
[Link]("Bike is created");
}
//main method
public static void main(String args[]) {
//calling a default constructor
Bike1 b=new Bike1();
}
}

Example of parameterized 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() {
[Link](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
[Link]();
[Link]();
}
}
Strings in Java:

String is basically an object that represents sequence of char values. An array of characters works same as Java string.
For example:

char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);

Is same as:

String s="javatpoint";

✔ Java String class provides a lot of methods to perform operations on strings such as compare(), concat(),
equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

CharSequence Interface:

The CharSequence interface is used to represent the sequence of characters.


String, StringBuffer and StringBuilder classes implement it. It means, we can create strings in Java by using these
three classes.

The Java String is immutable which means it cannot be changed. Whenever we change any string, a new instance
is created. For mutable strings, you can use StringBuffer and StringBuilder classes.

StringBuffer:

Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer class in Java is the
same as String class except it is mutable i.e. it can be changed.
✔ Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it is safe and
will result in an order.

StringBuilder:
Java StringBuilder class is used to create mutable (modifiable) String. The Java StringBuilder class is same as
StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.

Methods Description

contains() checks whether the string contains a substring


substring() returns the substring of the string

join() join the given strings using the delimiter

replace() replaces the specified old character with the specified new character

replaceAll() replaces all substrings matching the regex pattern

replaceFirst() replace the first matching substring

charAt() returns the character present in the specified location

getBytes() converts the string to an array of bytes

indexOf() returns the position of the specified character in the string

compareTo() compares two strings in the dictionary order

compareToIgnoreCase() compares two strings ignoring case differences

trim() removes any leading and trailing whitespaces

format() returns a formatted string

split() breaks the string into an array of strings

toLowerCase() converts the string to lowercase

toUpperCase() converts the string to uppercase

valueOf() returns the string representation of the specified argument

toCharArray() converts the string to a char array

matches() checks whether the string matches the given regex

startsWith() checks if the string begins with the given string

endsWith() checks if the string ends with the given string

isEmpty() checks whether a string is empty of not


intern() returns the canonical representation of the string

contentEquals() checks whether the string is equal to charSequence

hashCode() returns a hash code for the string

subSequence() returns a subsequence from the string

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

// create strings
String first = "Java";
String second = "Python";
String third = "JavaScript";

// print strings
[Link](first); // print Java
[Link](second); // print Python
[Link](third); // print JavaScript
}
}

Collections in Java
The Collection in Java is a framework that provides an architecture to store and manipulate the group of objects. A
Collection represents a single unit of objects, i.e., a group.

Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion,
manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue,
Deque) and classes (Array List, Vector, Linked List, Priority Queue, HashSet, Linked HashSet, Tree Set).
List Interface
List interface is the child interface of Collection interface. It inhibits a list type data structure in which we can store
the ordered collection of objects. It can have duplicate values.
List interface is implemented by the classes Array List, LinkedList, Vector, and Stack.

Array List
The Array List class implements the List interface. It uses a dynamic array to store the duplicate element of different
data types. The Array List class maintains the insertion order and is non-synchronized. The elements stored in the
Array List class can be randomly accessed. Consider the following example.

Ex:
import [Link].*;
class JavaExample{
public static void main(String args[]){
//creating ArrayList of string type
ArrayList<String> arrList=new ArrayList<>();

//adding few elements


[Link]("Cricket"); //list: ["Cricket"]
[Link]("Hockey"); //list: ["Cricket", "Hockey"]

//inserting element at first position, index 0


//represents first element because ArrayList is based
//on zero based indexing system
[Link](0, "BasketBall"); //list: ["BasketBall", "Cricket", "Hockey"]

[Link]("ArrayList Elements: ");


//Traversing ArrayList using enhanced for loop
for(String str:arrList)
[Link](str);
}
}

LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally to store the elements. It can store
the duplicate elements. It maintains the insertion order and is not synchronized. In LinkedList, the manipulation is fast
because no shifting is required.

Ex:
import [Link].*;
public class JavaExample{
public static void main(String args[]){
LinkedList<String> linkList=new LinkedList<>();
[Link]("Apple"); //["Apple"]
[Link]("Orange"); //["Apple", "Orange"]

//inserting element at first position


[Link](0, "Banana"); ////["Banana", "Apple", "Orange"]

[Link]("LinkedList elements: ");


//iterating LinkedList using iterator
Iterator<String> it=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
Set:
Set Interface in Java is present in [Link] package. It extends the Collection interface. It represents the unordered set
of elements which doesn't allow us to store the duplicate items. We can store at most one null value in Set. Set is
implemented by HashSet, LinkedHashSet, and Tree Set.

Tree Set:
Tree Set stores elements in a red-black tree. It is substantially slower than HashSet. Tree Set class implements Sorted
Set interface, which allows Tree Set to order its elements based on their values, which means Tree Set elements are
sorted in ascending order.

Ex:
import [Link].*;
public class JavaExample{
public static void main(String args[]){
TreeSet<String> set=new TreeSet<>();
[Link]("Paul");
[Link]("Ram");
[Link]("Aaron");
[Link]("Leo");
[Link]("Becky");

Iterator<String> it=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}

HashSet
HashSet class implements Set Interface. It represents the collection that uses a hash table for storage. Hashing is used
to store the elements in the HashSet. It contains unique items.

Ex:
import [Link].*;
public class JavaExample{
public static void main(String args[]){
HashSet<String> set=new HashSet<>();
[Link]("Paul");
[Link]("Ram");
[Link]("Aaron");
[Link]("Leo");
[Link]("Becky");

Iterator<String> it=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
LinkedHashSet:
LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends the HashSet class and
implements Set interface. Like HashSet, it also contains unique elements. It maintains the insertion order and permits
null elements.

Ex:
import [Link].*;
public class JavaExample{
public static void main(String args[]){
LinkedHashSet<String> set=new LinkedHashSet<>();
[Link]("Paul");
[Link]("Ram");
[Link]("Aaron");
[Link]("Leo");
[Link]("Becky");

Iterator<String> it=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
Map:
A map contains values on the basis of key, i.e., key and value pair. Each key and value pair is known as an entry. A
Map contains unique keys.
A Map is useful if you have to search, update or delete elements on the basis of a key.
HashMap:
Java HashMap class implements the Map interface which allows us to store key and value pair, where keys should
be unique. If you try to insert the duplicate key, it will replace the element of the corresponding key. It is easy to
perform operations using the key index like updating, deletion, etc. HashMap class is found in the [Link] package.

HashMap in Java is like the legacy Hash table class, but it is not synchronized. It allows us to store the null elements
as well, but there should be only one null key. Since Java 5, it is denoted as HashMap<K, V>, where K stands for key
and V for value. It inherits the Abstract Map class and implements the Map interface.

Ex:
import [Link].*;
public class JavaExample{
public static void main(String args[]){
HashMap<Integer, String> hmap = new HashMap<>();

//key and value pairs


[Link](101, "Chaitanya");
[Link](105, "Derick");
[Link](111, "Logan");
[Link](120, "Paul");

//print HashMap elements


Set set = [Link]();
Iterator iterator = [Link]();
while([Link]()) {
[Link] m = ([Link])[Link]();
[Link]("key is: "+ [Link]() + " & Value is: ");
[Link]([Link]());
}
}
}

HashMap class:
Java Linked HashMap class is Hash table and Linked list implementation of the Map interface, with predictable
iteration order. It inherits HashMap class and implements the Map interface.
● Java Linked HashMap contains values based on the key.
● Java Linked HashMap contains unique elements.
● Java Linked HashMap may have one null key and multiple null values.
● Java Linked HashMap is non synchronized.
● Java Linked HashMap maintains insertion order.

Ex:
import [Link].*;
public class JavaExample{
public static void main(String args[]){
LinkedHashMap<Integer, String> hmap = new LinkedHashMap<>();

//key and value pairs


[Link](100, "Chaitanya");
[Link](120, "Paul");
[Link](105, "Derick");
[Link](111, "Logan");

//print LinkedHashMap elements


Set set = [Link]();
Iterator iterator = [Link]();
while([Link]()) {
[Link] m = ([Link])[Link]();
[Link]("key is: "+ [Link]() + " & Value is: ");
[Link]([Link]());
}
}
}

Exception Handling in Java:

Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException,


SQLException, RemoteException, etc.

Exception:

Exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
Types of Java Exceptions:
There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked exception.
However, according to Oracle, there are three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error

1) Checked Exception:
The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked
exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at compile-
time.
2) Unchecked Exception:
The classes that inherit the Runtime Exception are known as unchecked exceptions. For example, Arithmetic
Exception, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
3) Error:
Error is irrecoverable. Some examples of errors are OutOfMemoryError, VirtualMachineError, Assertion Error etc.

Java Exception Keywords:

Java provides five keywords that are used to handle the exception. The following table describes each.

Keyword Description

try The "try" keyword is used to specify a block where we should place an exception code. It means we can't use try
block alone. The try block must be followed by either catch or finally.

catch The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use
catch block alone. It can be followed by finally block later.

finally The "finally" block is used to execute the necessary code of the program. It is executed whether an exception is
handled or not.

throw The "throw" keyword is used to throw an exception.


throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method.
It doesn't throw an exception. It is always used with method signature.

Example:
public class JavaExceptionExample{
public static void main (String args []) {
try {
int data=100/0;
} catch (Arithmetic Exception e){[Link](e);
}
[Link]("rest of the code...");
} }

You might also like