java pdf
java pdf
INTRODUCTION
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
3. Robust:- Java is robust as it is capable of handling run-time errors, supports automatic
garbage collection and exception handling, and avoids explicit pointer concept.
4. 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 provide security. Any machine with Java Runtime Environment can run Java
Programs.
5. Secure:- Java is a more secure language as compared to C/C++, as it does not allow a
programmer to explicitly create pointers. Thus in Java, we can not gain access to a
particular variable if we do not initialize it properly. Programs run in a virtual machine
sandbox – A separate environment that allows users to execute their applications without
affecting the underlying system.
6. Architectural Neutral:- The program written on one platform or OS is independent of other
platforms or environments and can run on any other Operating System without recompiling
them. In other words, it is based on the ‘Write-once-run-anywhere’ (WORA) or ‘Write-once-
run-everywhere’ (WORE) approach.
9. Portable:- Java is portable because it facilitates you to carry the Java bytecode to any
platform. It doesn't require any implementation.
10. 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.
11. 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++.
Java OOPs Concepts:-
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.
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.
In Java, we use method overloading and method overriding to achieve polymorphism. 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.
3) OOPs provides the ability to simulate real-world event much more effectively. We can
provide the solution of real word problem if we are using the Object-Oriented Programming
language.
Object-based programming language follows all the features of OOPs except Inheritance.
JavaScript and VBScript are examples of object-based programming languages.
Java Virtual Machine:-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.
JVM, JRE, and JDK are platform dependent because the configuration of each OS is different
from each other.
The JVM performs the following main tasks:
Loads code
Verifies code
Executes code
Provides runtime environment
Java Runtime Environment:- 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
contains a set of libraries + other files that JVM uses at runtime.
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. The JDK contains a private Java Virtual Machine (JVM) and
a few other resources such as an interpreter/loader (java), a compiler (javac), an archiver (jar), a
documentation generator (Javadoc), etc. to complete the development of a Java Application.
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.
Types of Variables
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.
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.
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
Boolean Data Type:- 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.
Example: boolean one = false
Byte Data Type:- The byte data type is an example of primitive data type. It isan 8-bit signed
two's complement integer. Its value-range lies between -128 to 127 (inclusive). Its minimum
value is -128 and maximum value is 127. Its default value is 0.
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.
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 default value is
0.
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).
Float Data Type:- The float data type is a single-precision 32-bit IEEE 754 floating point. Its
default value is 0.0F.
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. Its default value is 0.0d.
Operators in Java:- Operator in Java is a symbol that is used to perform operations. For
example: +, -, *, / etc. There are many types of operators in Java which are given below:
Unary Operator,
Arithmetic Operator,
Shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator,
Assignment Operator.
additive +-
equality == !=
Bitwise bitwise AND &
bitwise exclusive ^
OR
bitwise inclusive OR |
logical OR ||
Ternary ternary ?:
Java Unary Operator:- The Java unary operators require only one operand. Unary operators are
used to perform various operations i.e.:
incrementing/decrementing a value by one
negating an expression
inverting the value of a boolean
Java Unary Operator Example: ++ and --
public class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);
System.out.println(++x);
System.out.println(x--);
System.out.println(--x);
}}
Output:
10
12
12
10
Example:-
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);
System.out.println(a-b);
System.out.println(a*b);
System.out.println(a/b);
System.out.println(a%b);
}}
Java Relational Operators:- Relational operators are used to check the relationship between
two operands. For example,
Example:-
class Main {
public static void main(String[] args) {
int a = 7, b = 11;
System.out.println("a is " + a + " and b is " + b);
System.out.println(a == b);
System.out.println(a != b);
System.out.println(a > b);
System.out.println(a < b);
System.out.println(a >= b);
System.out.println(a <= b);
}}
Logical Operators:- Logical operators are used to check whether an expression is true or false.
They are used in decision making.
Output:-
Is str an object of String? true
Java Ternary Operator:- The ternary operator (conditional operator) is shorthand for the if-
then-else statement. For example,
If the Expression is true, expression1 is assigned to the variable. If the Expression is false,
expression2 is assigned to the variable.
Example:-
class Java {
public static void main(String[] args) {
int februaryDays = 29;
String result;
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
System.out.println(result);
}}
Java Type Casting:- Type casting is when you assign a value of one primitive data type to
another type. In Java, there are two types of casting:
o Widening casting
o Narrowing casting
byte -> short -> char -> int -> long -> float -> double
double -> float -> long -> int -> char -> short -> byte
Widening Casting:- Widening casting is done automatically when passing a smaller size type to
a larger size type:
Example:-
public class Main {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt);
System.out.println(myDouble);
}}
Narrowing Casting:-Narrowing casting must be done manually by placing the type in
parentheses in front of the value
Example:-
public class Main {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Explicit casting: double to int
System.out.println(myDouble);
System.out.println(myInt);
}}
Java Arrays:- Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value. To declare an array, define the variable type with square
brackets: For example,
String[] cars;
To insert values to it, we can use an array literal - place the values in a comma-separated list,
inside curly braces:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
To create an array of integers, you could write:
int[] myNum = {10, 20, 30, 40};
Access the Elements of an Array:- You access an array element by referring to the index
number.
Example:-
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
}}
Change an Array Element:- To change the value of a specific element, refer to the index
number.
Example:- cars[0] = "Opel";
Example:-
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
}}
Array Length:- To find out how many elements an array has, use the length property.
Example:-
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
}}
Loop Through an Array:- You can loop through the array elements with the for loop, and use
the length property to specify how many times the loop should run.
Example:-
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
} }}
Loop Through an Array with For-Each:- There is also a "for-each" loop, which is used
exclusively to loop through elements in arrays.
Syntax:-
for (type variable : arrayname)
{
...
}
Example:-
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
} }}
Example:-
public class TestArray
{
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
for (double element: myList)
{
System.out.println(element);
} }}
Output:-
1.9
2.9
3.4
3.5
Binary search example:-
class BinarySearchExample
{
public static void binarySearch(int arr[], int first, int last, int key)
{
int mid = (first + last)/2;
while( first <= last )
{
if ( arr[mid] < key ){
first = mid + 1;
}
else if ( arr[mid] == key )
{
System.out.println("Element is found at index: " + mid);
break;
}
Else
{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last )
{
System.out.println("Element is not found!");
}
}
public static void main(String args[])
{
int arr[] = {10,20,30,40,50};
int key = 30;
int last=arr.length-1;
binarySearch(arr,0,last,key);
} }
Example:-
public class TestArray
{
public static void main(String[] args)
{
double[] myList = {1.9, 2.9, 3.4, 3.5};
for (int i = 0; i < myList.length; i++)
{
System.out.println(myList[i] + " ");
}
double total = 0;
for (int i = 0; i < myList.length; i++)
{
total += myList[i];
}
System.out.println("Total is " + total);
double max = myList[0];
for (int i = 1; i < myList.length; i++)
{
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}}
Output:-
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
Java program to demonstrate passing of array to method
class Test
{
public static void main(String args[])
{
int arr[] = {3, 1, 2, 5, 4};
sum(arr);
}
public static void sum(int[] arr)
{
int sum = 0;
for (int i = 0; i < arr.length; i++)
sum+=arr[i];
System.out.println("sum of array values : " + sum);
}}
Output :
sum of array values : 15
Program:-
public class Main {
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
int x = myNumbers[1][2];
System.out.println(x);
}}
Program:-
public class Main {
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; ++i)
{
for(int j = 0; j < myNumbers[i].length; ++j)
{
System.out.println(myNumbers[i][j]);
} } }}
Conditional Statements:-
Syntax:-
if (condition)
Example:-
} }}
The else Statement:- Use the else statement to specify a block of code to be executed if the
condition is false.
Syntax:-
if (condition) {
} else {
Example:-
public class Main {
public static void main(String[] args) {
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
} }}
The else if Statement:-Use the else if statement to specify a new condition if the first condition
is false.
Syntax:-
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Example:-
public class Main {
public static void main(String[] args) {
int time = 22;
if (time < 10) {
System.out.println("Good morning.");
} else if (time < 20) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
} }}
Java Switch:- Use the switch statement to select one of many code blocks to be executed.
Syntax:-
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Example:-
public class Main {
public static void main(String[] args) {
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
} }}
While Loop:-The while loop loops through a block of code as long as a specified condition is
true.
Syntax:-
while (condition) {
Example:-
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
} }}
The Do/While Loop:-The do/while loop is a variant of the while loop. This loop will execute
the code block once, before checking if the condition is true, then it will repeat the loop as long
as the condition is true.
Syntax:-
do {
// code block to be executed
}while (condition);
Example:-
public class Main {
public static void main(String[] args) {
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
}}
For Loop:- When you know exactly how many times you want to loop through a block of code,
use the for loop instead of a while loop.
Syntax:-
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
Example:-
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i);
} }}
For-Each Loop:-There is also a "for-each" loop, which is used exclusively to loop through
elements in an array.
Syntax:-
Example:-
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
} }}
break:-You have already seen the break statement used in an earlier chapter of this tutorial. It
was used to "jump out" of a switch statement.The break statement can also be used to jump out
of a loop.
Example:-This example stops the loop when i is equal to 4.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
} }}
continue:- The continue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop.
Example:-
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
} }}
Methods:- A method is a block of code which only runs when it is called. You can pass data,
known as parameters, into a method. Methods are used to perform certain actions, and they are
also known as functions.
Modifier-: Defines 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: accessible in all classes in your application.
protected: accessible within the class in which it is defined and in its subclass(es)
private: accessible only within the class in which it is defined.
default (declared/defined without using any modifier): accessible within the same class and
package within which its class is defined.
The return type: The data type of the value returned by the method or void if does not return a
value.
Method Name: the rules for field names apply to method names as well, but the convention is a
little different.
Parameter list: Comma separated list of the input parameters are defined, preceded with their
data type, within the enclosed parenthesis. If there are no parameters, you must use empty
parentheses ().
Exception list: The exceptions you expect by the method can throw, you can specify these
exception(s).
Method body: it is enclosed between braces. The code you need to be executed to perform your
intended operations.
Example:-
import java.io.*;
class Addition {
int sum = 0;
public int addTwoInt(int a, int b)
{
sum = a + b;
return sum;
}}
class GFG {
public static void main (String[] args)
{
Addition add = new Addition();
int s = add.addTwoInt(1,2);
System.out.println("Sum of two integer values :"+ s);
}}
Example:-
public class ExampleMinNumber {
public static void main(String[] args) {
int a = 11;
int b = 6;
int c = minFunction(a, b);
System.out.println("Minimum Value = " + c);
}
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}}
Passing Parameters by Value to method:- While working under calling process, arguments is
to be passed. These should be in the same order as their respective parameters in the method
specification. Parameters can be passed by value or by reference.
Example:-
public class swappingExample {
public static void main(String[] args) {
int a = 30;
int b = 45;
System.out.println("Before swapping, a = " + a + " and b = " + b);
swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping values will be same here**:");
System.out.println("After swapping, a = " + a + " and b is " + b);
}
public static void swapFunction(int a, int b) {
System.out.println("Before swapping(Inside), a = " + a + " b = " + b);
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + " b = " + b);
}}
Example:-
else {
System.out.println("Access granted - You are old enough!");
} }
m.checkAge(20);
}}
Return Value from method:-
return 5 + x;
System.out.println(m.myMethod(3));
}}
class Factorial {
if (n != 0) // termination condition
else
return 1;
result = factorial(number);
}}
Method Overloading:- With method overloading, multiple methods can have the same name
with different parameters.
Three ways to overload a method. In order to overload a method, the argument lists of the
methods must differ in either of these:
1. Number of parameters.
add(int, int)
For example:
add(int, int)
add(int, float)
For example:
add(int, float)
add(float, int)
When I say argument list, I am not talking about return type of the method, for example if two
methods have same name, same parameters and have different return type, then this is not a valid
method overloading example. This will throw compilation error.
System.out.println(c);
}}
class Sample
obj.disp('a');
obj.disp('a',10);
}}
Output:-
a 10
System.out.println(c);
System.out.println(c );
}}
class Sample2
obj.disp('a');
obj.disp(5);
}}
Output:-
class Sample3
obj.disp('x', 51 );
obj.disp(52, 'y');
}}
Output:-
When a data type of smaller size is promoted to the data type of bigger size than this is called
type promotion, for example: byte data type can be promoted to short, a short data type can be
promoted to int, long, double etc.
The data type on the left side can be promoted to the any of the data type present in the right side
of it.
float → double
Example:-
class Demo{
System.out.println("Method A");
System.out.println("Method B");
obj.disp(100, 20.67f);
}}
Output:
Method A
As you can see that I have passed the float value while calling the disp() method but it got
promoted to the double type as there wasn’t any method with argument list as (int, float).
class Demo{
System.out.println("Method A");
System.out.println("Method B");
System.out.println("Method C");
/* This time promotion won't happen as there isa method with arg list as (int, float)
*/
obj.disp(100, 20.67f);
}}
Output:Method C
Case 1:
Result: Compile time error. Argument lists are exactly same. Both methods are having same
number, data types and same sequence of data types.
Case 2:
Result: Perfectly fine. Valid case of overloading. Here data types of arguments are different.
Case 3:
Result: Perfectly fine. Valid case of overloading. Here number of arguments are different.
Case 4:
Result: Perfectly fine. Valid case of overloading. Sequence of the data types of parameters are
different, first method is having (int, float) and second is having (float, int).
Case 5:
Result: Compile time error. Argument lists are exactly same. Even though return type of methods
are different, it is not a valid case. Since return type of method doesn’t matter while overloading
a method.
Constructors:-
Constructor is a block of code that initializes the newly created object. A constructor resembles
an instance method in java but it’s not a method as it doesn’t have a return type. In short
constructor and method are different. Constructor has same name as the class and looks like this
in a java code.
MyClass()
..
Constructor(s) of a class must have the same name as the class name in which it resides.
A constructor in Java can not be abstract, final, static and Synchronized.
Access modifiers can be used in constructor declaration to control its access i.e which
other class can call the constructor.
When we create the object of MyClass like this:
MyClass obj = new MyClass()
The new keyword here creates the object of class MyClass and invokes the constructor to
initialize this newly created object.
Constructor Vs Method:-
Constructor Method
<class_name>(){}
Rule: If there is no constructor in a class, compiler automatically creates a default constructor.
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.
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
} }
Example of default constructor that displays the default values
class Student3{
int id;
String name;
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
} }
Java Parameterized Constructor
A constructor which has a specific number of parameters is called a 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
class Student4{
int id;
String name;
Student4(int i,String n)
id = i;
name = n;
void display()
System.out.println(id+" "+name);
s1.display();
s2.display();
} }
class Example2
//default constructor
public Example2()
var = 10;
//parameterized constructor
var = num;
return var;
}}
Constructor Chaining:- When a constructor calls another constructor of same class then this is
called constructor chaining.
Constructor Overloading:-
Java Constructor overloading is a technique in which a class can have any number of
constructors that differ in parameter list. The compiler differentiates these constructors by taking
into account the number of parameters in the list and their type.
Examples of valid constructors for class Account are
Account(int a);
Account (int a,int b);
Account (String a,int b);
Example:-
class Box
{
width = w;
height = h;
depth = d;
Box()
Box(double len)
double volume()
}}
double vol;
vol = mybox1.volume();
vol = mybox2.volume();
vol = mycube.volume();
}}
Static Keyword:-
static keyword is mainly used for memory management. It can be used with variables, methods,
blocks and nested classes. It is a keyword which is used to share the same variable or method of
a given class.In order to create a static member (block, variable, method, nested class), you need
to precede its declaration with the keyword static. When a member of the class is declared as
static, it can be accessed before the objects of its class are created, and without any object
reference.
In Java programming language, static keyword is a non-access modifier and can be used for the
following:
Static Block
Static Variable
Static Method
Static Classes
Static Block:- If you need to do the computation in order to initialize your static variables, you
can declare a static block that gets executed exactly once, when the class is first loaded.
Example:-
import java.util.*;
static int n;
static
n = j * 8;
System.out.println("Value of j : "+j);
System.out.println("Value of n : "+n);
}}
Output:
Value of j:10
Value of n : 80
Static Variable:- When you declare a variable as static, then a single copy of the variable is
created and divided among all objects at the class level. Static variables are, essentially, global
variables. Basically, all the instances of the class share the same static variable. Static variables
can be created at class-level only.
Example:-
import java.util.*;
static {
System.out.println("from n ");
return 20;
System.out.println("Value of j : "+j);
}}
Output:
from n
Value of j: 20
Static Methods:- When a method is declared with the static keyword, it is known as a static
method. The most common example of a static method is the main( ) method. Methods declared
as static can have the following restrictions:
// static variable
// instance variable
int n = 200;
// static method
a = 200;
// Cannot make a static reference to the non-static method a2() from the type Test
// instance method
void a2()
System.out.println("Inside a2");
{
// main method
}}
Static Class:- A class can be made static only if it is a nested class. Nested static class doesn’t
need a reference of Outer class. In this case, a static class cannot access non-static members of
the Outer class.
Example:-
class JavaExample{
//Static class
//non-static method
*/
System.out.println(str);
} }
* class instance but for a regular nested class you would need
*/
}}
Output:-
BeginnersBook
this keyword:-In Java, this is a keyword which is used to refer current object of a class. we can
it to refer any member of the class. It means we can access any instance variable and method by
using this keyword.
this can be used to return the current class instance from the method.
If there is ambiguity between the instance variables and parameters, this keyword resolves the
problem of ambiguity.
Let's understand the problem if we don't use this keyword by the example given below:
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
class TestThis1{
s1.display();
s2.display();
}}
Output:
0 null 0.0
0 null 0.0
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
class TestThis2{
s1.display();
s2.display();
}}
Output:
If local variables(formal arguments) and instance variables are different, there is no need to use
this keyword like in the following program:
class Student{
int rollno;
String name;
float fee;
rollno=r;
name=n;
fee=f;
class TestThis3{
s1.display();
s2.display();
}}
You may invoke the method of the current class by using the this keyword. If you don't use the
this keyword, compiler automatically adds this keyword while invoking the method.
class A{
void n(){
System.out.println("hello n");
this.m();
} }
class TestThis4{
A a=new A();
a.n();
}}
The this() constructor call can be used to invoke the current class constructor. It is used to reuse
the constructor. In other words, it is used for constructor chaining.
class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
} }
class TestThis5{
A a=new A(10);
}}
class A{
A(){
this(5);
System.out.println("hello a");
A(int x){
System.out.println(x);
} }
class TestThis6{
A a=new A();
}}
int rollno;
String name,course;
float fee;
this.rollno=rollno;
this.name=name;
this.course=course;
this(rollno,name,course);//reusing constructor
this.fee=fee;
class TestThis7{
s1.display();
s2.display();
}}
Rule: Call to this() must be the first statement in constructor.
class S2{
System.out.println("method is invoked");
void p(){
m(this);
S2 s1 = new S2();
s1.p();
} }
this: to pass as argument in the constructor call:- We can pass the this keyword in the
constructor also. It is useful if we have to use one object in multiple classes.
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
void display(){
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
A4 a=new A4();
} }
class A{
A getA(){
return this;
class Test1{
new A().getA().msg();
} }
Garbage Collection:-In java, garbage means unreferenced objects. Garbage Collection is
process of reclaiming the runtime unused memory automatically. In other words, it is a way to
destroy the unused objects. An object is said to be unreachable if it doesn’t contain any reference
to it. To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.
1) By nulling a reference:
e=null;
3) By anonymous object:
new Employee();
finalize() method:- The finalize() method is invoked each time before the object is garbage
collected. This method can be used to perform cleanup processing. This method is defined in
Object class as:
{}
gc() method:- The gc() method is used to invoke the garbage collector to perform cleanup
processing. The gc() is found in System and Runtime classes.
{ }
Example:-
s1=null;
s2=null;
System.gc();
} }
Final keyword:-Java final keyword is a non-access specifier that is used to restrict a class,
variable, and method. If we initialize a variable with the final keyword, then we cannot modify
its value. If we declare a method as final, then it cannot be overridden by any subclasses. And, if
we declare a class as final, we restrict the other classes to inherit or extend it. In other words, the
final classes cannot be inherited by other classes.
Final Variable:- Once we declare a variable with the final keyword, we can’t change its value
again. If we attempt to change the value of the final variable, then we will get a compilation
error. Generally, we can consider a final variable as a constant, as the final variable acts like a
constant whose values cannot be changed. We can’t just declare a variable as final without
initializing it. That is, we have to give it an initial value while declaring a final variable. If we
declare the final variable without initialization, then it is a blank final variable. But it is
mandatory to initialize a final variable either during declaration or after declaration. If we leave it
uninitialized, then we will get a compilation error.
Output:
speedlimit = 150;
^
1 error
blank final variable example:-
EmployeeDetails(int idNum) {
id = idNum;
void getDetails() {
emp.getDetails();
}}
Final Method:-We can declare Java methods as Final Method by adding the Final keyword before
the method name.The Method with Final Keyword cannot be overridden in the subclasses. The
purpose of the Final Method is to declare methods of how’s definition cannot be changed by a child or
subclass that extends it.
Example:-
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
} }
Output: Compile Time Error
Final Class:- When we declare a class as final, then we restrict other classes to inherit or extend it. In
short, Java final class can’t be extended by other classes in the inheritance. If another class attempts to
extend the final class, then there will be a compilation error.
Example:-
final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[])
{
Honda1 honda= new Honda1();
honda.run();
} }
In Java, it is possible to define a class within another class, such classes are known as nested
classes. They enable you to logically group classes that are only used in one place, thus this
increases the use of encapsulation, and creates more readable and maintainable code.
Types of Nested classes:- There are two types of nested classes non-static and static nested
classes. The non-static nested classes are also known as inner classes.
syntax:-
class OuterClass
...
class NestedClass
...
}}
Difference between nested class and inner class in Java:- An inner class is a part of a nested
class. Non-static nested classes are known as inner classes.
Member Inner class:- A non-static class that is created inside a class but outside a method is
called member inner class. It is also known as a regular inner class. It can be declared with
access modifiers like public, default, private, and protected.
Example:-
class TestMemberOuter1{
class Inner{
}
public static void main(String args[]){
in.msg();
} }
Output:- data is 30
A static class is a class that is created inside a class, is called a static nested class in Java. It
cannot access non-static data members and methods. It can be accessed by outer class name.
It can access static data members of the outer class, including private.
The static nested class cannot access non-static (instance) data members.
Example:-
class TestOuter1{
obj.msg();
} }
Output:- data is 30
Java static nested class example with a static method
If you have the static member inside the static nested class, you don't need to create an instance
of the static nested class.
Example:-
} }
A class i.e., created inside a method, is called local inner class in java. Local Inner Classes are
the inner classes that are defined inside a block.If you want to invoke the methods of the local
inner class, you must instantiate this class inside the method.Local inner class cannot be invoked
from outside the method.
Example: -
void display(){
class Local{
void msg(){System.out.println(data);}
}
Local l=new Local();
l.msg();
obj.display();
} }
Variable Arguments (Varargs) in Java is a method that takes a variable number of arguments.
Variable Arguments in Java simplifies the creation of methods that need to take a variable
number of arguments.
Syntax:-
// method body
This syntax tells the compiler that fun( ) can be called with zero or more arguments.
Example:-
class Test1
{
static void fun(int... a)
{
System.out.println("Number of arguments: " + a.length);
for (int i : a)
System.out.print(i + " ");
System.out.println();
}
public static void main(String args[])
{
fun(100);
fun(1, 2, 3, 4);
fun();
}}
Note: A method can have variable length parameters with other parameters too, but one should
ensure that there exists only one varargs parameter that should be written last in the parameter
list of the method declaration. For example:
int nums(int a, float b, double… c)
Example:-
class Test2 {
for (int i : a)
System.out.println();
fun2("CSPortal", 1, 2, 3, 4, 5);
fun2("forGeeks");
}}
Case 2: Specifying Varargs as the first parameter of the method instead of the last one:
Inheritance:-
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors
of a parent object. It is an important part of OOPs (Object Oriented programming system).The
idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.Inheritance
represents the IS-A relationship which is also known as a parent-child relationship. The keyword
extends is used by the sub class to inherit the features of super class.
Class: A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created.
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
Super Class/Parent Class:Superclass is the class from where a subclass inherits the features. It
is also called a base class or a parent class.
Syntax:
{
//methods and fields
Example:-
class Teacher {
void does(){
System.out.println("Teaching");
}}
System.out.println(obj.collegeName);
System.out.println(obj.designation);
System.out.println(obj.mainSubject);
obj.does();
}}
Note:- The derived class inherits all the members and methods that are declared as public or
protected. If the members or methods of super class are declared as private then the derived class
cannot use them directly. The private members can be accessed only in its own class. Such
private members can only be accessed using public or protected getter and setter methods of
super class as shown in the example below.
class Teacher {
private String designation = "Teacher";
return designation;
this.designation = designation;
return collegeName;
this.collegeName = collegeName;
void does(){
System.out.println("Teaching");
System.out.println(obj.getDesignation());
System.out.println(obj.mainSubject);
obj.does();
}}
Types of inheritance: -
Single inheritance
Multilevel inheritance
Hierarchical inheritance
Multiple inheritance
Hybrid inheritance
Single Inheritance: refers to a child and parent class relationship where a class extends the
another class.
Example:-
class Animal{
void eat(){System.out.println("eating...");}
class TestInheritance{
d.bark();
d.eat();
}}
Output:
barking...
eating...
Multilevel inheritance:- refers to a child and parent class relationship where a class extends the
child class. For example class C extends class B and class B extends class A.
Example:-
class Animal{
void eat(){System.out.println("eating...");}
void weep(){System.out.println("weeping...");}
class TestInheritance2{
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
Hierarchical inheritance:- refers to a child and parent class relationship where more than one
classes extends the same class. For example, classes B, C & D extends the same class A.
Example:-
class Animal{
void eat(){System.out.println("eating...");}
void bark(){System.out.println("barking...");}
void meow(){System.out.println("meowing...");}
class TestInheritance3{
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
Multiple Inheritance:- refers to the concept of one class extending more than one classes,
which means a child class has two parent classes. For example class C extends both classes A
and B. Java doesn’t support multiple inheritance.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If
A and B classes have the same method and you call it from child class object, there will be
ambiguity to call the method of A or B class.
class A{
void msg(){System.out.println("Hello");}
class B{
void msg(){System.out.println("Welcome");}
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
} }
Output:-
Hybrid inheritance:- Combination of more than one types of inheritance in a single program.
For example class A & B extends class C and another class D extends class A then this is a
hybrid inheritance example because it is a combination of single and hierarchical inheritance.
The access specifiers also determine which data members (methods or fields) of a class can be
accessed by other data members of classes or packages etc.
1) Access Modifiers:- Access modifiers in Java allow us to set the scope or accessibility or
visibility of a data member be it a field, constructor, class, or method.
2) Non-access Modifiers:- Java also provides non-access specifiers that are used with classes,
variables, methods, constructors, etc. The non-access specifiers/modifiers define the behavior of
the entities to the JVM.
static
final
abstract
transient
volatile
synchronized
native
Private Yes No No No
Default Access Specifiers:- A default access modifier in Java has no specific keyword.
Whenever the access modifier is not specified, then it is assumed to be the default. The entities
like classes, methods, and variables can have a default access. A default class is accessible inside
the package but it is not accessible from outside the package i.e. all the classes inside the
package in which the default class is defined can access this class. Similarly a default method or
variable is also accessible inside the package in which they are defined and not outside the
package.
Example:-
class BaseClass
}}
class Main
}}
Output:
In the above program, we have a class and a method inside it without any access modifier. Hence
both the class and method display has default access. Then we see that in the method, we can
directly create an object of the class and call the method.
A class or a method or a data field specified as ‘public’ is accessible from any class or package
in the Java program. The public entity is accessible within the package as well as outside the
package. In general, public access modifier is a modifier that does not restrict the entity at all.
Example:-
class A
System.out.println("SoftwareTestingHelp!!");
}}
class Main
obj.display();
}}
Output:
The protected access specifier allows access to entities through subclasses of the class in which
the entity is declared. It doesn’t matter whether the class is in the same package or different
package, but as long as the class that is trying to access a protected entity is a subclass of this
class, the entity is accessible. Note that a class and an interface cannot be protected i.e. we
cannot apply protected modifiers to classes and interfaces. The protected access modifier is
usually used in parent-child relationships.
class A
{
protected void display()
{
System.out.println("SoftwareTestingHelp");
}}
class B extends A {}
class C extends B {}
class Main{
public static void main(String args[])
{
B obj = new B(); //create object of class B
obj.display(); //access class A protected method using obj
C cObj = new C(); //create object of class C
cObj.display (); //access class A protected method using cObj
} }
Output:-
SoftwareTestingHelp
SoftwareTestingHelp
Private Access Modifier:- The ‘private’ access modifier is the one that has the lowest
accessibility level. The methods and fields that are declared as private are not accessible outside
the class. They are accessible only within the class which has these private entities as its
members.Note that the private entities are not even visible to the subclasses of the class. A
private access modifier ensures encapsulation in Java.
Example:-
class TestClass{
//private variable and method
private int num=100;
private void printMessage(){System.out.println("Hello java");}
}
public class Main{
public static void main(String args[]){
TestClass obj=new TestClass();
System.out.println(obj.num);//try to access private data member - Compile Time Error
obj.printMessage();//Accessing private method - Compile Time Error
} }
The program above gives compilation error as we are trying to access private data members
using the class object.
But there is a method to access private member variables. This method is using getters and
setters in Java. So we provide a public get method in the same class in which private variable is
declared so that getter can read the value of the private variable. Similarly, we provide a public
setter method that allows us to set a value for the private variable.
Getter and Setter Methods:-
Example for getter and setter methods for private variables:-
class DataClass {
private String strname;
// getter method
public String getName() {
return this.strname;
}
// setter method
public void setName(String name) {
this.strname= name;
}
}
public class Main {
public static void main(String[] main){
DataClass d = new DataClass();
The super keyword in Java is a reference variable which is used to refer immediate parent class
object. Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
Example:-
class Animal{
String color="white";
String color="black";
void printColor(){
} }
class TestSuper1{
d.printColor();
}}
Output:-
black
white
The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.
Example:-
class Animal{
void eat(){System.out.println("eating...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
} }
class TestSuper2{
d.work();
}}
Output:
eating...
barking...
In the above example Animal and Dog both classes have eat() method if we call eat() method
from Dog class, it will call the eat() method of Dog class by default because priority is given to
local. To call the parent class method, we need to use super keyword.
class Animal{
Animal(){System.out.println("animal is created");}
Dog(){
super();
System.out.println("dog is created");
} }
class TestSuper3
}}
Output:
animal is created
dog is created
Note: super() is added in each class constructor automatically by compiler if there is no super()
or this().
Example:-
class Person{
int id;
String name;
this.id=id;
this.name=name;
} }
class Emp extends Person{
float salary;
this.salary=salary;
class TestSuper5{
e1.display();
}}
Abstract class:-
A class that is declared using “abstract” keyword is known as abstract class. It can have abstract
methods(methods without body) as well as concrete methods (regular methods with body). A
normal class(non-abstract class) cannot have abstract methods.
An abstract class cannot be instantiated, which means you are not allowed to create an object of
it.
A class which contains 0 or more abstract methods is known as abstract class. If it contains at
least one abstract method, it must be declared abstract.
An abstract class outlines the methods but not necessarily implements all the methods.
abstract class A
{
abstract void myMethod(); //abstract method
System.out.println("Woof");
}
obj.sound();
}}
Output:
Woof
Java abstraction
System.out.println("SportsBike Brake");
{
public void brake()
System.out.println("MountainBike Brake");
class Main
m1.brake();
s1.brake();
}}
a.display();
}}
Method Overriding:- Ifsubclass (child class) has the same method as declared in the parent
class, it is knownas method overriding in Java.
Rules for Java Method Overriding
The method must have the same name as in the parent class
The method must have the same parameter as in the parent class.
There must be an IS-A relationship (inheritance).
class Vehicle{
obj.run();
} }
class Bank{
class Test2
} }
It is a process in which a call to an overridden method is resolved at runtime rather than compile-
time. In this process, an overridden method is called through the reference variable of a
superclass. The determination of the method to be called is based on the object being referred to
by the reference variable.
Upcasting:- If the reference variable of Parent class refers to the object of Child class, it is
known as upcasting. For example:
class A{}
A a=new B();//upcasting
class Bike{
void run(){System.out.println("running");}
b.run();
} }
class Bank{
float getRateOfInterest(){return 0;}
class TestPolymorphism{
Bank b;
b=new SBI();
b=new ICICI();
b=new AXIS();
} }
Output:
class Shape{
void draw(){System.out.println("drawing...");}
class TestPolymorphism2{
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
} }
int speedlimit=90;
int speedlimit=150;
System.out.println(obj.speedlimit);
} }
Output:- 90
In the example given above, both the classes have a data member speedlimit. We are accessing
the data member by the reference variable of Parent class which refers to the subclass object.
Since we are accessing the data member which is not overridden, hence it will access the data
member of the Parent class always.
static binding:- When type of the object is determined at compiled time(by the compiler), it is
known as static binding. If there is any private, final or static method in a class, there is static
binding.
class Dog{
d1.eat();
} }
Dynamic binding
class Animal{
a.eat();
} }
class OverloadingExample{
class Animal{
void eat(){System.out.println("eating...");}
finalize() method : This method is called just before an object is garbage collected. It is
called by the Garbage Collector on an object when garbage collector determines that there
are no more references to the object.
clone() : It returns a new object that is exactly the same as this object. For clone() method
refer Clone()
wait()-It tells the calling thread to give up the lock and go to sleep until some other
thread enters the same monitor and calls notify().
notify()-It wakes up one single thread that called wait() on the same object. It should be
noted that calling notify() does not actually give up a lock on a resource.
notifyAll()-It wakes up all the threads that called wait() on the same object.
Interface in Java:-
An interface is a reference type in Java. It is similar to class. It is a collection of abstract
methods. A class implements an interface, thereby inheriting the abstract methods of the
interface.Along with abstract methods, an interface may also contain constants, default
methods, static methods, and nested types. Method bodies exist only for default methods and
static methods.Writing an interface is similar to writing a class. But a class describes the
attributes and behaviors of an object. And an interface contains behaviors that a class
implements.Unless the class that implements the interface is abstract, all the methods of the
interface need to be defined in the class.
Interface cannot be instantiated just like the abstract class. We can have default and static
methods in an interface.
Syntax:
interface <interface_name>
{
Example:-
interface printable
void print();
{
public void print(){System.out.println("Hello");
obj.print();
} }
Example:-
interface Polygon
class Main
r1.getArea(5, 6);
}}
Example:-
interface Bank
float rateOfInterest();
class TestInterface2
System.out.println("ROI: "+b.rateOfInterest());
}}
Class Interface
The members of a class can be declared as The members of an interface are always
private, public or protected declared as public
Contains the concrete methods i.e methods Contains abstract method i.e methods without
with body the body
Can contain final and static methods Cannot contain final or static methods
A class can extend only one class but can An interface can extend any number of
implement any number of interfaces interfaces but cannot implement any interface
Interface variables:-
In an interface, variables are static and final by default. All variables in an interface in java
should have only public access modifier.
interface Shape{
Note that if we don’t write public, static and final before interface variable, the compiler by
default understand it as below.
interface Shape
Example:-
interface Math
{
}}
Example:-
interface AnimalEat
{
void eat();
interface AnimalTravel
void travel();
System.out.println("Animal is eating");
System.out.println("Animal is travelling");
}}
a.eat();
a.travel();
}}
}}
d.dispD();
d.show();
}}
Interface inheritance
Example:-
interface Printable
void print();
void show();
System.out.println("Welcome");
obj.print();
obj.show();
} }
Nested interface:-An interface which is declared inside another interface or class is called
nested interface. They are also known as inner interface.we can only call the nested interface by
using outer class or outer interface name followed by dot( . ), followed by the interface name.
interface MyInterfaceA{
void display();
interface MyInterfaceB{
void myMethod();
obj.myMethod();
} }
class MyClass{
interface MyInterfaceB{
void myMethod();
}}
obj.myMethod();
} }
1) Abstract class can have abstract and Interface can have only abstract methods.
non-abstract methods. Since Java 8, it can have default and static
methods also.
3) Abstract class can have final, non- Interface has only static and final
final, static and non-static variables. variables.
4) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.
5) The abstract keyword is used to The interface keyword is used to declare
declare abstract class. interface.
6) An abstract class can extend another An interface can extend another Java
Java class and implement multiple Java interface only.
interfaces.
8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.
9)Example: Example:
public abstract class Shape public interface Drawable
{ {
public abstract void draw(); void draw();
} }
Packages:-
Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and
annotations) providing access protection and namespace management.
Example:- Circle.java
package p1;
int r;
r=radius;
return 3.14*r*r;
return 2*3.14*r;
}}
PackTest.java
package p2;
import p1.Circle;
import java.util.Scanner;
class PackTest
System.out.println(“enter radius”);
int rad=sc.nextInt();
}}
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Private:- The private access modifier is accessible only within the class.
Example:-
class A
} }
A obj=new A();
} }
Default: -If you do not use any modifier, it is treated as default by default. The default modifier
is accessible only within package. It cannot be accessed from outside the package. It provides
more accessibility than private. But, it is more restrictive than protected, and public.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
//save by B.java
package mypack;
import pack.*;
class B{
} }
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
Protected:- The protected access modifier is accessible within package and outside the package
but through inheritance only.The protected access modifier can be applied on the data member,
method and constructor. It can't be applied on the class.It provides more accessibility than the
default modifier.
//save by A.java
package pack;
public class A{
//save by B.java
package mypack;
import pack.*;
class B extends A{
obj.msg();
} }
Public:-The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.
A.java
package pack;
public class A{
B.java
package mypack;
import pack.*;
class B{
obj.msg();
} }
String Class
In java, string is an immutable object, which means it is constant and cannot be changed once it
has been created.
String literal
Using new keyword
String literal:- In java, Strings can be created like this: Assigning a String literal to a String
instance:
Example:-
char arrch[]={'h','e','l','l','o'};
System.out.println(str);
System.out.println(str2);
System.out.println(str3);
}}
String Methods:-
1. char charAt(int index): It returns the character at the specified index. Specified index value
should be between 0 to length() -1 both inclusive.
2. boolean equals(Object obj): Compares the string with the specified string and returns true if
both matches else false.
3. boolean equalsIgnoreCase(String string): It works same as equals method but it doesn’t
consider the case while comparing strings. It does a case insensitive comparison.
4. int compareTo(String string): This method compares the two strings based on the Unicode
value of each character in the strings.
5. int compareToIgnoreCase(String string): Same as CompareTo method however it ignores
the case during comparison.
6. boolean startsWith(String prefix, int offset): It checks whether the substring (starting from
the specified offset index) is having the specified prefix or not.
7. boolean startsWith(String prefix): It tests whether the string is having specified prefix, if
yes then it returns true else false.
8. boolean endsWith(String suffix): Checks whether the string ends with the specified suffix.
9. int indexOf(int ch): Returns the index of first occurrence of the specified character ch in the
string.
10. int indexOf(int ch, int fromIndex): Same as indexOf method however it starts searching in
the string from the specified fromIndex.
11. int indexOf(String str): This method returns the index of first occurrence of specified
substring str.
12. String substring(int beginIndex): It returns the substring of the string. The substring starts
with the character at the specified index.
13. String substring(int beginIndex, int endIndex): Returns the substring. The substring starts
with character at beginIndex and ends with the character at endIndex.
14. String concat(String str): Concatenates the specified string “str” at the end of the string.
15. String replace(char oldChar, char newChar): It returns the new updated string after
changing all the occurrences of oldChar with the newChar.
16. boolean contains(CharSequence s): It checks whether the string contains the specified
sequence of char values. If yes then it returns true else false.
17. String toUpperCase(): Equivalent to toUpperCase(Locale.getDefault()).
18. public boolean isEmpty(): This method returns true if the given string has 0 length. If the
length of the specified Java String is non-zero then it returns false.
19. public static String join(): This method joins the given strings using the specified delimiter
and returns the concatenated Java String.
Example:-
import java.lang.String;
public class StringMethods
{
public static void main(String[] args)
{
String str = "Saket Saurav";
String str1 = "Software";
String str2 = "Testing";
System.out.println(str1 + str2);
System.out.println(str1.concat(str2));
System.out.println(str.length());
System.out.println(str.charAt(3));
System.out.println("index of 's' is "+ str2.indexOf('s'));
String str3 = "Softwaretestinghelp";
String str4 = "testing";
System.out.println("testing is a part of Softwaretestinghelp:" +
str3.contains(str4));
String str5 = "Thexyzwebsitexyzisxyzsoftwaretestingxyzhelp";
String[] split = str5.split("xyz");
for (String obj: split) {
System.out.println(obj);
}
String replace = str.replace('r', ou');
System.out.println(replace);
System.out.println(str.substring(3,6));
System.out.println(str2.compareTo(str4));
String str6= " hello ";
System.out.println(str6.trim());
String s1="HELLO HOW Are You?”;
String s1lower=s1.toLowerCase();
System.out.println(s1lower);
String s1="hello how are you";
String s1upper=s1.toUpperCase();
System.out.println(s1upper);
}}