Java
Java
• Desktop Application
• Web Application
• Enterprise application
• Mobile Application
• Embedded Application
• Smart Card Application
• Robotics
• Games etc
Java platforms /Editions
50 Keywords of
Rules to follow for keywords:
• Keywords cannot be used as an identifier for class, subclass, variable, and methods.
• Keywords are case-sensitive.
• const and goto are reserved words but not used.
• True, false and null are literals, not keywords.
• All keywords are in lower-case.
Java Identifiers
A Java identifier is a name given to a package, class, interface, method,
or variable. It allows a programmer to refer to the item from other
places in the program.
To make the most out of the identifiers you choose, make them
meaningful and follow the standard Java naming conventions.
A Few Words About Cases
• Using the right letter case is the key to following a naming convention:
• Lowercase is where all the letters in a word are written without any capitalization
(e.g., while, if, mypackage).
• Uppercase is where all the letters in a word are written in capitals. When there are
more than two words in the name use underscores to separate them (e.g.,
MAX_HOURS, FIRST_DAY_OF_WEEK).
• CamelCase (also known as Upper CamelCase) is where each new word begins with a
capital letter (e.g., CamelCase, CustomerAccount, PlayingCard).
• Mixed case (also known as Lower CamelCase) is the same as CamelCase except the
first letter of the name is in lowercase (e.g., hasChildren, customerFirstName,
customerLastName)
Standard Java Naming Conventions
Packages: Names should be in lowercase. With small projects that only
have a few packages it's okay to just give them simple (but meaningful!)
names:
package pokeranalyzer
package mycalculator
Only use very short names when the variables are short-lived, such as in
for loops:
for (int i=0; i<20;i++)
{ //i only lives in here
}
Constants: Names should be in uppercase.
static final int DEFAULT_WIDTH static final int MAX_HEIGHT
Overall Identifiers notations
Package: lowercase
Classes: Camelcase
Interfaces: Camelcase
Methods: Mixedcase + verbs
Variables: Mixedcase
Constants: Uppercase
Variable and Data Type
• Variable is a space in memory where we can store data. It helps to
access the data easily.
• Most importantly Java has numerous datatypes and all data types are
predefined, which is used to store a large amount of information.
• There are two main categories of data type primitive and non-
primitive which classified the various data type.
Primitive type includes:
Integer type: It is further divided into subcategories of datatypes.
byte: The byte data type holds an 8-bit signed two’s complement integer. It is also one of the
reserved words in Java. byte stores whole numbers ranges in between -128 to 127. As it is allocated
limited memory space, it can be used as a replacement of int datatype.
boolean: This datatype is used to store two possible value: either True or False. boolean type values
are not converted implicitly or explicitly to any other type (means typecasting is not possible).
short: It stores whole numbers and the range lies in between -32768 to 32767.
int: When creating variables consisting of numeric values, Java gives preference to int datatype as it
has a higher precedence order. So in a program if you have not defined the datatype, by default java
assumes it as int. It stores whole numbers from -2147483648 to 2147483647. Negative numbers are
also permissible here. It has a wider range compared to short and byte.
long: This datatype can store whole numbers from -9223372036854775808 to
9223372036854775807. For storing a large amount of data, long datatype is preferred over int. In
Java, the value of long datatype must end with literal “L”. Otherwise, Java considers it as int type.
Floating-point type: A floating-point datatypes are used for calculating simple to complex
fractional data. It is further subcategorized into two parts:
float: For storing fractional numbers, float datatype is used. It has a 7-decimal digit precision in
memory. It is not recommended to use float datatype while calculating financial figures or values. As
the value processed here is an approximate value and hence, not used for precise values such as
currency. By default, Java assumes floating-point datatype as double, so you need to add a literal at
the end, denoted by the letter “f”.
double: Another floating-point datatype used to store a huge amount of data in memory. It has a 15-
decimal digit precision in memory. Storing decimal values this data type is generally the default
choice.
}
Assigning one primitive variable to another
public static void main(String[] args) {
int value1 = 1;
int value2 = value1;
System.out.println (value2);
}
Naming Convention of varaibles
The names of variables are case sensitive “value” and “Value” both are different.
Space is not permitted in variable names.
Primitive Data Types
• Java supports eight primitive data types.
• These are the basic and predefined data type of the programming language.
• Java determines the size of each primitive data types, it cannot be changed.
• Primitive data types are represented by reserved keywords.
byte
The size of the byte type is 8bit/1byte. The minimum value of the byte is -128 and the maximum value is 127.
short
The short data type is integer compatible data type and used to contain integer value or an integer number. The size of the short type is
16bit/2byte. The minimum value of the short is -32768 and the maximum value is 32767.
int
The size of the int value is 32bit/4byte. The minimum value of int is -2147483648 and the maximum range is 2147483647.
long
The size of the long data type is 64bit/8byte. While declaring long data type always use suffix “L” by default Java considered it as an integer. Java is a case-
sensitive language so it is recommended use “L” in upper case.
Precision in float:
public static void main(String[] args) {
float var = 10f / 6f;
System.out.println(var);
}
Output:
1.6666666
Double – double is used for high precision floating point values, it occupies 64-bit memory
Initialization of double variable:
double var = 9.5d;
d specifies that value is double.
Precision in double data type is more than a float data type.
Precision in double:
public static void main(String[] args) {
double var = 10d / 6d;
System.out.println (var);
}
Output:
1.6666666666666667
Boolean
Boolean is a data type which represents one bit of information either true or false.
public static void main(String[] args) {
boolean var = true;
System.out.println (var);
}
Output: true
Char
A char data type is a single length entity. This could be an alphabet, a digit or a symbol. It is also used to hold
the Unicode for symbols. Value for char should be with single quotes.
public static void main(String[] args) {
char var = '\u00A7';
char var1 = 'A';
System.out.println (var); Note: We must only use the single quotes pointing to left
System.out.println (var1);
} The length should be one.
Single quote point to the left should be used
Output:
Any character on the keyboard is allowed
§
Example: ‘A’,’*’,’1’
A
Strings in Java
Initialization of String variable
In the below example, we will create a String. Here var is the reference of data “Hello World” of type String.
String var = “Hello World”; String methods
public class App {
} if(z.equals("Studyeasy")){
System.out.println("Text is Studyeasy");
}else{
System.out.println("Text is not
Studyeasy");
}
}
}
Type Casting
In Java, Type Casting is a process of converting a variable of one data type into another.
Typecasting is of two types:
Implicit typecasting.
Explicit typecasting.
Implicit typecasting
Implicit type casting is also known as Widening or Automatic typecasting. When a small range data type
variable is converted into a large range data type, The process is called implicit typecasting.
Example:
we initialize an int variable with a short value.
public static void main(String[] args) {
short x = 10;
int y = x;
System.out.println(y);
}
Output:10
Explicit typecasting
Explicit typecasting is also known as narrowing typecasting. When a large range data type is converted into small
range data.
Example
We initialize the short variable y with int x, when we try to execute, the program will crash with “type mismatch”
error. As we are trying to store large data type (int) into smaller data type variable (short).
public static void main(String[] args) {
int x = 10;
short y = x;
System.out.println(y);
}
Output
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at challanges.Hello.main(Hello.java:7)
In this example, we initialize the short variable by assigning an integer variable, in the narrowing
typecasting scenario; we have to explicitly typecast data.
The following code demonstrates the addition of two numbers as well as concatenation
operation.
public static void main(String[] args) {
int x = 1+2;
String s = "Hello" + " world";
System.out.println(x);
System.out.println(s);
}
Output:
3
Hello world
Subtraction operator
Minus (-) operator is used for subtracting the second operand from the first.
public static void main(String[] args) {
int x = 1;
int y = 12 - x;
System.out.println(y);
}
Output:
11
Multiplication Operator
Multiplication (*) operator used for multiply two numbers.
In following illustration 12*2 gives 24.
public static void main(String[] args) {
int x = 1;
int y = 12 * 2;
System.out.println(y);
}
Output:
24
Division Operator
Division operator (/) used for divide numerator by de-numerator and it gives the quotient.
In the following illustration 12 divided by 2 and the result is 6.
public static void main(String[] args) {
int x = 1;
int y = 12 / 2;
System.out.println(y);
}
Output
6
Modulus operator
Modulus operator used to returns the remainder of one number divided by another.
In following illustration 13%2 and remainder are 1.
public static void main(String[] args) {
int mod = 13 % 2;
System.out.println(mod);
}
Output
1
Increment operator
Increment operator is a unary operator that increments its operand by one. This operator can be used for both postfix(x++) as well as a
prefix (++x).
Postfix- In the postfix form, it evaluates to the value of the operand before the increment operation.
Case 1
public static void main(String[] args) {
int x = 10;
System.out.println(x++);
}
Output
10
Prefix-In the prefix form it evaluates the value of the operand after the increment operation.
Case 2
public static void main(String[] args) {
int x = 10;
System.out.println(++x);
}
Output
11
Decrement operator:
Decrement operator is also a unary operator that decrements its operand by one. This operator can be used for both postfix(x–) as well as a
prefix (–x).
Postfix-In the postfix form, it evaluates to the value of the operand before the decrement operation.
Case 1
public static void main(String[] args) {
int x = 10;
System.out.println(x--);
}
Output
10
Prefix-In the prefix form it evaluates the value of the operand after the increment operation.
Case 2
public static void main(String[] args) {
int x = 10;
System.out.println(--x);
}
Output
9
Ternary Operator In Java
Ternary operator works on three operands. It returns a value based on a condition that evaluates either true or false statement. True and false
statements are also an expression that you want to evaluate. If the expression is true it evaluates expression true otherwise it evaluates the
expression false.
Syntax
Ternary operator has three operands: Condition? Expression 1: Expression 2
false
Example2:
public static void main(String[] args) {
int age = 12;
String a = "Allowed to vote";
String b = "Not allowed to vote";
String accessallowed = (age > 18) ? a : b;
System.out.println(accessallowed);
}
Output
Not allowed to vote
Ternary operator allows you to evaluate two primitive value are equal or not.
public static void main(String[] args) {
int x;
x = (10==9) ? 1 : 0;
System.out.println(x);
}
Output
0
Assignment Operators
Assignment operators are a binary operator that is used to assign a value of an expression to a variable on the
left-hand side of the operator, with the result of the value on the right-hand side of the equation.
Example1:
public static void main(String[] args) {
int x = 5;
x += 5;
System.out.println(x);
}
Output:10
Example2:
public static void main(String[] args) {
int x = 5;
x += 5;
x -= 5;
System.out.println(x);
}
Output:5
Example3:
public static void main(String[] args) { Example4:
int x = 5;
public static void main(String[] args) {
int x = 5;
x *= 5; x %= 5;
System.out.println(x); System.out.println(x);
} }
Output:0
Output:25
Example4;
public static void main(String[] args) {
int x = 5;
x /= 5;
System.out.println(x);
}
Output:1
Java Control Statements | Conditional & Looping Control Statements
They are mainly categorized in 2 types –
Conditional Control Statements
Whenever a condition is to be tested depending on which particular tasks are to be performed, Conditional control statements are used.
Looping / Iterative Control Statements
Whenever a particular task has to be iterated for a particular number of times or depending on some condition, Looping control statements are
used.
Java Conditional Statements.
• if statement
if(condition){
• if-else statement
//code to be executed
• if-else-if ladder }
• nested if statement
Java if Statement
• The Java if statement tests the condition. It executes the if block if condition is true.
Code Block
• Code block in Java is used for grouping of two or more statements. The code in Java always start with curly
braces and end with close curly braces.
• A code block can be used inside a block. There is no restriction number of block and the level of nesting the
block can be nested and can be included inside another Code block. It is generally used in loops statement
(For, while loop, do while loop). Class and method content are blocks too.
Code Indentation
• Indentation is part of style guide which is used to organize your source code in a good manner.
• An indentation is a group of style. This style should be followed by every programmer.
• If we follow proper style guide then the reader will be comfortable and understand the meaning of the
program.
The purpose of code indentation and style guide is to make the code:
• Easy to read
• Easy to understand
• Easy to modify
• Easy to maintain
• Easy to enhance
Incorrect Indentation
public static void main(String[] args) {
Expression statement
The expression is any section of the code that is used to evaluate the condition.
Declaration statement
Statement of the declaration is used to declare a variable.
Output:
1
GFG
What is a Class ?
It is a template or blueprint from which objects are created.
It is a logical entity. It can’t be physical.
A class in Java can contain:
Fields (variables)
methods
constructors
blocks
nested class and interface
What is n Object ?
An entity that has state and behavior is known as an object.
An object has three characteristics:
• state: represents data (value) of an object.
• behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
• identity: Object identity is typically implemented via a unique ID.
• The value of the ID is not visible to the external user. But, it is used internally by the JVM to identify each object uniquely.
Relation Between Class and Object –
Object is an instance of a class.
Class is a template or blueprint from which objects are created.
So object is the instance(result) of a class.
In another way, we can say that objects are variables of type class
Some Important Concepts that come along with Classes and Objects are –
• Instance variables
• Methods
• new keyword
Instance variable in Java
A variable which is created inside the class but outside the method, is known as instance variable.
Instance variable doesn’t get memory at compile time. It gets memory at run time when
object(instance) is created. That is why, it is known as instance variable.
Method in Java
In java, a method is like function i.e. used to expose behavior of an object.
Advantage of Method
Code Reusability
Code Optimization
new keyword in Java
The new keyword is used to allocate memory at run time. All objects get memory in Heap
memory area.
package mystudentexample;
class Student{
int id; // instance variables
String name; // instance variables
}
public class MyStudentExample {
public static void main(String[] args) {
Student object1 = new Student();
object1.id = 1;
object1.name = “Srikanth";
Student obj2;
obj2 = new Student();
obj2.id = 2;
obj2.name = "Simple Snippets";
System.out.println(object1.id);
System.out.println(object1.name);
System.out.println(obj2.id);
System.out.println(obj2.name);
}
}
Java Methods
User-defined Methods
Types of Methods public class FunctionExample {
• Standard Library Methods
• User-defined Methods public int max(int x, int y)
{
if(x>y){
return x;
Standard Library Methods }
else {
public class Numbers { return y;
public static void main(String[] args) { }
}
System.out.print("Hello World");
public static void main(String[] args) {
} // TODO code application logic here
} FunctionExample obj = new FunctionExample();
int num = obj.max(5, 6); // FUNCTION CALL
System.out.println("Max value is: "+num);
}
}
Java Constructors Explained
A constructor is a special method in Java. It is called when an instance of object is created and
memory is allocated for the object. It is called constructor because it constructs the values at the time
of object creation.
Default Constructor
A constructor that has no parameter is known as default constructor. If we don’t define a constructor
in a class, then compiler creates default constructor(with no arguments) for the class.
Default constructor example
public class MyClass {
int number;
public MyClass() {
System.out.println("Constructor Called");
number=5;
}
public static void main(String[] args) {
type var-name[];
OR
type[] var-name;
Instantiating an Array in Java
int intArray[]; //declaring array int[] intArray = new int[20]; // combining both statements in one
intArray = new int[20]; // allocating memory to array
class Testarray {
public static void main(String args[]) {
//printing array
for (int i = 0; i < a.length; i++) //length is the property of array
System.out.println(a[i]);
}
}
Arrays of Objects
An array of objects is created just like an array of primitive type data items in the following way.
class Student // Elements of array are objects of a class Student. // so on...
public class GFG arr[2] = new Student(3,"shikar");
{ { arr[3] = new Student(4,"dharmesh");
public static void main (String[] args) arr[4] = new Student(5,"mohit");
public int roll_no; {
public String name; // declares an Array of integers. // accessing the elements of the specified
Student[] arr; array
Student(int roll_no, String name) for (int i = 0; i < arr.length; i++)
// allocating memory for 5 objects of type Student. System.out.println("Element at " + i + " : "
{
arr = new Student[5]; +
this.roll_no = roll_no; arr[i].roll_no +" "+ arr[i].name);
// initialize the first elements of the array }
this.name = name; arr[0] = new Student(1,"aman"); }
}
// initialize the second elements of the array
} arr[1] = new Student(2,"vaibhav");
Java Multi Dimensional Arrays
int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array
2-D Array in Java Example Program
class multiDimensional
{
public static void main(String args[])
{
int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };
for (int i=0; i< 3 ; i++)
{
for (int j=0; j < 3 ; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}
Jagged array in java is array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D
arrays but with variable number of columns in each row. These type of arrays are also known as Jagged arrays.
Inheritance and types
// Program to demonstrate 2-D jagged array in Java
// Displaying the values of 2D Jagged array
class Main System.out.println("Contents of 2D
{ Jagged Array");
public static void main(String[] args) for (int i=0; i<arr.length; i++)
{ {
// Declaring 2-D array with 2 rows
for (int j=0; j<arr[i].length; j++)
System.out.print(arr[i][j] + " ");
int arr[][] = new int[2][];
System.out.println();
// Making the above array Jagged }
// First row has 3 columns }
arr[0] = new int[3]; }
// Second row has 2 columns
arr[1] = new int[2]; Contents of 2D Jagged Array
// Initializing array 012
int count = 0; 34
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
Strings
• 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.
• The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.
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.
What is String in Java?
Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of characters.
The java.lang.String class is used to create a string object.
class Teststringcomparison1{
class Teststringcomparison2{
public static void main(String args[]){
public static void main(String args[]){
String s1="Sachin";
String s1="Sachin";
String s2="Sachin"; String s2="SACHIN";
String s3=new String("Sachin");
String s4="Saurav"; System.out.println(s1.equals(s2));//false
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true System.out.println(s1.equalsIgnoreCase(s2));//tru
System.out.println(s1.equals(s4));//false e
} }
} }
2) By Using == operator
true
false
3) String compare by compareTo() method
The above code, demonstrates the use of == operator used for comparing two String objects.
3) By Using compareTo() method
The String class compareTo() method compares values lexicographically and returns an integer value that describes if first string is less than, equal to or
greater than second string.
Suppose s1 and s2 are two String objects. If:
s1 == s2 : The method returns 0.
s1 > s2 : The method returns a positive value.
s1 < s2 : The method returns a negative value.
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
String Concatenation in Java
In Java, String concatenation forms a new String that is the combination of multiple strings. There are two ways to concatenate strings in Java:
• By + (String concatenation) operator
• By concat() method
1) String Concatenation by + (String concatenation) operator
Java String concatenation operator (+) is used to add strings. For Example:
class TestStringConcatenation1{
public static void main(String args[]){
String s="Sachin"+" Tendulkar";
System.out.println(s);//Sachin Tendulkar
}
}
Output:
Sachin Tendulkar
2) String Concatenation by concat() method
The String concat() method concatenates the specified string to the end of current string.
Syntax:
public String concat(String another)
class TestStringConcatenation3{
public static void main(String args[]){
String s1="Sachin ";
There are some other possible ways to concatenate Strings in Java,
String s2="Tendulkar";
String s3=s1.concat(s2);
1. String concatenation using StringBuilder class
System.out.println(s3);//Sachin Tendulkar 2. String concatenation using format() method
} 3. String concatenation using String.join() method (Java Version 8+)
} 4. String concatenation using StringJoiner class (Java Version 8+)
Test it Now 5. String concatenation using Collectors.joining() method (Java Version 8+)
Output:
Sachin Tendulkar
Substring in Java
• A part of String is called substring. In other words, substring is a subset of another String.
• Java String class provides the built-in substring() method that extract a substring from the given string by using the index
values passed as an argument.
• In case of substring() method startIndex is inclusive and endIndex is exclusive.
You can get substring from the given String object by one of the two methods:
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it is safe and will result in
an order.
Important Constructors of StringBuffer Class
Constructor Description
StringBuffer() It creates an empty String buffer with the initial capacity of 16.
StringBuffer(String str) It creates a String buffer with the specified string..
StringBuffer(int capacity) It creates an empty String buffer with the specified capacity as length.
What is a mutable String?
A String that can be modified or changed is known as mutable String. StringBuffer and StringBuilder classes are used for
creating mutable strings.
1) StringBuffer Class append() Method
The append() method concatenates the given argument with this String.
StringBufferExample.java
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
Output:
Hello Java
2) StringBuffer insert() Method
The insert() method inserts the given String with this string at the given position.
StringBufferExample2.java
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
Output:
HJavaello
3) StringBuffer replace() Method
The replace() method replaces the given String from the specified beginIndex and endIndex.
StringBufferExample3.java
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
Output:
HJavalo
4) StringBuffer delete() Method
The delete() method of the StringBuffer class deletes the String from the specified beginIndex to endIndex.
StringBufferExample4.java
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
Output:
Hlo
5) StringBuffer reverse() Method
The reverse() method of the StringBuilder class reverses the current String.
StringBufferExample5.java
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
Output:
olleH
Java StringBuilder Class
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.
class StringBuilderExample{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
Output:
Hello Java
2) StringBuilder insert() method
The StringBuilder insert() method inserts the given string with this string at the given position.
StringBuilderExample2.java
class StringBuilderExample2{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
Output:
HJavaello
3) StringBuilder replace() method
The StringBuilder replace() method replaces the given string from the specified beginIndex and endIndex.
StringBuilderExample3.java
class StringBuilderExample3{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
Output:
HJavalo
4) StringBuilder delete() method
The delete() method of StringBuilder class deletes the string from the specified beginIndex to endIndex.
StringBuilderExample4.java
class StringBuilderExample4{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
Output:
Hlo
4) StringBuilder delete() method
The delete() method of StringBuilder class deletes the string from the specified beginIndex to endIndex.
StringBuilderExample4.java
class StringBuilderExample4{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
Output:
Hlo
Difference between String and StringBuffer
There are many differences between String and StringBuffer. A list of differences between String and StringBuffer are given
below:
Performance Test of StringBuffer and StringBuilder
Let's see the code to check the performance of StringBuffer and StringBuilder classes.
sb.append("Tpoint");
startTime = System.currentTimeMillis();
sb2.append("Tpoint");
Output:
Character at 0 index is: W
Character at last index is: l
Print Characters Presented at Odd Positions by Using the charAt() Method
Let's see an example where we are accessing all the elements present at odd index.
Output:
FileName: CharAtExample4.java
Char at 1 place e
Char at 3 place c
public class CharAtExample4 { Char at 5 place m
public static void main(String[] args) {
Char at 7 place
Char at 9 place o
String str = "Welcome to Javatpoint portal"; Char at 11 place J
for (int i=0; i<=str.length()-1; i++) { Char at 13 place v
if(i%2!=0) { Char at 15 place t
Char at 17 place o
System.out.println("Char at "+i+" place "+str.charAt(i));
Char at 19 place n
} Char at 21 place
} Char at 23 place o
} Char at 25 place t
Char at 27 place l
}
Counting Frequency of a character in a String by Using the charAt() Method
FileName: CharAtExample5.java
public class CharAtExample5 {
public static void main(String[] args) {
String str = "Welcome to Javatpoint portal";
int count = 0;
for (int i=0; i<=str.length()-1; i++) {
if(str.charAt(i) == 't') {
count++;
}
}
System.out.println("Frequency of t is: "+count);
}
}
Output:
Frequency of t is: 4
Java String compareTo()
The Java String class compareTo() method compares the given string with the current string lexicographically. It returns a
positive number, negative number, or 0.
It compares strings on the basis of the Unicode value of each character in the strings.
if s1 > s2, it returns positive number
if s1 < s2, it returns negative number
if s1 == s2, it returns 0
Syntax
public int compareTo(String anotherString)
The method accepts a parameter of type String that is to be compared with the current string.
Signature
The signature of the string concat() method is given below:
Returns
combined string
Java String concat() method example
public class ConcatExample{
public static void main(String args[]){
String s1="java string";
// The string s1 does not get changed, even though it is invoking the method
// concat(), as it is immutable. Therefore, the explicit assignment is required here.
s1.concat("is immutable");
System.out.println(s1);
s1=s1.concat(" is immutable so assign it explicitly");
System.out.println(s1);
}}
java string
java string is immutable so assign it explicitly
Java String concat() Method Example 3
Let's see an example where we are concatenating spaces and special chars to the string object. It is done using the chaining of the concat()
method.
public class ConcatExample3 {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Javatpoint";
String str3 = "Reader";
// Concatenating Space among strings
String str4 = str1.concat(" ").concat(str2).concat(" ").concat(str3);
System.out.println(str4);
// Concatenating Special Chars
String str5 = str1.concat("!!!");
System.out.println(str5); }}
Output:
Hello Javatpoint Reader
Hello!!!
Java String contains()
The Java String class contains() method searches the sequence of characters in this string. It returns true if the sequence of char values is found
in this string otherwise returns false.
Signature
The signature of string contains() method is given below:
Returns
true if the sequence of char value exists, otherwise false.
Exception
NullPointerException : if the sequence is null.
Java String contains() Method Example
FileName: ContainsExample.java
class ContainsExample{
public static void main(String args[]){
String name="what do you know about me";
System.out.println(name.contains("do you know"));
System.out.println(name.contains("about"));
System.out.println(name.contains("hello"));
}}
Output:
true
true
false
The contains() method searches case-sensitive char sequence. If the argument is not case sensitive, it returns false. Let's see an
example.
FileName: ContainsExample2.java
Signature
The syntax or signature of endsWith() method is given below.
Returns
true or false
Java String endsWith() Method Example
FileName: EndsWithExample.java
true
true
Java String equals()
The Java String class equals() method compares the two given strings based on the content of the string. If any character is not
matched, it returns false. If all characters are matched, it returns true.
The String equals() method overrides the equals() method of the Object class.
Signature
publicboolean equals(Object anotherObject)
Parameter
anotherObject : another object, i.e., compared with this string.
Returns
true if characters of both strings are equal otherwise false.
Java String equals() Method Example
FileName: EqualsExample.java
public class EqualsExample{
public static void main(String args[]){
String s1="javatpoint";
String s2="javatpoint";
String s3="JAVATPOINT";
String s4="python";
System.out.println(s1.equals(s2));//true because content and case is same
System.out.println(s1.equals(s3));//false because case is not same
System.out.println(s1.equals(s4));//false because content is not same
}}
Output:
true
false
false
Java String equalsIgnoreCase()
The Java String class equalsIgnoreCase() method compares the two given strings on the basis of the content of the string
irrespective of the case (lower and upper) of the string. It is just like the equals() method but doesn't check the case sensitivity.
If any character is not matched, it returns false, else returns true.
Signature
publicboolean equalsIgnoreCase(String str)
Parameter
str : another string i.e., compared with this string.
Returns
It returns true if characters of both strings are equal, ignoring case otherwise false.
Java String equalsIgnoreCase() Method Example
FileName: EqualsIgnoreCaseExample.java
class LargestOfThreeNumbers
int x, y, z;
x = in.nextInt();
y = in.nextInt();
z = in.nextInt();
else
}
Swapping of 2 Variables using 3rd Variable in C++
#include <iostream>
using namespace std;
int main() {
int a,b,c;
cout<<"Enter value of a: ";
cin>>a;
cout<<"Enter value of b: ";
cin>>b;
cout<<"Before Swapping: a: "<<a<<" b: "<<b<<endl;
// start: swapping logic
c=a;
a=b;
b=c;
// end: swapping logic
cout<<"After Swapping: a: "<<a<<" b: "<<b<<endl;
return 0;
}
Swapping of 2 Variables Without using 3rd Variable in C++
#include <iostream>
using namespace std;
int main() {
int a,b;
int num = 4;
int factorial =1;
for(int i = num; i>0; i--)
{
factorial = factorial *i;
}
System.out.println("Factorial is: "+factorial);
}
}
Java program to Find if a Number is PALINDROME or not –
package javaapplication4;
int num=121;
int temp=num;
int rev = 0;
while(num>0)
rev = rev*10;
num = num/10;
if(temp == rev)
System.out.println("Palindrome");
else
System.out.println("Not Palindrome");
}
Java Program to Print FIBONACCI Series using FOR LOOP
// 0 + 1 + 1 + 2 + 3 + 5 + 8 +
package javaapplication4;
public class JavaApplication4 {
public static void main(String[] args) {
int a = 0;
int b = 1;
int c;
for(int i = 0; i<5 ; i++)
{
System.out.print(a+" ");
c = a+b;
a=b;
b=c;
}
}
}
Polymorphism in Java – Method Overloading | Method Overriding
• Polymorphism is derived from 2 greek words: poly and morphs. The word “poly” means many and “morphs” means forms.
So Polymorphism means the ability to take many forms.
• Polymorphism is a concept by which we can perform a single task in different ways.
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Packages Example Step 2: import pack.*;
Step1 : package pack; import Subpackage.*;
public class A{ class B{
public void msg(){System.out.println("Hello A");} public static void main(String args[]){
A obj = new A();
}
C obj1 = new C();
Step 1.1 package pack; D obj2 = new D();
public class C { obj.msg();
public void msg() obj1.msg();
{ obj2.msg();
System.out.println("Hello C"); }
}
}
}
Step 1.3 package Subpackage;
public class D {
}
Source >> Generate Getter and Setter public String getEngine() {
public class Car { return engine;
private String doors;
}
private String engine;
private String drivers;
private int speed; public void setEngine(String engine) {
this.engine = engine;
public int getspeed() { }
return speed;
} public String getDrivers() {
return drivers;
public void setspeed(int speed) {
this.speed = speed; }
}
public void setDrivers(String drivers) {
public String getDoors() { this.drivers = drivers;
return doors; }
}
public void setDoors(String doors) {
}
this.doors = doors;
}
public class Car {
private String doors;
private String engine; public static void main(String[] args) {
private String driver; Car car = new Car ();
private int speed; car.setspeed (10);
car.setDoors ("closed");
car.setEngine ("on");
public String run() { car.setDrivers ("seated");
if(doors.equals("closed") &&
engine.equals("on")&& driver.equals("seated")
//calling the function
&& speed System.out.println (car.run ());
>0) {
return "car is running"; }
}else {
return "car is not Output
running"; car is running
}
}
Access Modifiers in Java
Access modifiers in java specify the scope of a class, constructor ,
variable , method or data member.
There are four types of access modifiers available in java:
• Private - The private access modifier is accessible only within class
• Default – No keyword required - accessible only within package.
• Protected - is accessible within package and outside the package but
through inheritance only
• Public - The public access modifier is accessible everywhere
Private Access Modifier
The private access modifier is accessible only within class. The private access modifier is
specified using the keyword private.
• The methods or data members declared as private are accessible only within the
class in which they are declared.
• Any other class of same package will not be able to access these members.
• Classes or interface can not be declared as private.
package p1; class B Output
class A { error: display() has private access in A
{ public static void main(String args[]) obj.display();
private void display() {
A obj = new A();
{
//trying to access private method of
System.out.println("TNS Sessions");
another class
} obj.display();
} }
}
Default Access Modifier
If you don’t use any modifier, it is treated as default by default. The default modifier is accessible
only within package.
• The data members, class or methods which are not declared using any access modifiers
i.e. having default access modifier are accessible only within the same package.
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
Methods
A method that is declared as abstract and does not have implementation is known as abstract method.
abstract void disp();
1. In Java, an instance of an abstract class cannot be created, we can have references of abstract class type though.
Method Description
nextInt() reads an int value from the user
nextFloat() reads a float value form the user
nextBoolean() reads a boolean value from the user
nextLine() reads a line of text from the user
next() reads a word from the user
nextByte() reads a byte value from the user
nextDouble() reads a double value from the user
nextShort() reads a short value from the user
nextLong() reads a long value from the user
Example 2: Java Scanner nextInt()
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Scanner; Output:
class Main { Enter a big integer: 987654321
public static void main(String[] args) { Using nextBigInteger(): 987654321
// creates an object of Scanner Enter a big decimal: 9.55555
Scanner input = new Scanner(System.in);
Using nextBigDecimal(): 9.55555
System.out.print("Enter a big integer: ");
// reads the big integer
BigInteger value1 = input.nextBigInteger();
System.out.println("Using nextBigInteger(): " + value1);
System.out.print("Enter a big decimal: ");
// reads the big decimal
BigDecimal value2 = input.nextBigDecimal();
System.out.println("Using nextBigDecimal(): " + value2);
input.close();
}
}
Java Scanner
• Scanner class in Java is found in the java.util package. Java provides various ways to read input from the keyboard, the java.util.Scanner
class is one of them.
• The Java Scanner class breaks the input into tokens using a delimiter which is whitespace by default.
import java.util.*;
public class ScannerClassExample1 {
public static void main(String args[]){
System.out.println("--------Enter Your Details-------- ");
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.next();
System.out.println("Name: " + name);
System.out.print("Enter your age: ");
int i = in.nextInt();
System.out.println("Age: " + i);
System.out.print("Enter your salary: ");
double d = in.nextDouble();
System.out.println("Salary: " + d);
in.close();
}
}
import java.util.*;
public class ScannerExample {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
in.close();
}
}
Java File Handling
Java Create and Write To Files
Create a File
To create a file in Java, you can use the createNewFile() method.
This method returns a boolean value: true if the file was successfully created, and false if the file already exists.
Note that the method is enclosed in a try...catch block. This is necessary because it throws an IOException if an error occurs (if the file cannot be created for some
reason):
Example
catch (IOException e) {
import java.io.File; // Import the File class
System.out.println("An error occurred.");
import java.io.IOException; // Import the IOException class to handle errors
e.printStackTrace();
public class CreateFile { }
public static void main(String[] args) { }
try { }
File myObj = new File("filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
}
Write To a File
In the following example, we use the FileWriter class together with its write() method to write some text to the file we created in the example above. Note that when you
are done writing to the file, you should close it with the close() method:
Example
import java.io.File; // Import the File class
Categories of Exceptions
• Checked exceptions
• Unchecked exceptions
• Errors
Checked exceptions − A checked exception is an exception that is checked (notified) by the compiler at
compilation-time, these are also called as compile time exceptions.
For example: if you use FileReader class in your program to read data from a file, if the file specified in its
constructor doesn't exist, then a FileNotFoundException occurs, and the compiler prompts the programmer to
handle the exception.
import java.io.File; C:\>javac FilenotFound_Demo.java
import java.io.FileReader; FilenotFound_Demo.java:8: error: unreported exception
FileNotFoundException; must be caught or declared to be
thrown
public class FilenotFound_Demo { FileReader fr = new FileReader(file);
^
1 error
public static void main(String args[]) {
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
Unchecked exceptions − An unchecked exception is an exception that occurs at the time of execution. These
are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of
an API.
public class Unchecked_Demo {
Try The "try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or
finally. It means, we can't use try block alone.
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 important code of the
program. It is executed whether an exception is handled or not
throw The "throw" keyword is used to throw an exception.
}
Java catch multiple exceptions
public class MultipleCatchBlock2 {
public class MultipleCatchBlock1 {
public static void main(String[] args) {
public static void main(String[] args) {
try{
try{ int a[]=new int[5];
int a[]=new int[5];
a[5]=30/0; System.out.println(a[10]);
} }
catch(ArithmeticException e) catch(ArithmeticException e)
{ {
System.out.println("Arithmetic Exception occurs"); System.out.println("Arithmetic Exception occurs");
} }
catch(ArrayIndexOutOfBoundsException e) catch(ArrayIndexOutOfBoundsException e)
{ {
System.out.println("ArrayIndexOutOfBounds System.out.println("ArrayIndexOutOfBounds
Exception occurs"); Exception occurs");
} }
catch(Exception e) catch(Exception e)
{ {
System.out.println("Parent Exception occurs"); System.out.println("Parent Exception occurs");
} }
System.out.println("rest of the code"); System.out.println("rest of the code");
} }
} }
public class MultipleCatchBlock4 {
public static void main(String[] args) {
try{
String s=null;
System.out.println(s.length());
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Java Nested try block
Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases,
exception handlers have to be nested.
class Excep6{
public static void main(String args[]){
going to divide
try{
java.lang.ArithmeticException: / by zero
try{
java.lang.ArrayIndexOutOfBoundsException: Index
System.out.println("going to divide");
5 out of bounds for length 5
int b =39/0;
other statement
}catch(ArithmeticException e){System.out.println(e);}
normal flow..
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
}
Java finally block
Java finally block is a block that is used to execute important code such as closing connection, stream etc.
Java finally block is always executed whether exception is handled or not.
Case 1: exception doesn't occur. Case 2: exception occurs and not handled.
class TestFinallyBlock{ class TestFinallyBlock1{
public static void main(String args[]){ public static void main(String args[]){
try{ try{
int data=25/5; int data=25/0;
System.out.println(data); System.out.println(data);
} }
catch(NullPointerException e){System.out.println(e);} catch(NullPointerException e)
finally{System.out.println("finally block is always {System.out.println(e);}
executed");} finally{System.out.println("finally block is always
System.out.println("rest of the code..."); executed");}
} System.out.println("rest of the code...");
} }
}
Output: Output:
5
finally block is always executed
finally block is always executed
rest of the code... Exception in thread main
java.lang.ArithmeticException:/ by zero
Case 3: exception occurs and handled.
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
int a = 5;
// converts into object
Integer aObj = a;
double b = 5.6;
// converts into object
Double bObj = b;
This process is known as auto-boxing
Unboxing
It is just the reverse process of autoboxing. Converting an object of a wrapper class to its corresponding primitive type is
known as unboxing.
The Java compiler applies unboxing when an object of a wrapper class is:
• Passed as a parameter to a method that expects a value of the corresponding primitive type.
• Wrapper Objects into Primitive Types
class Main {
public static void main(String[] args) { Output
// runs perfectly
ArrayList<Integer> list = new ArrayList<>();
• Basic Concepts required to understand Collections
Variables concept
• int x=10, y=20,z=30; // 10000 values …. Worst practice
Collection vs collection framework
Arrays
• Student[] s = new student[10000]; 0,1,2,…..9999 Collection(I) : group of individual objects as a single
unit
Limitations of arrays
• Fixed Size( You cant change once the size is fixed) Student <- S1,s2,s3…sn
• Homogeneous
• No standard method (readymade methods are not supported)
Collection framework: Several classes and interfaces is
• treeset collection contains insert() , contains (),clear(), remove() required / used to implement collection.(sort , search)
• Iterable Interface :
• Collection Interface
• List Interface : Array List , Linked list , Vector , stack
• Queue Interface : Priority queue
• Deque Interface : array Dequeue
• Set Interface : Hashset , Linked hashset
• Sorted Set Interface :Treeset
• Map Interface : Hashmap
1 Iterable Interface:
• This is the root interface for the entire collection framework. The collection interface extends the
iterable interface.
• Therefore, inherently, all the interfaces and classes implement this interface.
• The main functionality of this interface is to provide an iterator for the collections. Therefore, this
interface contains only one abstract method which is the iterator.
• It returns the Iterator iterator();
2 Collection Interface:
• This interface extends the iterable interface and is implemented by all the classes in the collection
framework.
• This interface contains all the basic methods which every collection has like adding the data into
the collection, removing the data, clearing the data, etc.
• All these methods are implemented in this interface because these methods are implemented by all
the classes irrespective of their style of implementation.
3 List Interface:
• This is a child interface of the collection interface.
• This interface is dedicated to the data of the list type in which we can store all the ordered
collection of the objects.
• This also allows duplicate data to be present in it. This list interface is implemented by various
classes like ArrayList, Vector, linked list , Stack, etc.
• Since all the subclasses implement the list, we can instantiate a list object with any of these
classes.
• For example,
List <T> al = new ArrayList<> ();
List <T> ll = new LinkedList<> ();
List <T> v = new Vector<> ();
Where T is the type of the object
The classes which implement the List interface are as follows:
3. a ArrayList:
• ArrayList provides us with dynamic arrays in Java. Though, it may be slower than standard arrays
but can be helpful in programs where lots of manipulation in the array is needed.
• The size of an ArrayList is increased automatically if the collection grows or shrinks if the objects
are removed from the collection.
• Java ArrayList allows us to randomly access the list. ArrayList can not be used for primitive types,
like int, char, etc. We will need a wrapper class for such cases.
// Java program to demonstrate the
// working of ArrayList in Java // Remove element at index 3
import java.io.*;
al.remove(3);
import java.util.*;
// Displaying the ArrayList
class GFG { // after deletion
public static void main(String[] args)
{ System.out.println(al);
For example,
Queue <T> pq = new PriorityQueue<> ();
Queue <T> ad = new ArrayDeque<> ();
Where T is the type of the object.
4.A Priority Queue:
A PriorityQueue is used when the objects are supposed to be processed based on the priority.
It is known that a queue follows the First-In-First-Out algorithm, but sometimes the elements of the
queue are needed to be processed according to the priority and this class is used in these cases.
The PriorityQueue is based on the priority heap.
// Java program to demonstrate the working of // Printing the top element of PriorityQueue
// priority queue in Java System.out.println(pQueue.peek());
import java.util.*;
// Printing the top element and removing it
class GfG { // from the PriorityQueue container
public static void main(String args[]) System.out.println(pQueue.poll());
{
// Creating empty priority queue // Printing the top element again
PriorityQueue<Integer> pQueue System.out.println(pQueue.peek());
= new PriorityQueue<Integer>(); }
}
// Adding items to the pQueue using add() Output:
pQueue.add(1); 1
pQueue.add(2); 1
pQueue.add(3); 2
5. Deque Interface: This is a very slight variation of the queue data structure.
Deque, also known as a double-ended queue, is a data structure where we can add and remove the
elements from both the ends of the queue.
This interface extends the queue interface. The class which implements this interface is ArrayDeque.
Since this class implements the deque, we can instantiate a deque object with this class.
For example,
Deque<T> ad = new ArrayDeque<> ();
Where T is the type of the object.
ArrayDeque: ArrayDeque class which is implemented in the collection framework provides us with
a way to apply resizable-array. This is a special kind of array that grows and allows users to add or
remove an element from both sides of the queue.
// Java program to demonstrate the // addFirst() method to insert the
// ArrayDeque class in Java // elements at the head
de_que.addFirst(564);
import java.util.*;
public class ArrayDequeDemo { de_que.addFirst(291);
public static void main(String[] args)
{ // addLast() method to insert the
// Initializing an deque // elements at the tail
ArrayDeque<Integer> de_que de_que.addLast(24);
= new ArrayDeque<Integer>(10); de_que.addLast(14);
// add() method to insert
System.out.println(de_que);
de_que.add(10);
de_que.add(20); }
de_que.add(30); }
de_que.add(40);
de_que.add(50);
System.out.println(de_que); Output:
[10, 20, 30, 40, 50]
// clear() method
[264,291, 564, 24, 14]
de_que.clear();
6 Set Interface:
A set is an unordered collection of objects in which duplicate values cannot be stored.
This collection is used when we wish to avoid the duplication of the objects and wish to store only
the unique objects.
This set interface is implemented by various classes like HashSet, TreeSet, LinkedHashSet, etc.
Since all the subclasses implement the set, we can instantiate a set object with any of these classes.
For example,
hs.add("Geeks"); Output:
hs.add("For"); Very helpful
hs.add("Geeks");
hs.add("Is");
Geeks
hs.add("Very helpful"); For
Is
6.B LinkedHashSet:
A LinkedHashSet is very similar to a HashSet. The difference is that this uses a doubly linked list to
store the data and retains the ordering of the elements.
lhs.add("Geeks");
lhs.add("For"); Output:
lhs.add("Geeks"); Geeks
lhs.add("Is");
lhs.add("Very helpful"); For
Is
7. Sorted Set Interface:
This interface is very similar to the set interface. The only difference is that this interface has extra
methods that maintain the ordering of the elements.
The sorted set interface extends the set interface and is used to handle the data which needs to be
sorted. The class which implements this interface is TreeSet.
Since this class implements the SortedSet, we can instantiate a SortedSet object with this class. For
example,
Above code compiles fine but throws ClassCastException at runtime because we are trying to cast
Object in the list to String whereas one of the element is of type Integer.
After Java 5, we use collection classes like below.
Notice that at the time of list creation, we have specified that the type of elements in the list will be
String. So if we try to add any other type of object in the list, the program will throw compile-time
error. Also notice that in for loop, we don’t need typecasting of the element in the list, hence removing
the ClassCastException at runtime.
Generic Class
Like C++, we use <> to specify parameter types in generic class creation. To create objects of generic class, we use following syntax.
// To create an instance of generic class
BaseType <Type> obj = new BaseType <Type>()
// Driver method
java.lang.Integer = 11
public static void main(String[] args)
java.lang.String = GeeksForGeeks
{
java.lang.Double = 1.0
// Calling generic method with Integer argument
genericDisplay(11);
Advantages of Generics:
Programs that uses Generics has got many benefits over non-generic code.
• Code Reuse: We can write a method/class/interface once and use for any type we want.
• Type Safety : Generics make errors to appear compile time than at run time (It’s always better to
know problems in your code at compile time rather than making your code fail at run time).
Suppose you want to create an ArrayList that store name of students and if by mistake programmer
adds an integer object instead of string, compiler allows it. But, when we retrieve this data from
ArrayList, it causes problems at runtime.
// A Simple Java program to demonstrate that NOT using String s1 = (String)al.get(0);
// generics can cause run time exceptions String s2 = (String)al.get(1);
import java.util.*;
class Test
// Causes Runtime Exception
{ String s3 = (String)al.get(2);
public static void main(String[] args) }
{ }
// Creatinga an ArrayList without any type specified Output :
ArrayList al = new ArrayList();
al.add("Sachin");
Exception in thread "main" java.lang.ClassCastException:
al.add("Rahul"); java.lang.Integer cannot be cast to java.lang.String
al.add(10); // Compiler allows this at Test.main(Test.java:19)
How generics solve this problem?
At the time of defining ArrayList, we can specify that this list can take only String objects.
class Test
{
public static void main(String[] args) Generics promotes code reusability.
{
// Creating a an ArrayList with String specified
ArrayList <String> al = new ArrayList<String> (); Implementing generic algorithms: By using
generics, we can implement algorithms that
al.add("Sachin");
al.add("Rahul");
work on different types of objects and at the
same they are type safe too.
// Typecasting is not needed
String s1 = al.get(0);
String s2 = al.get(1);
}
}
Bounded types with generics in Java
There may be times when you want to restrict the types that can be used as type arguments in a
parameterized type. For example, a method that operates on numbers might only want to accept
instances of Number or its subclasses
Declare a bounded type parameter
Unbounded Wildcard: This wildcard type is specified using the wildcard character (?),
• When the code is using methods in the generic class that don’t depend on the type parameter
Unbounded Wildcard: This wildcard type is specified using the wildcard character (?),
• When the code is using methods in the generic class that don’t depend on the type parameter
import java.util.Arrays;
import java.util.List;
class unboundedwildcardemo
{ private static void printlist(List<?> list)
public static void main(String[] args) {
{
System.out.println(list);
//Integer List }
List<Integer> list1= Arrays.asList(1,2,3);
}
//Double list
Output:
List<Double> list2=Arrays.asList(1.1,2.2,3.3);
[1, 2, 3]
printlist(list1); [1.1, 2.2, 3.3]
printlist(list2);
}
What is Thread in java?
A thread is a lightweight sub process, a smallest unit of processing.
Multithreading in Java Programming
• Multithreading in java is a process of executing multiple threads simultaneously.
• Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization
of CPU. Each part of such program is called a thread.
• Thread is basically a lightweight sub-process, a smallest unit of processing.
• Multiprocessing and multithreading, both are used to achieve multitasking. But we use multithreading than multiprocessing
because threads share a common memory area. They don’t allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.
• Multitasking
• Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking
can be achieved by two ways:
• Process-based Multitasking(Multiprocessing)
• Thread-based Multitasking(Multithreading)
Advantages of Java Multithreading
• It doesn’t block the user because threads are independent and you can perform multiple operations at same time.
• You can perform many operations together so it saves time.
• Threads are independent so it doesn’t affect other threads if exception occur in a single thread.
Life cycle of a Thread (Thread States)
A thread can be in one of the five states. The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:
• New
• Runnable
• Running
• Non-Runnable (Blocked/Waiting)
• Terminated
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running
thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked/Wait)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
Multithreading in Java by Inheriting Thread Class
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part
of such program is called a thread. So, threads are light-weight processes within a process.
As discussed in the previous post Threads can be created by using two mechanisms :
1. Extending the Thread class
2. Implementing the Runnable Interface
class MultithreadingDemo extends Thread
{ public class JavaApplication4 { Output –
public void run()
{
public static void main(String[] args) {
try main Thread 1 is running
{
for(int i=0;i<5;i++){ MultithreadingDemo object = new main Thread 1 is running
// Displaying the thread that is running
System.out.println ("Thread " +
MultithreadingDemo(); main Thread 1 is running
object.start();
Thread.currentThread().getId() + Thread 10 is running
for(int i=0;i<5;i++){
}
" is running");
// Displaying the thread that is running main Thread 1 is running
} System.out.println ("main Thread " + Thread 10 is running
catch (Exception e) Thread.currentThread().getId() + main Thread 1 is running
{ " is running");
// Throwing an exception } Thread 10 is running
}
System.out.println ("Exception is caught");
} Thread 10 is running
} } Thread 10 is running
}
Thread Class vs Runnable Interface
1. If we extend the Thread class, our class cannot extend any other class because Java doesn’t support multiple inheritance.
But, if we implement the Runnable interface, our class can still extend other base classes.
2. We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt methods like
yield(), interrupt() etc. that are not available in Runnable interface.
Multithreading in Java by Implementing Runnable Interface
Output –
class MultiThread implements Runnable {
Main Thread id: 1
@Override Thread 10 is running
public void run() { Main Thread id: 1
for (int i = 0; i < 10; i++) { Main Thread id: 1
System.out.println("Thread " + Thread.currentThread().getId()+ " is running"); Main Thread id: 1
} Thread 10 is running
} Thread 10 is running
} Thread 10 is running
Thread 10 is running
public class JavaApplication4 { Main Thread id: 1
Thread 10 is running
public static void main(String[] args) { Main Thread id: 1
Thread object = new Thread(new MultiThread()); Main Thread id: 1
object.start(); Main Thread id: 1
for (int i = 0; i < 10; i++) { Main Thread id: 1
System.out.println("Main Thread id: " + Thread.currentThread().getId()); Main Thread id: 1
} Thread 10 is running
} Thread 10 is running
} Thread 10 is running
Thread 10 is running
Sleep method in java
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
Syntax of sleep() method in java
The Thread class provides two methods for sleeping a thread:
• public static void sleep(long miliseconds)throws InterruptedException
• public static void sleep(long miliseconds, int nanos)throws InterruptedException
Example of sleep method in java
class TestSleepMethod1 extends Thread{
public void run(){
for(int i=1;i<5;i++){
try{Thread.sleep(500);}catch(InterruptedException
e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod1();
t1.start();
}
}
Priority of a Thread (Thread Priority)
In a Multi threading environment, thread scheduler assigns processor to a thread based on priority of thread. Whenever we create a thread in
Java, it always has some priority assigned to it. Priority can either be given by JVM while creating the thread or it can be given by programmer
explicitly.
Accepted value of priority for a thread is in range of 1 to 10.
There are are 3 basic priority constants defined in the Thread Class –
}
}
ow is a table of differences between Git and GitHub:
GitHub is maintained by
4. Git is maintained by linux. microsoft.
• Servlet technology is robust and scalable because of java language. Before Servlet, CGI (Common Gateway
Interface) scripting language was common as a server-side programming language. However, there were
many disadvantages to this technology.
• There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet, HttpServlet,
ServletRequest, ServletResponse, etc.
What is a Servlet?
Servlet is a technology which is used to create a web application.
Servlet is an API that provides many interfaces and classes including documentation.
Servlet is an interface that must be implemented for creating any Servlet.
Servlet is a class that extends the capabilities of the servers and responds to the incoming requests. It can
respond to any requests.
Servlet is a web component that is deployed on the server to create a dynamic web page.
What is a web application?
A web application is an application accessible from the web. A web application is composed of web components like Servlet,
JSP, Filter, etc. and other elements such as HTML, CSS, and JavaScript. The web components typically execute in Web Server
and respond to the HTTP request.
CGI (Common Gateway Interface)
CGI technology enables the web server to call an external program and pass HTTP request information to the external program
to process the request. For each request, it starts a new process.
Disadvantages of CGI
Website: static vs dynamic It is a collection of related web pages that may contain text,
images, audio and video.
HTTP Requests It is the request send by the computer to a web server that
contains all sorts of potentially interesting information.
Get vs Post It gives the difference between GET and POST request.
Website
• Website is a collection of related web pages that may contain text, images, audio and video.
• The first page of a website is called home page.
• Each website has specific internet address (URL) that you need to enter in your browser to access
a website.
A website can be of two types:
• Static Website
• Dynamic Website
Static website
• Static website is the basic type of website that is easy to create.
• You don't need the knowledge of web programming and database design to create a static website.
• Its web pages are coded in HTML.
The codes are fixed for each page so the information contained in the page does not change and it
looks like a printed page.
Dynamic website
• Dynamic website is a collection of dynamic web pages whose content changes dynamically.
• It accesses content from a database or Content Management System (CMS). Therefore, when you
alter or update the content of the database, the content of the website is also altered or updated.
Static Website Dynamic Website
Prebuilt content is same every time the page is loaded. Content is generated quickly and changes regularly.
It uses the HTML code for developing a website. It uses the server side languages such
as PHP,SERVLET, JSP, and ASP.NET etc. for
developing a website.
It sends exactly the same response for every request. It may generate different HTML for each of the request.
The content is only changed when someone publishes The page contains "server-side" code which allows the
and updates the file (sends it to the web server). server to generate the unique content when the page is
loaded.
Flexibility is the main advantage of static website. Content Management System (CMS) is the main
advantage of dynamic website.
HTTP (Hyper Text Transfer Protocol)
• It is the data communication protocol used to establish communication between client and server.
• HTTP is TCP/IP based communication protocol, which is used to deliver the data like image files, query
results, HTML files etc on the World Wide Web (WWW) with the default port is TCP 80.
• It provides the standardized way for computers to communicate with each other.
HTTP Requests
• The request sent by the computer to a web server, contains all sorts of potentially interesting information; it is
known as HTTP requests.
• The HTTP client sends the request to the server in the form of request message which includes following
information:
• The Request-line
• The analysis of source IP address, proxy and port
• The analysis of destination IP address, protocol, port and host
• The Requested URI (Uniform Resource Identifier)
• The Request method and Content
• The User-Agent header
• The Connection control header
• The Cache control header
The HTTP request methods are:
HTTP Request Description
GET Asks to get the resource at the requested URL.
POST Asks the server to accept the body info attached. It is like GET request with extra
info sent with the request.
HEAD Asks for only the header part of whatever a GET would return. Just like GET but
with no body.
TRACE Asks for the loopback of the request message, for testing or troubleshooting.
PUT Says to put the enclosed info (the body) at the requested URL.
OPTIONS Asks for a list of the HTTP methods to which the thing at the request URL can
respond
Get vs. Post
There are many differences between the Get and Post request. Let's see these differences:
GET POST
1) In case of Get request, only limited In case of post request, large amount of
amount of data can be sent because data is data can be sent because data is sent in
sent in header. body.
2) Get request is not secured because data Post request is secured because data is not
is exposed in URL bar. exposed in URL bar.
GET/RegisterDao.jsp?name1=value1&name2=value2
As we know that data is sent in request header in case of get request. It is the default request type. Let's see what
information is sent to the server.
Some other features of GET requests are:
As we know, in case of post request original data is sent in message body. Let's see how information is passed to
the server in case of post request.
JSP Elements
Expression Elements
<%= new java.util.Date() %>
<br/>
JSP Comments (Unexecutable Parts)
<%= 25*4 %>
<% -- response.sendRedirect("http://studyeasy.org"); --%>
<br/>
Declarative Elements
<%! JSP Scriplets
String message(){ <%
return "I love JSP"; for(int i=0;i<10;i++){
} out.print("<br/>");
%> out.print(i);
}
<%= message() %> %>
List of Content Types
There are many content types. The commonly used content types are given below:
text/html
text/plain
application/msword
application/vnd.ms-excel
application/jar
application/pdf
application/octet-stream
application/x-zip
images/jpeg
images/png
images/gif
audio/mp3
video/mp4
video/quicktime etc.
Servlet API
• The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.
• The javax.servlet package contains many interfaces and classes that are used by the servlet or web container.
These are not specific to any protocol.
• The javax.servlet.http package contains interfaces and classes that are responsible for http requests only.
Interfaces in javax.servlet package
There are many interfaces in javax.servlet package. They are as follows:
Servlet
ServletRequest
ServletResponse
RequestDispatcher
ServletConfig
ServletContext
SingleThreadModel
Filter
FilterConfig
FilterChain
ServletRequestListener
ServletRequestAttributeListener
ServletContextListener
ServletContextAttributeListener
Classes in javax.servlet package
There are many classes in javax.servlet package. They are as follows:
GenericServlet
ServletInputStream
ServletOutputStream
ServletRequestWrapper
ServletResponseWrapper
ServletRequestEvent
ServletContextEvent
ServletRequestAttributeEvent
ServletContextAttributeEvent
ServletException
UnavailableException
Interfaces in javax.servlet.http package
There are many interfaces in javax.servlet.http package. They are as follows:
HttpServletRequest
HttpServletResponse
HttpSession
HttpSessionListener
HttpSessionAttributeListener
HttpSessionBindingListener
HttpSessionActivationListener
HttpSessionContext (deprecated now)
Classes in javax.servlet.http package
There are many classes in javax.servlet.http package. They are as follows:
HttpServlet
Cookie
HttpServletRequestWrapper
HttpServletResponseWrapper
HttpSessionEvent
HttpSessionBindingEvent
HttpUtils (deprecated now)
Servlet Interface
Servlet interface provides common behavior to all the servlets.
Servlet interface defines methods that all servlets must implement.
Servlet interface needs to be implemented for creating any servlet (either directly or indirectly). It provides 3 life cycle
methods that are used to initialize the servlet, to service the requests, and to destroy the servlet and 2 non-life cycle
methods.
Methods of Servlet interface
There are 5 methods in Servlet interface. The init, service and destroy are the life cycle methods of servlet. These are invoked
by the web container.
Method Description
public void init(ServletConfig config) initializes the servlet. It is the life cycle method of servlet and
invoked by the web container only once.
public void service(ServletRequest request,ServletResponse provides response for the incoming request. It is invoked at each
response) request by the web container.
public void destroy() is invoked only once and indicates that servlet is being destroyed.
public String getServletInfo() returns information about servlet such as writer, copyright, version
etc.
public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{
import java.io.*;
import javax.servlet.*; res.setContentType("text/html");
PrintWriter out=res.getWriter();
public class First implements Servlet{ out.print("<html><body>");
ServletConfig config=null; out.print("<b>hello simple servlet</b>");
out.print("</body></html>");
public void init(ServletConfig config){
}
this.config=config; public void destroy(){System.out.println("servlet is
System.out.println("servlet is destroyed");}
initialized"); public ServletConfig getServletConfig(){return config;}
} public String getServletInfo(){return "copyright 2007-1010";}
}
Life Cycle of a Servlet (Servlet Life Cycle)
The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet:
Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service()
method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete,
etc. methods as appropriate.
The doGet() and doPost() are most frequently used methods with in each service request. Here is the signature of
these two methods.
The doGet() Method
A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by
doGet() method.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The doPost() Method
A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The destroy() Method
The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database
connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection. The destroy method definition looks like this −
public void destroy() {
// Finalization code...
}
Architecture Diagram
The following figure depicts a typical servlet life-cycle scenario.
First the HTTP requests coming to the server are delegated to the servlet container.
The servlet container loads the servlet before invoking the service() method.
Then the servlet container handles multiple requests by spawning multiple threads, each thread executing the service() method
of a single instance of the servlet.
Agenda -20/5/2021
1 Jsp form design
2 servelets form design
3 jsp servelets form design with validation
4 jsp elements ( expression , scriplets , comments, declaration , derective )
5 include files into jsp file
6 import clases into jsp file
7 get and post method
Declaration <%! Declarations %> <%! Public int count =0; %>
Features of JUnit
JUnit is an open source framework, which is used for writing and running tests.
Provides annotations to identify test methods.
Provides assertions for testing expected results.
Provides test runners for running tests.
JUnit tests allow you to write codes faster, which increases quality.
JUnit is elegantly simple. It is less complex and takes less time.
JUnit tests can be run automatically and they check their own results and provide immediate feedback. There's no need to
manually comb through a report of test results.
JUnit tests can be organized into test suites containing test cases and even other test suites.
JUnit shows test progress in a bar that is green if the test is running smoothly, and it turns red when a test fails.
What is a Unit Test Case ?
A Unit Test Case is a part of code, which ensures that another part of code (method) works as expected.
To achieve the desired results quickly, a test framework is required. JUnit is a perfect unit test framework for Java
programming language.
Lambda Expressions
• Lambda expression is a new and important feature of Java which was included in Java SE 8.
• It provides a clear and concise way to represent one method interface using an expression.
• The Lambda expression is used to provide the implementation of an interface which has
functional interface.
• It saves a lot of code. In case of lambda expression, we don't need to define the method again for
providing the implementation. Here, we just write the implementation code.
• Java lambda expression is treated as a function, so compiler does not create .class file.
Functional Interface
• Lambda expression provides implementation of functional interface.
• An interface which has only one abstract method is called functional interface.
• Java provides an anotation @FunctionalInterface, which is used to declare an interface as
functional interface.
Why use Lambda Expression
• To provide the implementation of Functional interface.
• Less coding.
Java Lambda Expression Syntax
(argument-list) -> {body}
Output:
Drawing 10
With Lambda Expression
Now, we are going to implement the above example with the help of Java lambda expression.
@FunctionalInterface //It is optional
interface Drawable{
public void draw();
}
public class LambdaExpressionExample2 {
public static void main(String[] args) {
int width=10;
//with lambda
Drawable d2=()->{
System.out.println("Drawing "+width);
};
d2.draw();
}
}
Output:
Drawing 10
Java Lambda Expression Example: No Parameter
interface Sayable{
public String say();
}
public class LambdaExpressionExample3{
public static void main(String[] args) {
Sayable s=()->{
return "I have nothing to say.";
};
System.out.println(s.say());
}
}
Output:
interface Sayable{
public String say(String name);
} Output:
public class LambdaExpressionExample4{ Hello, Sonoo
Hello, Sonoo
public static void main(String[] args) {
// Lambda expression with single parameter.
Sayable s1=(name)->{
return "Hello, "+name;
};
System.out.println(s1.say("Sonoo"));
// You can omit function parentheses
Sayable s2= name ->{
return "Hello, "+name;
};
System.out.println(s2.say("Sonoo"));
}
}
Java Lambda Expression Example: Multiple Parameters
interface Addable{
int add(int a,int b);
}
public class LambdaExpressionExample5{
public static void main(String[] args) {
// Multiple parameters in lambda expression
Addable ad1=(a,b)->(a+b);
System.out.println(ad1.add(10,20));
// Multiple parameters with data type in lambda expression
Addable ad2=(int a,int b)->(a+b);
System.out.println(ad2.add(100,200));
}
}
Output:
30
300
Java Lambda Expression Example: with or without return keyword
In Java lambda expression, if there is only one statement, you may or may not use return keyword. You must use return keyword when lambda
expression contains multiple statements.
interface Addable{
int add(int a,int b);
} Output:
public class LambdaExpressionExample6 {
public static void main(String[] args) { 30
// Lambda expression without return keyword. 300
Addable ad1=(a,b)->(a+b);
System.out.println(ad1.add(10,20));
// Lambda expression with return keyword.
Addable ad2=(int a,int b)->{
return (a+b);
};
System.out.println(ad2.add(100,200));
}
}
Java Lambda Expression Example: Foreach Loop
import java.util.*;
public class LambdaExpressionExample7{
Output:
public static void main(String[] args) {
ankit
List<String> list=new ArrayList<String>(); mayank
list.add("ankit"); irfan
list.add("mayank");
jai
list.add("irfan");
list.add("jai");
list.forEach(
(n)->System.out.println(n)
);
}
}
Java Lambda Expression Example: Multiple Statements
@FunctionalInterface
interface Sayable{
String say(String message);
}
public class LambdaExpressionExample8{
public static void main(String[] args) {
// You can pass multiple statements in lambda expression
Sayable person = (message)-> {
String str1 = "I would like to say, ";
String str2 = str1 + message;
return str2;
};
System.out.println(person.say("time is precious."));
}
}
Output:
I would like to say, time is precious.
• Default method vs static method in an interface in Java
• An interface in Java is similar to class but, it contains only abstract
methods and fields which are final and static.
• Since Java8 static methods and default methods are introduced in
interfaces.
• Default Methods - Unlike other abstract methods these are the
methods can have a default implementation. If you have default
method in an interface, it is not mandatory to override (provide body)
it in the classes that are already implementing this interface.
• You can access the default methods of an interface using the objects of
the implementing classes.
interface MyInterface{
public static int num = 100;
public default void display() {
System.out.println("display method of MyInterface");
}
}
public class InterfaceExample implements MyInterface{
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.display();
}
}
Output: display method of MyInterface
Static methods - They are declared using the static keyword and will be
loaded into the memory along with the interface. You can access static
methods using the interface name.
If your interface has a static method you need to call it using the name
of the interface, just like static methods of a class.
interface MyInterface{
public void demo();
public static void display() {
System.out.println("This is a static method");
}
}
public class InterfaceExample{
public void demo() {
System.out.println("This is the implementation of the demo method");
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.demo();
MyInterface.display();
}
}
Output
This is the implementation of the demo method
This is a static method
Difference between static and default methods −
Calling the method
You can call a static method using the name of an interface.
To call a default method you need to use the object of the implementing class.
Overriding the method
If you want, you can override a default method of an interface from the implementing class.
interface MyInterface{
public static int num = 100;
public default void display() {
System.out.println("display method of MyInterface");
}
}
public class InterfaceExample implements MyInterface{
public void display() {
System.out.println("display method of class");
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.display();
}
}
Output: display method of class
interface MyInterface{
public static void display() {
System.out.println("Static method of the interface");
}
}
public class InterfaceExample{
public static void display() {
System.out.println("Static method of the class");
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
MyInterface.display();
InterfaceExample.display();
}
}
Output:Static method of the interface
Static method of the class
Stream API In java8
• A Stream in Java can be defined as a sequence of elements from a source. The source of elements here refers
to a Collection or Array that provides data to the Stream.
• Stream operations
1. Intermediate Operations
2. Terminal or Aggregate Operations
• Java streams are designed in such a way that most of the stream operations (called intermediate operations)
return a Stream.
• This helps to create a chain of stream operations. This is called stream pipe-lining.
• Java streams also support the aggregate or terminal operations on the elements. The aggregate operations are
operations that allow us to express common manipulations on stream elements quickly and clearly, for
example, finding the max or min element, finding the first element matching giving criteria, and so on.
Difference between Collections and streams
• A Collection is an in-memory data structure that holds all the data structure’s values.
• Every element in the Collection has to be computed before it can be added to the Collection.
• While a Stream is conceptually a pipeline in which elements are computed on demand.
• This concept gives rise to significant programming benefits. The idea is that a user will extract only the
values they require from a Stream.
Not thread safe : Unlike old java.util.Date which is not thread safe the new date-time API is immutable and
doesn’t have setter methods.
Less operations : In old API there are only few date operations but the new API provides us with many date
operations.
Java 8 under the package java.time introduced a new date-time API, most important classes among them are :
Serialization is a mechanism for storing an object’s states into a persistent storage like disk files, databases, or
sending object’s states over the network. The process of retrieval and construction of objects from disk files,
databases and network is called de-serialization.
Here are some examples of using serialization:
- Storing data in an object-oriented way to files on disk, e.g. storing a list of Student objects.
- Sending data over the network in form objects, e.g. sending messages as objects in chat application.
JRE System library
• JRE System Library implements the Java API in Eclipse IDE. So all the predefined functions of Java, can be
accessed by the Java Programs written in Eclipse IDE because of this JRE System Library.
• Eclipse IDE adds the JRE System Library to the Java Projects on their creation automatically.
Annotations
• Annotations in java provide additional information to the compiler and JVM.
• An annotation is a tag representing metadata about classes , interfaces , variables , methods and fields.
S.No List Set
1. The list implementation allows us to add the same or duplicate The set implementation doesn't allow us to add the same or
elements. duplicate elements.
2. The insertion order is maintained by the List. It doesn't maintain the insertion order of elements.
3. List allows us to add any number of null values. Set allows us to add at least one null value in it.
4. The List implementation classes are LinkedList and ArrayList. The Set implementation classes are TreeSet, HashSet and
LinkedHashSet.
5. We can get the element of a specified index from the list using We cannot find the element from the Set based on the index
the get() method. because it doesn't provide any get method().
6. It is used when we want to frequently access the elements by It is used when we want to design a collection of distinct
using the index. elements.
ArrayList Linked List