HTML & CSS Java script Bootstrap Angular React
Java Python PHP .Net Node JS
Tomcat JBoss Glassfis Oracle Weblogic IBM WebSphere IIS
Oracle MySQL SQL Server Postgres Mongo DB Casandra Hbase Hive
Git Hub : For Code Integration JIRA : Project Management / Bug Tracking / Work Assignment SonarQube : For Code Quality Checking JUnit : For Unit Testing JMeter : For Performance Testing Jenkins : For Deployment (Automated Deployment)
Amazon ---> AWS Microsoft ---> Azure Google -----> GCP Oracle Cloud IBM Cloud VM Ware Cloud Alibaba CLoud etc.....
1) Understand Requirements of Project 2) Analyze requirements 3) Design / Planning 4) Database Design 5) Development (Backend development) 6) Unit Testing 7) Code Review 8) Code Integration (Git Hub) 9) Frontend Development 10) Frontend + Backend Integration 11) Deployment 12) Support / Maintenence
1) J2SE 2) J2EE 3) J2ME
J2SE / JSE ---> JAVA STANDARD EDITION
J2EE / JEE ---> JAVA ENTERPRISE EDITION
J2ME / JME ---> JAVA MICRO / MOBILE EDITION
1) Stand-alone applications 2) Web applications 3) Mobile Applications
Simple
Platform Independent
Robust (Strong)
OOPS (Object Oriented Programming System)
Secure
Distributed
Portable
Dynamic
Java Slogan : WORA (Write Once Run Anywhere)
Download and Install Java Software
JDK (Java Development Kit) JRE (Java Runtime Environment)
Q) What is the difference between JDK, JRE & JVM ?
Set Path for Java
We can write java programs in any text editor
Note Pad Note Pad++ Edit Plus
In companies we will use IDE to develop java programs/projects
Eclipse MyEclipse Netbeans STS (Spring Tool Suite) IntelliJ
package statements import statements class declaration variables methods
// -----------hello.java---------
class hello {
public static void main(String... args) {
System.out.println("Welcome To Ashok IT...!!");
System.out.println("Welcome to Java");
}
}
// javac hello.java - to compile
// java hello - to run
class demo {
public static void main (String... args){
System.out.println("Hello World");
System.out.println("Welcome to Java");
}
}
It is used to convert from one format to antoher format
3 types of translators available
1) Interpreter 2) Compiler 3) Assembler
Interpreter will convert the program line by line ( performance is slow )
Compiler will convert all the lines of program at a time ( performance is fast )
Assembler is used to convert assembler programming languages into machine
language
Data types are used to specify type of the data
Data types are divided into 2 categories
1) Primitive / Pre-Defined Data Types 1) Integral Data Types - byte - short - int - long 2) Decimal Data Types - float - double 3) Character Data Type - char 4) Boolean Data Type - boolean 2) Non-Primitive / Referenced Data Types - Arrays - Strings - Classes
// Intergral Data Type
age = 30;
phno = 66868686868;
studentscnt = 40;
balance = - 3000;
We have 4 data types in this category
For These 4 data types memory & range is different
1) byte ----> default value is 0 ----> 1 byte 2) short ----> default value is 0 ----> 2 bytes 3) int ----> default value is 0 ----> 4 bytes 4) long ----> default value is 0l ----> 8 bytes
// Decimal Data Types
petrol price = 110.567979;
stockPrice = 334.3279797979797979;
percentage = 9.8;
weight = 55.6;
height = 5.6;
length = 10.2;
In this category we have 2 data types
1) float ----> 4 bytes ---> upto 6 decimal points 2) double -----> 8 bytes --> upto 15 decimal points
// Character Data Type
gender = 'm';
rank = '1';
// Boolean Data Type
isPass = true;
isFail = false;
isMarried = true;
isOdd = true;
isEven = false;
Variables are used to store the data / value
To store the data into variable we need to specify data type
To store data into variables we need to perform 2 steps
1) Variable Declaration (defining variable with data type) Ex: byte age ; 2) Variable Intialization (storing value into variable) Ex: age = 20;
We can complete declaration and initialization in single line
byte age = 20;
// ============ Variables Program ============
class var {
public static void main (String... args) {
int age = 20;
System.out.println(age);
float a = 25.01f;
System.out.println(a);
double price = 120.87;
System.out.println(price);
char gender = 'm';
System.out.println(gender);
boolean pass = true;
System.out.println(pass);
}
}
int age ;
class Hello {
// code
}
main ( ) {
//logic
}
Rule-1 : Java will allow only below charaters for identifiers
1) a - z 2) A - Z 3) 0 to 9 4) $ (dollar) 5) _ (underscore) Ex: name -----> valid name@ -----> invalid age# ------> invalid
Rule-2 : Identifier should not start with digit (first character shouldn't be digit)
1age --------> invalid age2 ------> valid name3 -----> valid _name -----> valid $name ------> valid @name ------> invalid $_amt --------> valid _1bill -----------> valid
Rule-3 : Java reserved words shouldn't be used as identifier (53 reserved words)
int byte = 20; -------> invalid bcz byte is a reserved word byte for = 25; -------> invalid bcz for is a reserved word int try = 30; ------> invalid bcz try is a reserved word long phno = 797979799 -----> valid
Rule-4 : Spaces are not allowed in identifiers
int mobile bill = 400; // invalid int mobile_bill = 400 ; // valid
Rule-5 : Java is case sensitive language 'name' & 'NAME' both are not same
// Naming Conventions for Class
class Hello {
}
class HelloWorld {
}
class UserManagementService{
}
class WelcomeRestController {
}
// Naming Convention for Variables
int age ;
int userAge;
long creditCardNumber ;
// Naming Convention for Methods
main ( ) {
}
save ( ) {
}
saveUser( ) {
}
getWelcomeMsg ( ) {
}
// Naming Conventions for Constants
final int MIN_AGE = 21;
final int MAX_AGE = 60 ;
int PI = 3.14;
// Naming Conventions for Packages
java.lang
java.io
java.util
in.ashokit
com.oracle
com.ibm
int a = 10 ;
int b = 20 ;
int c = a + b;
We have below operators in java
1) Arithmetic Operators 2) Logical Operators 3) Relational Operators 4) Assignment Operators 5) new operator 6) dot (.) operator 7) ternary operator ( Conditional Operator )
Arithmetic Operators are used to perform Arithmetic Operations ( Calculations )
1) Addition -----> + 2) Subtraction ----> - 3) Division ------------> / (quotient) 4) Multiplication ----------> * 5) Modulus ---------> % (reminder) 6) Increment -------> ++ 7) Decrement ------> --
Increment ( ++ ) is used to increase the value of variable by 1
Increment is divided into 2 types
1) Post Increment ( a ++ ) 2) Pre Increment ( ++ a)
Decrement ( -- ) is used to decrease the value of variable by 1
Decrement is divided into 2 types
1) Post Decrement ( a -- ) 2) Pre-Decrement ( --a )
// Increment and Decrement Operators
class PostIncrement {
public static void main(String... args){
int a = 5;
System.out.println(a++); // it will print 5 then it will become 6
a++; // it will become 7
System.out.println(a++); // it will print 7 then it will become 8
System.out.println(a); // it will print 8
}
}
class PreIncrement {
public static void main(String... args){
int a = 5;
System.out.println ( ++ a ); // it will become 6 then it will print
++ a ; // it will become 7
System.out.println(++a); // it will become 8 then it will print
System.out.println(a); // it will print 8
}
}
class PostPreIncrement {
public static void main(String... args){
int a = 5;
int b = ++a + a++ + a++ + ++a;
// int b = 6 + 6 + 7 + 9 ==> 28
System.out.println(b);
}
}
class Decrement {
public static void main(String... args){
int a = 5;
System.out.println( a -- ); // it will print 5 then it will become 4
System.out.println( -- a); // it will become 3 then it will print 3
}
}
class PostPreDecrement {
public static void main(String... args){
int a = 5;
int b = a-- + --a + a--;
// int b = 5 + 3 + 3
System.out.println ( b );
}
}
>, < , >= , <=, !=, ==
AND ----> &&
OR -----> ||
NOT -----> !
int a = 10 ;
ClassName refVar = new ClassName( );
Note: Creating object means allocating memory in heap area
System.out.println ( );
java.lang.String;
java.util.ArrayList;
// Conditional Operator Syntax
( condition ) ? expression-1 : expression-2
String str = "ashokit";
if (str instanceof String ) {
//logic
}
Java program code will execute line by line sequentially (this is default behaviour)
In project code should execute based on user operation
To satisfy user requirement our code should execute based on some conditions
Using Control Statements we can control program execution flow
Control Statements are divided into 3 types
1) Decision Making Statements / Conditional Statements 2) Looping Statements 3) Transfer / Branching Statements
Execute the code only once based on condition
1) simple if 2) if - else 3) if - else - if - else -if - else (if else ladder) 4) switch
// if Syntax
if ( condition ){
// stmt - 1
// stmt - 2
// stmt - 3
}
// or
if (condition )
//stmt
// Simple if Demo
class SimpleIf{
public static void main(String... args){
int a = 100;
int b = 20;
if( a > b ) {
System.out.println("a is greater than b");
System.out.println("Completed");
}
System.out.println("Bye");
}
}
// if-else Demo
class IfElseDemo{
public static void main (String... args){
int age = 16 ;
if ( age >= 18 ) {
System.out.println("Eligible For Vote") ;
} else {
System.out.println("Not eligible for Vote");
}
}
}
Requirement :
int a = 20; if a > 0 -----> display msg as 'a is positive number' if a < 0 ----> display msg as 'a is negative number' When above both conditions are failed then display msg as 'a is zero'
// else-if ladder syntax
if ( condition_1 ) {
// stmt - 1
} else if ( condition_2 ) {
// stmt - 2
} else if ( condition_3 ) {
//stmt - 3
} else {
//stmt-4
}
// else-if ladder Demo
class IfElseLadderDemo {
public static void main(String... args){
int a = 0;
if( a > 0) {
System.out.println(" a is positive number ");
} else if ( a < 0 ) {
System.out.println("a is negative number");
} else {
System.out.println("a is zero");
}
}
}
// Develop a java program to decide role of software engineer based on his/her experience
// 0 - 2 year exp -----> Associate Engineer
// 3 - 5 years exp -----> Software Engineer
// 6 - 9 years exp -----> Sr.Software Engineer
// 10 - 13 years exp ----> Manager
class RoleFinder {
public static void main(String... args) {
int exp = 13;
if( exp >= 0 && exp <= 2 ){
System.out.println("Associate Engineer");
}else if ( exp >= 3 && exp <=5 ){
System.out.println("Software Engineer");
}else if( exp >= 6 && exp <=9 ){
System.out.println("Sr. Software Engineer");
}else if( exp >= 10 && exp <=13 ){
System.out.println("Manager");
}else {
System.out.println("Role Not Found");
}
}
}
How to read data from keyboard In Java
1) BufferedReader ( java.io ) 2) Scanner ( java.util ) 3) Command Line Arguments (input for main method)
// ---------------------BufferedReader Program-----------------------
import java.io.*;
class RoleFinder {
public static void main(String... args) throws Exception {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String str = br.readLine ( );
int exp = Integer.parseInt(str);
if( exp >= 0 && exp <= 2 ){
System.out.println("Associate Engineer");
}else if ( exp >= 3 && exp <=5 ){
System.out.println("Software Engineer");
}else if( exp >= 6 && exp <=9 ){
System.out.println("Sr. Software Engineer");
}else if( exp >= 10 && exp <=13 ){
System.out.println("Manager");
}else {
System.out.println("Role Not Found");
}
}
}
// Write a java program to find given number is odd or even
import java.io.*;
class OddOrEven {
public static void main(String... args) throws Exception {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader ( isr );
System.out.println("Enter Number");
String str = br.readLine ( );
int num = Integer.parseInt (str);
if( num % 2 == 0){
System.out.println("It is even");
}else{
System.out.println("It is odd");
}
}
}
Assignment -1 : Write a java program to check given number is a prime number or not
Assignment -2 : Write a java program to check given year is a leap year or not
// switch Syntax
switch ( case ) {
case 1 : // stmt - 1
break;
case 2 : // stmt - 2
break;
case 3 : // stmt - 3
break;
.....
default : // stmt - default
}
// Write a java program to read a number from keyboard. Based on the given number print week of the day using 'switch' case.
import java.io.*;
class WeekDay {
public static void main(String... args) throws Exception {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Enter number");
String str = br.readLine ( );
int num = Integer.parseInt(str);
switch ( num ) {
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;
default : System.out.println("Day not found");
}
}
}
Conclusion
1) 'if' accepts only boolean value (or) boolean expression 2) 'switch' accepts numbers, char & strings (added in java 1.7v) 3) switch will not accept boolean and decimal values 4) switch cases should belongs to same type 5) switch case datatype and switch case input value should belongs to same datatype 6) 'default' case is optional in 'switch case' 7) 'break' keyword is also optional in 'switch case'
Loops are used to execute statements repeatedly
In java we have below loops
1) while loop 2) do-while loop 3) for loop 4) for-each loop (arrays & collections)
// while loop syntax
while ( condition ){
//stmts
}
// Write a java program to print numbers from 1 to 10 using while loop
class WhileDemo {
public static void main (String... args){
int i = 1;
while ( i <= 10 ){
System.out.println(i);
i++;
}
}
}
// do-while loop syntax
do{
//stmts
} while (condition );
// Write a java program to print numbers from 1 to 10 using do-while loop
class DoWhile{
public static void main(String... args){
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 10);
}
}
Q) What is the difference between while and do-while ?
while ==> It will check the condition first then it will execute the statements
do-while ==> It will execute statement first then it will check condition.
Note: Even if condition is not satisfied our statement will execute once.
// for-loop syntax
for ( initialization ; condition ; increment / decrement ) {
//stmts
}
// Write java program to print numbers from 1 to 10 using for loop
class ForLoop {
public static void main(String... args) {
for ( int i = 1 ; i <= 10 ; i++ ) {
System.out.println(i);
}
}
}
// Writing one loop inside another loop is called as Nested loop
for ( int i = 1; i <= 5 ; i++ ){
for ( int j = 1; j< = 5; j++){
}
}
// Write a java program to print below pattern using loops
*
* *
* * *
* * * *
* * * * *
class NestedLoop {
public static void main(String... args){
for ( int i = 1; i <=5 ; i++ ){
for ( int j = 1; j <= i ; j++ ){
System.out.print("*");
}
System.out.println();
}
}
}
// Write a java program to print below pattern
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
class NestedLoop {
public static void main(String... args){
for ( int i = 1; i <=5 ; i++ ){
for ( int j = 1; j <= i ; j++ ){
System.out.print(j);
}
System.out.println();
}
}
}
// break demo
class Break {
public static void main(String... args){
for (int i = 1; i<= 10; i++ ){
if (i >= 5 ){
break;
}
System.out.println(i);
}
}
}
// continue demo
class Continue {
public static void main(String... args){
for (int i = 1; i<= 10; i++ ){
if(i == 6 ) {
continue;
}
System.out.println(i);
}
}
}
// Write a java program to read shoes brand name from keyboard, based on brand name print brand slogan like below
// Nike -> Just do it
// Adidas -> Impossible is nothing
// Puma -> Forever Faster
// Reebok -> I Am What I Am
import java.io.*;
class Shoes {
public static void main(String... args) throws Exception {
InputStreamReader isr = new InputStreamReader (System.in);
BufferedReader br = new BufferedReader ( isr );
System.out.println ("Enter Brand Name");
String brand = br.readLine ( );
switch ( brand ) {
case "Nike" : System.out.println("Just do it");
break;
case "Adidas" : System.out.println("Impossible is nothing");
break;
case "Puma" : System.out.println("Forever Faster");
break;
case "Reebok" : System.out.println("I Am What I Am");
break;
default : System.out.println("Brand Not Found");
}
}
}
// Write a java program to read person basic salary and calculate Provident Fund amount from the basic salary
// Formula : Provident Fund is 12 % of Basic Salary
import java.io.*;
class EmpPf {
public static void main(String... args) throws Exception {
InputStreamReader isr = new InputStreamReader( System.in );
BufferedReader br = new BufferedReader (isr);
System.out.println("Enter Basic Salary");
String str = br.readLine ( );
double basicSalary = Double.parseDouble ( str );
double pf = basicSalary * 12 / 100;
System.out.println(pf);
}
}
// Write a java program to read person age and person salary and print his eligibility for marriage
// Condtion : If person age lessthan 30 and salary greater than 1 lakh then eligible for marriage
import java.io.*;
class Marriage {
public static void main (String... args) throws Exception {
InputStreamReader isr = new InputStreamReader( System.in );
BufferedReader br = new BufferedReader(isr);
System.out.println("Enter Your Age");
String str1 = br.readLine ( );
int age = Integer.parseInt ( str1 );
System.out.println("Enter Your Salary");
String str2 = br.readLine ( );
double salary = Double.parseDouble(str2);
if ( age < 30 && salary > 100000 ) {
System.out.println("You are eligible for marriage");
} else {
System.out.println("You are not eligible for marriage");
}
}
}
// Write a java program to print Right Triangle Star Pattern
class RightTriangle {
public static void main(String... args) {
for( int i = 1; i<=5 ; i ++ ){
for( int j = 1; j<=i ; j++ ){
System.out.print ("* ");
}
System.out.println();
}
}
}
// Write a java program to print left traingle start pattern
*
* *
* * *
* * * *
* * * * *
class LeftTriangle {
public static void main(String... args) {
for( int i = 1; i<=5 ; i ++ ){
for ( int k = 5-i ; k >= 1 ; k-- ){
System.out.print(" ");
}
for( int j = 1; j<=i ; j++ ){
System.out.print ("*");
}
System.out.println();
}
}
}
// Write a java program to print Pyramid pattern
*
* *
* * *
* * * *
* * * * *
class Pyramid {
public static void main(String... args) {
for( int i = 1; i<=5 ; i ++ ){
for ( int k = 5-i ; k >= 1 ; k-- ){
System.out.print(" ");
}
for( int j = 1; j<=i ; j++ ){
System.out.print ("* ");
}
System.out.println();
}
}
}
// variable declaration
int a ;
// variable intialization
a = 20 ;
int i = 45; // this is valid
int b = 20, 30 ; // this is in-valid (we can store only one value)
// store one student subject wise marks (we need 6 variables for 6 subjects for one student)
int sub1 = 78;
int sub2 = 98;
int sub3 = 79;
int sub4 = 90;
int sub5 = 95;
int sub6 = 87;
// i want to store 50 students subject wise marks (we need 300 variables to store all students marks)
// Array Declaration
datatype [ ] variableName;
dataype variableName [ ] ;
datatype [ ]variableName ;
// Array Creation
variableName = new datatype [ size ] ;
datatype[ ] variableName = new datatype [ size ] ;\
int[ ] arr = new int [ 5 ];
Note: At the time of creating the array the size is mandatory
// Array Demo
class ArrayDemo {
public static void main(String... args){
int [ ] arr = new int [ 3 ] ;
arr[0] = 100;
arr[1] = 101;
arr[2] = 102;
System.out.println ( arr [ 0 ] ) ;
System.out.println ( arr [ 1 ] ) ;
System.out.println ( arr [ 2 ] ) ;
}
}
// Array length Property
class ArrayDemo {
public static void main(String... args){
int [ ] arr = new int [ 5 ] ;
arr[0] = 100;
arr[1] = 101;
arr[2] = 102;
System.out.println ( arr.length ) ;
}
}
class ArrayDemo {
public static void main (String... args) {
int arr[ ] = new int [ 3 ] ;
arr[0] = 100;
arr[1] = 101;
arr[2] = 102;
for( int i = 0 ; i < arr.length ; i ++ ) {
System.out.println ( arr [i] );
}
}
}
class ArrayDemo {
public static void main(String... args) {
boolean [ ] arr = new boolean [ 3 ] ;
arr [2] = true;
for( int i = 0 ; i < arr.length ; i ++ ) {
System.out.println ( arr [i] );
}
}
}
class ArrayDemo {
public static void main(String... args) {
int arr [ ] = { 101, 102, 103, 104 } ;
for ( int i = 0; i < arr.length; i++){
System.out.println(arr[i]);
}
}
}
class ArrayDemo {
public static void main(String... args) {
int arr [ ] = { 101, 102, 103, 104 } ;
arr [ 0 ] = 200 ; // it will update 0th index value from 101 to 200
arr [ 1 ] = 300 ; // it will update 1st index value from 102 to 300
System.out.println ( arr [ 101 ] ) ; // AIOBE ( 101 index not available in array )
}
}
Note: Array size should be positive integer only
// Write a java program to find min and max elements in the array
// int arr [ ] = { 15, 8, 9, 2, 11, 4 }
// ============= Program with Sort method =============
import java.util.*;
class ArrayDemo {
public static void main(String... args) {
int arr [ ] = { 15, 8, 9, 2, 11, 4 } ;
Arrays.sort(arr);
System.out.println ("Min Element : " + arr [ 0 ] );
System.out.println("Max Element : " + arr [ arr.length - 1 ] );
}
}
// ============= Program without sort method =============
class ArrayDemo {
public static void main(String... args) {
int arr [ ] = { 15, 8, 9, 2, 11, 4 } ;
int min = arr [ 0 ];
int max = arr [ 0 ] ;
for ( int i = 0 ; i < arr.length ; i++){
if ( arr [ i ] > max ) {
max = arr [ i ] ;
}
if ( arr [ i ] < min ){
min = arr [ i ];
}
}
System.out.println ( " Min Element :: " + min );
System.out.println (" Max Element :: " + max);
}
}
// Write a java program to reverse an array ?
// int arr [ ] = { 15, 8, 9, 2, 11, 4 } ;
class ArrayDemo {
public static void main(String... args) {
int arr [ ] = { 15, 8, 9, 2, 11, 4, 7 } ;
int temp = 0;
for ( int i = 0; i < arr.length / 2 ; i++ ){
temp = arr [ i ];
arr [ i ] = arr [ arr.length - 1 - i ];
arr [ arr.length-1 - i ] = temp;
}
for( int n : arr){
System.out.print ( n + " " );
}
}
}
// Array Elements Printing - 3 ways
import java.util.Arrays;
public class ArraySorting {
public static void main(String[] args) {
int arr[] = { 5, 8, 2, 6, 9, 3 };
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
for (int x : arr) {
System.out.print(x + " ");
}
System.out.println();
System.out.println(Arrays.toString(arr));
}
}
public class ArraySorting {
public static void main(String[] args) {
int arr[] = { 5, 8, 2, 6, 9, 3 };
int temp = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if ( arr[i] < arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println(Arrays.toString(arr));
}
}
public class SumMatchingPairs {
public static void main(String[] args) {
int arr[] = { 3, 5, 1, 6, 2, 7, 9 };
int sum = 8;
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] + arr[j] == sum) {
System.out.println(arr[i] + "+" + arr[j] + "=" + sum);
}
}
}
}
}
public class NonRepeatedElements {
public static void main(String[] args) {
int arr[] = { 2, 3, 2, 1, 3, 4, 5 };
for (int i = 0; i < arr.length; i++) {
int count = 0;
for (int j = 0; j < arr.length; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
if (count == 1) {
System.out.print(arr[i] + " ");
}
}
}
}
// Arrays are divided into 2 types
// 1) Single Dimensional Array
int arr [ ] = new int [ size ] ;
// 2) Multi Dimensional Array
int arr [ ] [ ] = new int [ rowsSize ] [ columnsSize ] ;
// Multi-Dimensional Arrays Demo
import java.util.*;
class MutliDimensionArray{
public static void main(String... args){
int arr [ ] [ ] = new int [ 2 ] [ 2 ];
arr [0] [0] = 100 ;
arr [0] [1] = 200;
arr [1] [0] = 300;
arr [1] [1] = 400;
for (int i = 0; i < arr.length ; i ++ ){
for ( int j = 0; j <arr.length ; j ++ ){
System.out.println( arr[i] [j] );
}
}
}
}
import java.util.Arrays;
public class Demo {
public static void main(String[] args) {
int arr[][] = new int[2][2];
arr[0][0] = 100;
arr[0][1] = 200;
arr[1][0] = 300;
arr[1][1] = 400;
for (int[] ar : arr) {
System.out.println(Arrays.toString(ar));
}
}
}
import java.util.Arrays;
public class Demo {
public static void main(String[] args) {
int arr[][] = { { 100, 200 }, { 300, 400 } };
for (int[] ar : arr) {
System.out.println(Arrays.toString(ar));
}
}
}
public class Demo {
public static void main(String[] args) {
int arr[][] = { { 100, 200 }, { 300, 400 } };
for (int[] ar : arr) {
for(int x : ar) {
System.out.println(x);
}
}
}
}
String name = "abc" ;
// approach - 1 (string literal)
String name = "ashokit";
// approach -2 (using new operator)
String str = new String ("ashokit");
String s1 = "hi" ;
String s2 = "hi" ;
class StringDemo {
public static void main(String[ ] args) {
String s1 = "hi" ;
String s2 = "hi" ;
if ( s1 == s2 ) {
System.out.println (" Both are same ");
}else {
System.out.println(" Both are not same" );
}
}
}
class StringDemo {
public static void main(String[ ] args) {
String s1 = new String ("hello") ;
String s2 = new String ("hello") ;
if ( s1 == s2 ) {
System.out.println (" Both are same ");
}else {
System.out.println(" Both are not same" );
}
}
}
Note: In Strings == will compare address of the objects not content.
// How many objects will be created ?
String s1 = "ashokit" ; // 1 obj
String s2 = "ashokit"; // 1 obj
String s3 = new String("ashokit"); // 2 objs
String s4 = new String("ashokit"); // 3 objs
String s5 = new String("hello"); // 5 objs
String s6 = new String("hi"); // 7 objs
// s1 == s2 =====> true
// s2 == s3 =====> false
// s3 == s4 =====> false
// s5 == s6 ====> false
String s1 = "ashokit";
System.out.println(s1.charAt(0));
String s1 = "ashokit";
System.out.println(s1.length( ) );
String s1 = "ashok";
String s2 = "it";
String s3 = s1.concat(s2);
// String s4 = s1 + s2 ;
System.out.println(s3);
String s1 = "hi";
String s2 = "hello";
System.out.println( s1.equals(s2) );
Note: In Strings, == operator will compare address of string objects where as 'equals( )' method will compare content of the objects.
String s1 = "hyderabad";
String s2 = s1.replace("bad", "good");
System.out.println(s2);
s1.toUpperCase( );
s1.toLowerCase( );
System.out.println(s1.indexOf('a'));
System.out.println(s1.lastIndexOf('a'));
Note: If given char is not available then it will return '-1'
// start-index : inclusive
// end-index : exclusive
System.out.println( s1.substring(0,5)
Note: If we don't give end index, it will print from start index to last index.
String s2 = "hi@hello@how are@you";
String [ ] arr = s2.split ("@");
System.out.println(Arrays.toString(arr));
int a = 10 ;
int b = 20 ;
a + b ===> 30
String s1 = "10";
String s2 = "20";
s1 + s2 ==> "1020"
String.valueOf (a) + String.valueOf (b) ==> 1020
"10" + "20" ==> 1020
Note: valueOf ( ) is a static method in String class. Static methods will be called using classname. Non-Static methods will be called using Object.
String str = "ashokit";
str.startsWith("a"); =====> true
str.startsWith("z"); =====> false
String str = "ashokit";
str.endsWith("it"); ===> true
str.endsWith("good") ===> false
String str = " hello ";
str.trim ( );
String s1 = "hi";
String s2 = s1.intern ( );
s1 == s2 ===> true
String s1 = "java";
char arr[ ] = s1.toCharArray ( );
StringBuffer sb = new StringBuffer ( "hello" );
class SBDemo {
public static void main (String[ ] args){
StringBuffer sb = new StringBuffer("hello");
sb.append(" hi");
System.out.println(sb);
StringBuffer sb1 = new StringBuffer("java");
System.out.println(sb1.reverse());
String s1 = "ashok";
s1.concat("it");
System.out.println(s1);
}
}
StringBuilder sb = new StringBuilder ( "java" );
sb.length ( );
sb.append("program");
class BuilderDemo {
public static void main (String[ ] args){
StringBuilder sb = new StringBuilder("java") ;
System.out.println(sb.length());
sb.append("program");
System.out.println(sb);
System.out.println(sb.length());
}
}
Q) What is the difference between String, StringBuffer & StringBuilder ?
String -> Immutable --> Jdk 1.0
StringBuffer -> Mutable + Thread-Safe --> Jdk 1.0
StringBuilder -> Mutable + Not-Thread-Safe --> Introduced in jdk 1.5v
// Program with command line arguments
class CmdArgs {
public static void main (String [ ] a){
String s1 = a [0] ;
String s2 = a [1];
String s3 = a [2];
System.out.println( s1 + s2 + s3 );
}
}
// javac CmdArgs.java
// java CmdArgs ashok it hyd
// Write a java program to perform sum of two numbers using command line Arguments
class CmdArgs {
public static void main (String [ ] a) {
System.out.println ("Total Cmd Args :: " + a.length );
String s1 = a [0];
String s2 = a [1];
int x = Integer.parseInt (s1);
int y = Integer.parseInt(s2);
System.out.println (x + y);
}
}
// javac CmdArgs.java
// java CmdArgs 10 20
// java CmdArgs 10 20 30
class CharOcc {
public static void main (String[ ] args){
String s = "java";
char ch = 'a';
char arr[ ] = s.toCharArray ( );
int count = 0;
for( int i = 0; i < arr.length ; i ++ ) {
if ( arr[i] == 'a' ) {
count ++ ;
}
}
System.out.println(count);
}
}
class StringReverse {
public static void main(String[ ] args){
String s = "java";
String rev = "";
for( int i = s.length( ) - 1 ; i >=0 ; i-- ){
rev = rev + s.charAt ( i ) ; //avaj
}
}
}
class StringReverse {
public static void main(String[ ] args){
String s = args[0];
String rev = "";
for( int i = s.length( ) - 1 ; i >=0 ; i-- ){
rev = rev + s.charAt ( i ) ;
}
System.out.println(rev);
}
}
class Palindrome {
public static void main(String[ ] args){
String s = args [0];
String s1 = "";
for(int i = s.length ( ) -1 ; i >=0 ; i -- ){
s1 = s1 + s.charAt (i);
}
if( s.equals(s1) ){
System.out.println("Palindrome");
} else {
System.out.println("Not Palindrome");
}
}
}
class Palindrome {
public static void main(String[ ] args){
String s = args [0] ;
StringBuffer sb = new StringBuffer(s);
sb.reverse() ;
String s1 = sb.toString( );
if( s.equals ( s1 ) ) {
System.out.println ("Palindrome");
} else {
System.out.println ("Not Palindrome");
}
}
}
import java.util.*;
class Anagram {
public static void main(String[ ] args){
String s1 = args[ 0 ] ;
String s2 = args[ 1 ];
if ( s1.length ( ) != s2.length () ){
System.out.println("Given Strings are not anagrams");
return ;
}
char a[ ] = s1.toCharArray ( );
char b[ ] = s2.toCharArray ( ) ;
Arrays.sort ( a );
Arrays.sort ( b );
boolean flag = Arrays.equals(a, b);
if( flag ){
System.out.println("Given strings are anagrams");
}else{
System.out.println("Given Strings are not anagrams");
}
}
}
class SwapStrings{
public static void main(String[ ] args){
String a = "java"; // 4
String b = "program"; // 7
a = a+b; // 11
b = a.substring(0, a.length() - b.length());
a = a.substring(b.length());
System.out.println(" a = " + a);
System.out.println(" b = " + b);
}
}
class RemoveVowels {
public static void main(String... args){
String s = "hello, i love my india";
s = s.replaceAll ("[aeiouAEIOU]", "");
System.out.println(s);
}
}
class ReverseEachWord {
public static void main(String... args){
String s = "Hello My Friend";
String[ ] arr = s.split(" ");
for(int i = 0; i < arr.length ; i++){
String x = arr [ i ];
StringBuffer sb = new StringBuffer(x);
sb.reverse( );
System.out.print (sb+" ");
}
}
}
class WordCount {
public static void main(String... args){
String s = "Hello Hello My Friend"
String[ ] arr = s.split("\\s+");
System.out.println(arr.length);
}
}
class WordCount {
public static void main(String... args){
String s = " Hello Hello My Friend";
String[ ] arr = s.trim().split("\\s+");
System.out.println(arr.length);
}
}
IDE means Integrated Development Environment
There are several IDEs available in the market
1) Eclipse IDE 2) MyEclipse IDE ( commercial ) 3) NetBeans IDE (outdated) 4) Spring Tool Suite (STS) IDE 5) IntelliJ IDE (commercial) 6) Visual Studio (VS) Code IDE ---> It is mostly used for front-end development
1) Download IDE as zip file 2) Extract IDE zip file 3) Open STS.exe / eclipse.exe file 4) Choose Workspace (location to store our projects) 5) Create Java Project
In java project we are able to see below two folders
- src (source files --> .java files we will create under src directory) - bin (binaries -> .class files will be stored in bin directory)
Once project created then we can create our programs / classes in that project
One project can contain any no of classes
We can create classes by following below steps
Goto src directory --> Right click on src --> select new --> select class --> Give Classname ---> Finish
We can pass command line arguments also in IDE
Right Click on Program --> Run as -> Run Configurations -> Arguments -> Program Arguments --> Enter Arguments with space -> Apply --> Run
Programming languages are divided into 2 types
1) Procedure Oriented Ex: C, Cobol, Pascal etc..... 2) Object Oriented Ex: Java, C#, Python etc.....
In Procedure Oriented programming language, we will develop functions & procedures
If we want to add more functionalities then we need to develop more functions
Maintaining & Managing more functions is difficult task
In POP, data is exposed globally
In POP, there is no security
If we want to develop a project using OOP language then we have to use Classes & Objects
Any language which follows OOPS Principles is called as OOP Language
Object Oriented languages provides security for our data
The main advantage of OOPS is code re-usability
1) Encapsulation 2) Abstraction 3) Polymorphism 4) Inheritance
Encapsulation
class Demo {
//variables
// methods
}
Abstraction
Polymorphism
Inheritance
class ClassName {
// variables
// methods
}
ClassName refVariable = new ClassName ( );
User u1 = new User ( );
User u2 = new User ( ) ;
u1.hashCode ( );
public class User {
public static void main(String[] args) {
User u1 = new User();
System.out.println(u1.hashCode());
User u2 = new User();
System.out.println(u2.hashCode());
User u3 = new User();
System.out.println(u3.hashCode());
}
}
int a = 10 ;
User u1 = new User ( );
Student s1 = new Student ( );
Variables are divided into 3 types
1) Global Variables / instance variables / non-static variables 2) static variables 3) local variables
public class User {
int age;
public static void main(String[] args) {
User raju = new User();
raju.age = 20;
System.out.println(raju.age);
User rani = new User();
rani.age = 25;
System.out.println(rani.age);
User ashok = new User();
}
}
public class Student {
String name;
String email;
long phno;
static String institute;
public static void main(String[] args) {
Student.institute = "ashokit";
Student ankit = new Student();
ankit.name = "Ankit";
Student goutham = new Student();
goutham.name = "Goutham";
}
}
When to declare variable as static or non-static ?
class Demo {
public static void main(String[ ] args){
int a = 20;
int b = 20;
System.out.println(a);
System.out.prinltn(b);
}
}
returnType methodName (param1, param2, para3..... paramN) {
//logic
return value;
}
Every method contains 2 parts
1) Method Declaration 2) Method Body
returntype methodname (list of parameters);
returntype methodname(list of parameters) {
//statements;
return value;
}
return value;
the datatype of the value we return must be match with the datatype that we specify as return type.
but if return type specified as void then we must not write any return value statement.
In java we can create any number of methods which are in any of the following 4 combinations of methods
1) method without return type, without parameters 2) method without return type, with parameters 3) method with return type, without parameters 4) method with return type, with parameters
// Write a method to print a msg on console
void hello ( ) {
System.out.println("Hello My Friend");
}
// Take 2 numbers as input and return sum as ouput
int add ( int a, int b ) {
int c = a + b ;
return c;
}
// take 2 names as input, concat them and print on console
void fullname (String fname, String lname) {
String name = fname + lname;
System.out.println(name);
}
// take person age as input, if person age >=18 then return true else return false
boolean check (int age ){
if ( age >= 18 ) {
return true;
} else {
return false;
}
}
Methods are divided into 2 types
1) instance methods ---> Object level methods 2) static methods ----> Class level method
instance method will be called by using Object
static method will be called by using Class
When we write methods in java class, by default jvm will not execute them
To execute our methods we have to call them
Note: JVM will start our program execution from main method. Main method is called as entry point for JVM execution
// this is valid
void m1( ){
// body
}
// this is valid
void m1(int a, float f){
// body
}
// this is valid
int add(int a, int b){
int c = a + b;
return c;
}
// this is valid
int add(int a, int b){
return a + b;
}
// this is valid
int div(int a, int b){
return a / b ;
}
// below method is invalid
int m1(String name){
Stirng s1 = name.toUpperCase( ) ;
return s1;
}
// this is valid
boolean m2( int a, int b){
if (a > b )
return true;
else
return false;
}
// this is valid
boolean m2(int a, int b){
return a > b ;
}
// this is invalid because it is having 2 return types
String void m2(){
return "hi";
}
// this is valid
boolean m3( ) {
return true ;
}
// this is valid
void c1(int [ ] arr ){
System.out.println(arr);
}
public class Student {
public static void main(String[] args) {
System.out.println("Hi, i am a student");
Student s1 = new Student();
s1.hello();
Student.greet();
}
void hello() {
System.out.println("Hello My Friend...");
}
static void greet() {
System.out.println("Good Evening..");
}
}
import java.util.Arrays;
public class Methods {
public static void main(String[] args) {
//object creation
Methods m = new Methods();
int[] ar = { 1, 2, 3 };
m.print(ar);
m.fullname("ashok", "it");
}
void fullname(String fname, String lname) {
String name = fname + lname;
System.out.println(name);
}
void print(int[] arr) {
System.out.println(Arrays.toString(arr));
}
}
// Write a java method to find max element in given array
int findMaxElement(int [ ] arr ) {
// logic
return maxElement;
}
// Write a java method to find length of given name
int findLength(String name) {
int length = name.length ( ) ;
retunr length;
}
// Write a java method to perform sum of two numbers
int add(int a, int b){
//logic
return a+b ;
}
// Write a java method to concat firstname and lastname
String concatNames(String fname, String lname){
return fname + lname;
}
// Write a java method to display person is elgible for vote or not
boolean check(int age){
return age >= 18 ;
}
void check(int age){
if(age > = 18){
System.out.println("eligible");
}else{
System.out.println("not-eligible");
}
}
// Write a java method to reverse given array
int[ ] reverseArray(int[ ] arr){
//logic
}
void reverseArray(int[ ] arr) { ... }
// Write a java method to convert the name into uppercase characters
String convertUppercase( String name ) {
return name.toUpperCase( );
}
public class Driver {
public static void main(String[] args) {
Driver d = new Driver(); // obj creation
int x = d.add(10, 20); // calling the method
System.out.println(x); // printing the output
}
// instance method
int add(int a, int b) {
int c = a + b;
return c;
}
}
// Write a java method to print data available in the Student object
class Student {
int id;
String name;
}
public class Driver {
public static void main(String[] args) {
Driver d = new Driver();
Student s = new Student();
s.id = 101;
s.name = "raju";
d.print(s);
}
void print(Student s) {
System.out.println(s.id + " " + s.name);
}
}
// Take employee class with id and salary as properties
// Take Driver class and write the method to print employee object data & call the print method from main method
class Employee {
int id;
double salary;
}
public class Driver {
public static void main(String[] args) {
Driver d = new Driver();
Employee e = new Employee();
e.id = 101;
e.salary = 15000.00;
d.print(e);
}
void print(Employee e) {
System.out.println(e.id + "--" + e.salary);
}
}
// Take Product class with productId, productName, productPrice as properties
// Create Driver class with print ( ) method to print product data
class Product {
int pid;
String pname;
double price;
}
class Driver {
void print(Product p) {
System.out.println(p.pid + " " + p.pname + " " + p.price);
}
public static void main(String[] args) {
Driver d = new Driver();
Product p = new Product();
p.pid = 101;
p.pname = "Mouse";
p.price = 450.00;
d.print(p);
}
}
// Take Docter class with docterName, docterAge as properties
// Create Driver class with print ( ) method to print Docter data
class Docter {
String name;
int age;
}
class Driver {
void print(Docter d) {
System.out.println(d.name + " " + d.age);
}
public static void main(String[] args) {
Driver d = new Driver();
Docter d1 = new Docter();
d1.name = "Rathod";
d1.age = 29;
d.print(d1);
}
}
// Take a Player class with id, name, age properties
class Player {
int id;
String name;
int age;
}
// Take driver class to print Player Data
class Driver {
void print (Player p1) {
System.out.println(p1.id +"--"+ p1.name+""+p1.age);
}
public static void main(String[] args) {
Driver d = new Driver( );
Player p2 = new Player ( );
//set data
d.print (p2);
}
}
// write a java method which will give Person object with data
package ashokit;
class Person {
int id;
String name;
int age;
}
class Driver {
public static void main(String[] args) {
Driver d = new Driver();
Person p = d.m1();
System.out.println(p.id + "--" + p.name + "--" + p.age);
}
Person m1() {
Person p = new Person();
p.id = 101;
p.name = "Rani";
p.age = 32;
return p;
}
}
// Write a java method to return College data (id, name)
package ashokit;
class College {
int id;
String name;
}
class Driver {
College m1() {
College c = new College();
c.id = 101;
c.name = "HITM";
return c;
}
public static void main(String[] args) {
Driver d = new Driver();
College c = d.m1();
System.out.println(c.id + "--" + c.name);
}
}
// Write a java method which will take id as input. if id is 101 then method should return Raju object if id is 102 then method should return Rani object.
package ashokit;
class Person {
int id;
String name;
int age;
}
class Driver {
public static void main(String[] args) {
Driver d = new Driver();
//read id from keyboard
Person person = d.m1(120);
System.out.println(person.id + "--" + person.name);
}
Person m1(int id) {
Person p = new Person();
if (id == 101) {
p.id = 101;
p.name = "Raju";
p.age = 30;
} else if (id == 102) {
p.id = 102;
p.name = "Rani";
p.age = 32;
}
return p;
}
}
// write a java method which will return cricket player data based on player number
// Player Data --> id, name, age
// 7 ----> Dhoni
// 18 ---> Kohli
// 45 ---> Rohit Sharma
package ashokit;
class Player {
int id;
String name;
int age;
}
class Driver {
public static void main(String[] args) {
Driver d = new Driver();
Player p = d.m1(45);
System.out.println(p.id + "--" + p.name + "--" + p.age);
}
Player m1(int id) {
Player p = new Player();
if (id == 7) { //false
p.id = 7;
p.name = "dhoni";
p.age = 40;
} else if (id == 18) { // false
p.id = 18;
p.name = "kohli";
p.age = 34;
} else if (id == 45) { // true
p.id = 45;
p.name = "Rohit";
p.age = 38;
}
return p;
}
}
// Write a java method to return University data based on unvesity ID
// 101 -----> id - 101, name - Oxford
// 102 ----> id- 102, name - Standford
public class University {
int id;
String name;
public static void main(String[] args) {
University u = m1(101);
System.out.println(u.id + "--" + u.name);
String str = u.m2();
System.out.println(str);
}
String m2() {
String s = "hello";
return s;
}
static University m1(int id) {
University u = new University();
if (id == 101) {
u.id = 101;
u.name = "Oxford";
} else if (id == 102) {
u.id = 102;
u.name = "Standford";
}
return u;
}
}
// Write a java class with two methods
// first method should take 2 Person objects as input
// Approach-1:
void m1(Person p1, Person p2){
// logic
}
// Approach-2 :
void m1 (Person[ ] p){
// logic
}
// second method should give 3 Person Objects as ouput
Person[ ] m2(){
// logic
}
package ashokit;
public class Person {
int id;
String name;
Person[] m2() {
Person p1 = new Person();
p1.id = 101;
p1.name = "Raju";
Person p2 = new Person();
p2.id = 102;
p2.name = "Rani";
Person p3 = new Person();
p3.id = 103;
p3.name = "Anil";
Person[] arr = { p1, p2, p3 };
return arr;
}
void m1(Person p1, Person p2) {
System.out.println(p1.id + "--" + p1.name);
System.out.println(p2.id + "--" + p2.name);
}
public static void main(String[] args) {
Person p = new Person(); // obj1 created
Person p1 = new Person(); // obj2 created
p1.id = 101;
p1.name = "Raju";
Person p2 = new Person(); // obj3 created
p2.id = 102;
p2.name = "Rani";
p.m1(p1, p2);
Person[] arr = p.m2();
for (Person person : arr) {
System.out.println(person.id + "--" + person.name);
}
}
}
Class : It is a plan or model. It contains variables & Methods
Object : Physical Entity. It is used to access variables & methods of the class
Variables : Used to store the data
- instance variables (inside class, outside method without static keyword) -> When obj created, memory will be allocated for instance variables -> Every obj will maintain its own copy of instance variables - static variables (inside class, outside method with static keyword) -> When class is loaded then memory will be allocated for static variables - local variables (inside the method) -> When method is invoked then only memory will be allocated for local variables -> Before using local variable, we have to initialize that
Methods : To perform some operation
- instance method ---> We will call by using object - static method -----> We will call by using Classname - Method Declaration(Signaure) ---> return type + name + list of parameters - Method Definition(Body) ----> logic
class Demo {
Demo ( ) {
// logic
}
}
javap classname
Note: If we write constructor in the class, then compiler will not add any constructor.
Constructors are divided into 2 types
1) Zero Param Constructor / Default Constructor 2) Parameterized Constructor
// Constructor without parameters
class Student {
Student ( ) {
...
}
}
// Constructor which contains 1 or more paramters
class Student {
Student (int i, int b ) {
...
}
}
class Employee {
public Employee(int i, int j) {
System.out.println(i + j);
}
public static void main (String[] args) {
Employee emp = new Employee(100, 200);
}
}
class Employee {
String name;
float salary;
public Employee(String name, float salary) {
this.name = name;
this.salary = salary;
System.out.println(this.name + "--" + this.salary);
}
public static void main(String[] args) {
Employee emp = new Employee("Raju", 55000.00f);
}
}
public class Student {
int id;
String name;
int age;
String gender;
public Student(int id, String name, int age, String gender) {
this.id = id;
this.name = name;
this.age = age;
this.gender = gender;
System.out.println(this.id + "-" + this.name + "-" + this.age + "-" + this.gender);
}
public static void main(String[] args) {
Student s1 = new Student(1, "Raju", 20, "Male");
Student s2 = new Student(1, "Rani", 22, "FeMale");
}
}
class Employee {
Employee(int id){
// logic
}
Employee(double d){
// logic
}
}
These are used to specify accessibility for our classes, constructors, variables & methods
In java we have below 4 access specifiers / modifiers
1) public 2) private 3) protected 4) default
It is used to specify global access for classes, variables, methods and Constructors
-> We can take class as public -> We can take constructor as public -> We can take variables as public -> We can take methods as public
Note: public means anybody can access from inside and outside the class also.
It is used to specify local access (with in the class). private variables, private methods, private constructors can't be accessed outside of the class.
-> We can't use private for classes (not allowed) -> We can take variables as private -> We can take constructor as private (no body can create obj from outside of cls) -> We can take method as private (no body can call our method from outside of cls)
Note: To make our java class as Singleton, we will use private constructor. The java class which is having only one object is called as Singleton class.
Encapsulation : Combining variables & methods as single unit. It is used for data hiding. Ex: Java Class
Abstraction : Hiding un-necessary details and providing only useful information. Ex: Abstract classes & Interfaces
Inheritance : The process of extending properties from one class to another class is called as inheritance. It is used for code re-usability
Polymorphism : Exhibiting multiple behaviours based on the situation is called as Polymorphism. Ex: Objects will exhibit multiple behaviours
public class Account {
private int accNum;
private String name;
public void setAccNum(int accNum) {
this.accNum = accNum;
}
public int getAccNum() {
return this.accNum;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
public class Test {
public static void main(String[] args) {
Account obj = new Account(); // obj creation
obj.setAccNum(797979);
obj.setName("Ashok");
int accNum = obj.getAccNum();
String name = obj.getName();
System.out.println(accNum + "--" + name);
}
}
class User {
// properties
// methods
}
class Student extends User {
// logic
}
// Inhertience w.r.t to variables
public class User {
int id;
String name;
}
public class Student extends User {
int rank;
public static void main(String[] args) {
// child class object creation
Student s = new Student();
s.rank = 1;
// accessing parent class properties using child cls obj
s.id = 101;
s.name = "Bhanu";
System.out.println(s.id + "--" + s.name + "--" + s.rank);
}
}
public class User {
int id;
String name;
}
public class Student extends User {
int rank;
public static void main(String[] args) {
// creating parent class obj
User user = new User();
user.id = 101;
user.name = "Raj";
user.rank = 1; // invalid bcz parent can't access child properties
}
}
// inhertience w.r.t to methods
public class User {
int id;
String name;
void m1() {
System.out.println(" Parent class :: m1 ( ) method called");
}
}
public class Employee extends User {
void m2() {
System.out.println("Child class - m2() method called");
}
public static void main(String[] args) {
// creating object for child class
Employee emp = new Employee();
// calling parent class method
emp.m1();
// calling child class method
emp.m2();
}
}
Q) Why Parent class constructor is executing first ?
// inhertience w.r.t to constructors
public class User {
int id;
String name;
public User() {
System.out.println("Parent class :: 0-param constructor called ");
}
}
public class Employee extends User {
double salary;
public Employee() {
System.out.println("Child Class :: 0-Param Constructor called");
}
void m2() {
System.out.println("Child class - m2() method called");
}
public static void main(String[] args) {
// creating object for child class
Employee emp = new Employee();
// initializing parent class properties using child obj
emp.id = 101;
emp.name = "John";
// initialing child class properties using its own obj
emp.salary = 4500.00;
System.out.println(emp.id + "--" + emp.name + "--" + emp.salary);
}
}
Inheritence is divided into multiple types
1) Single Level 2) Multi Level 3) Multiple --------> Not supported by Java due to Ambiguity problem 4) hierarchical
Single level : Class B extends Class A
Multi Level : Class C extends Class B extends class A extends Object
Multiple Inheritance : If one child having more than one parent (Java doesn't support to avoid ambiguity)
Hierarchical : If one parent having multiple childs
class Parent {
void m1() {
System.out.println("Parent - Class - m1() Called");
}
void m2() {
System.out.println("Parent - Class - m2() called");
}
}
class Child extends Parent {
public int hashCode() {
return 101;
}
void m1() {
System.out.println("Child - Class - m1() Called");
}
void m2() {
System.out.println("Child - Class - m2() called");
super.m2();
}
}
public class Test {
public static void main(String[] args) {
Child c = new Child();
c.m1();
c.m2();
int hashcode = c.hashCode();
System.out.println("Hash Code :: " + hashcode);
}
}
When we call a method using Object, first it will check in current class for that method, if available it will call that method directly. If method not available in current class then it will check in parent class (It can be direct or indirect parent). If parent having that method then it will call parent class method. If parent class also doesn't have method then it will throw Exception.
Note: In inheritance always priority will be given for Child class / Sub class object. If child class doesn't contain that method then priority will be given to Parent class method.
Poly ----> Many
Phism ---> Forms
If any object is exhibiting multiple behaviours based on the Situation then it is called as Polymorphism.
Polymorphism is divided into 2 types
1) Static polymorphism / Compile-time Polymorphism Ex: Overloading 2) Dynamic polymorphism / Run-time Polymorphism Ex: Overriding
public class Calculator {
void add (int i, int j) {
System.out.println("Sum from 1st method :" + (i + j));
}
void add (int i, int j, int k) {
System.out.println("Sum from 2nd method : " + (i + j + k));
}
public static void main(String[] args) {
Calculator c = new Calculator();
c.add(10, 20);
c.add(10, 20, 30);
c.add(10, 20, 30, 40); // invalid
}
}
substring (int start)
substring(int start, int end)
class Parent {
void m1( ) {
// logic
}
}
class Child extends Parent {
void m1 ( ){
//logic
}
public static void main(String[] args){
Child c = new Child ( );
c.m1 ( );
}
}
// Write a program on Method Overriding
class RBIBank {
boolean checkElgibility() {
// docs verification logic
return true;
}
double getHomeLoanRofi() {
return 10.85;
}
}
public class SBIBank extends RBIBank {
// overriding parent method to give my own rofi
double getHomeLoanRofi() {
return 12.85;
}
public String applyHomeLoan() {
boolean status = checkElgibility(); // parent method
if (status) {
double homeLoanRofi = getHomeLoanRofi(); // child method
String msg = "Your loan approved with RI as ::" + homeLoanRofi;
return msg;
} else {
return "You are not elgible for home loan";
}
}
public static void main(String[] args) {
SBIBank bank = new SBIBank();
String msg = bank.applyHomeLoan();
System.out.println(msg);
}
}
// Method Overriding Example with User-Defined Objects and String Objects
public class Demo {
public static void main(String[] args) {
SBIBank b1 = new SBIBank();
SBIBank b2 = new SBIBank();
boolean bankObjStatus = b1.equals(b2); // false
System.out.println("Both Banks Are Equal ?? :: " + bankObjStatus);
String s1 = new String("ashokit");
String s2 = new String("ashokit");
boolean stringObjStatus = s1.equals(s2); // true
System.out.println("Both Strings Are Equal ?? :: " + stringObjStatus);
}
}
In java we can write 2 types of methods
1) Concrete Method 2) Abstract Method
The method which contains body is called as 'Concrete method'
public void m1( ){
// logic
}
public abstract void m2( );
In java classes we can use below 2 types of relations
1) IS-A relation -----> Inheritance 2) HAS-A relation -----> Composition
If one class wants to re-use all the properties of another class then we will go for IS-A relation.
Ex: Inhertiance is the example for IS-A relation
class User {
int id;
String name;
void speak ( ){
System.out.println("Hi, My Id is : "+ id + ", My Name : "+ name);
}
}
class Student extends User { // IS-A relation
public static void main(String... args){
Student s = new Student ( );
s.id = 10;
s.name = "Raju";
s.speak ( );
}
}
If one class wants to re-use some properties of another class then we will go for HAS-A relation.
Ex: Composition is the example for HAS-A relation
class Engine {
int id;
String name;
String fuelType;
void start ( ){
System.out.println("Engine Starting....");
}
}
class Car {
void drive ( ){
Engine e = new Engine ( ); // HAS-A Relation
e.start ( );
System.out.println("Journey Started");
}
public static void main(String... args){
Car c = new Car ( );
c.drive ( );
}
}
final is a reserved keyword in java
We can use final keyword at 3 places
1) class level 2) variable level 3) method level
final classes can't be inherited. We can't extend properties from final classes. Final classes are immutable.
public class User extends String { // invalid because String is final class
// logic
}
public final int pi = 3.14;
pi = 4.32; // invalid
public interface Bank {
public void moneyTransfer();
public void checkBalance();
}
public class HdfcBank implements Bank {
public void moneyTransfer() {
System.out.println("Money Transfer from HDFC....");
}
public void checkBalance() {
System.out.println("Checking Balance from HDFC.....");
}
}
public class AxisBank implements Bank {
public void moneyTransfer() {
System.out.println("Money Transfer from Axis ....");
}
public void checkBalance() {
System.out.println("Check Balance from Axis....");
}
}
public class BankDemo {
public static void main(String[] args) {
Bank b; // reference variable
b = new AxisBank(); // storing impl obj into ref variable
b.moneyTransfer(); // axis-bank method will be called
b.checkBalance(); // axis-bank method will be called
b = new HdfcBank(); // storing impl obj into ref variable
b.moneyTransfer(); // hdfc-bank method will be called
b.checkBalance(); // hdfc-bank method will be called
}
}
Bank b = new AxisBank ( ) ; // valid
Bank b = new HdfcBank ( ) ; // valid
Bank b = new Kotak ( ) ; // in-valid because it is not implementation class for Bank
public void m1(Bank b ){
// loosely coupled bcz we can pass any impl cls obj
}
public void m1(AxisBank b){
// tightly coupled bcz we have to pass only AxisBank obj
}
public Bank m2( ){
// loosely coupled bcz we can return any impl cls obj
}
public HdfcBank m2( ){
// tighthly coupled bcz only HdfcBank obj shud be returned
}
If interface doesn't contain any method then that interface is called as 'Marker Interface'
Ex: Cloneable, Serializable etc.....
If our class implements pre-defined marker interface then JVM will treat our classes as special classes and JVM will provide special functionality based on the marker interface we have implemented.
// user defined marker interface
public interface Demo {
// logic
}
public class Test implements Demo {
// logic
}
public interface Bank {
public void checkBalance ( ) ;
}
public interface RbiBank implements Bank { // invalid
}
public interface RbiBank extends Bank { // valid
public void applyLoan ( ) ;
}
abstract class DieselMachine {
public DieselMachine() {
System.out.println("DieselMachine-Constructor");
}
public void start() {
System.out.println("Machine starting....");
}
public abstract void fillFuel();
}
public class Machine extends DieselMachine {
public Machine() {
System.out.println("Machine Constructor");
}
@Override
public void fillFuel() {
System.out.println("filling fuel tank....");
}
public static void main(String[] args) {
Machine m = new Machine();
m.fillFuel();
m.start();
}
}
public abstract final void m1 ( ) ; // invalid
abstract means override in child where as 'final' means don't override .
=> To create interface we will use 'interface' keyword => To create abstract classes we will use 'abstract' keyword => Interface contains abstract methods => Abstract classes can contain both abstract methods & concrete methods => Interface can't have constructor => Abstract class can have constructor => We can't create obj for interface => We can't create obj for abstract class => One interface can't implement another interface => One interface can extend another interface => When we implement any interface then we have to implement all the abstract methods of that interface => When we extend abstract class, we need override all abstract methods => Abstract class constructor will be executed when we create object for sub class. => If interface contains only one method then it is called Functional Interface => If interface doesn't have any method then it is called as Marker interface => When we don't know implementation for methods then we will go for Interfaces => When we know partial implementation for methods then we will go for abstract classes
Block means some part or some piece of information or some piece of code
In java program we can write 2 types of blocks
1) instance block 2) static block
// instance block syntax
{
// stmts
}
// static block syntax
static
{
// stmts
}
When class is loaded into JVM then static control flow will start
When we run java program, JVM will check for below static members & JVM will allocate memory for them in below order
a) static variables b) static methods c) static blocks
Once memory allocation completed for static members then it will start execution in below order
a) static block b) static method (if we call) -- only main method will execute automatically by jvm c) static variable
static variables can be accessed directly in static blocks and static methods.
Note: If we want to access any instance method or instance variable in static area then we should create object and using that object only we can access. We can't access directly without object.
instance means Object
Instance control flow will begin when object is created for a class
When Object is created then memory will be allocated for
a) instance variables b) instance methods c) instance blocks
Once memory allocation completed then execution will happen in below order
a) instance block b) constructor c) instance methods (if we call)
Note: static members can be access directly in instance areas because for static members memory already allocated at the time of class loading.
public class Demo {
{
System.out.println("i am from instance block");
}
public Demo() {
System.out.println("I am from constructor");
}
static {
System.out.println("I am from static block");
}
public static void main(String[] args) {
System.out.println("i am from main method...");
Demo d = new Demo();
}
}
Object is a pre-defined class available in java.lang package
Object class will act as super class for all the classes in java either directly or in-directly
Note: If our class doesn't have any super class then Object class will become direct Super class. If our class having any super class then Object class will become in-direct super class.
Object class having 11 methods, those 11 methods are by default available for every java object.
1) protected Object clone ( ) 2) boolean equals (Object obj) 3) protected void finalize( ) 4) Class <?> getClass( ) 5) int hashCode( ) 6) String toString( ) 7) notify ( ) 8) notifyAll ( ) 9) void wait ( ) 10) void wait(long timeout) 11) void wait (long timeout, int nanos)
Note: Last 5 methods will be used in Multi-Threading concept.
public String toString ( ) {
return this.getClass( ).getName ( ) + "@"+ Integer.toHexString(this.hashCode());
}
// Output : Student@15db9742
public class Student {
int id;
String name;
public static void main(String[] args) {
Student s = new Student();
s.id = 101;
s.name = "John";
System.out.println(s); // toString ( ) will be called
System.out.println(s.toString());
String s1 = new String("hi");
System.out.println(s1);
}
public String toString() {
return id + "--" + name;
}
}
public class Student {
int id;
String name;
public static void main(String[] args) {
Student s = new Student();
s.id = 101;
s.name = "John";
System.out.println(s); // toString ( ) will be called
System.out.println(s.hashCode());
}
public String toString() {
return id + "--" + name;
}
public int hashCode() {
return id;
}
}
public class Student {
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public static void main(String[] args) {
Student s1 = new Student(101, "John");
Student s2 = new Student(101, "John");
System.out.println(s1.equals(s2)); // false - compares address
System.out.println(s1 == s2); // false - compares address
String s3 = new String("hi");
String s4 = new String("hi");
System.out.println(s3.equals(s4)); // true - compares content of objects
}
}
public class Student {
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public static void main(String[] args) {
Student s1 = new Student(101, "John");
Student s2 = new Student(101, "John");
System.out.println(s1.equals(s2)); // true - compares content (overriden)
System.out.println(s1 == s2); // false - compares address
String s3 = new String("hi");
String s4 = new String("hi");
System.out.println(s3.equals(s4)); // true - compares content of objects
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) // s1 == s2
return true;
if (obj == null) // s2 == null
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj; // typecasting
if (id != other.id) // s1.id != s2.id
return false;
if (name == null) { // s1.name == null
if (other.name != null)
return false;
} else if (!name.equals(other.name)) // !s1.name.equals(s2.name)
return false;
return true; // ---> true
}
}
public class Student {
public static void main(String[] args) throws Exception {
Student s = new Student(); // obj creation
Class clz = s.getClass();
System.out.println(clz.getName());
System.out.println(s.getClass().getName()); // method chaining to get cls name
Object object = clz.newInstance(); // 2nd approach to create object for a cls
System.out.println(object);
}
}
public class Student implements Cloneable {
public static void main(String[] args) throws Exception {
Student s = new Student();
System.out.println(s);
Object clone = s.clone(); // cloning (another approch to create obj for a class)
System.out.println(clone);
}
}
Q) In how many ways we can create Object for a class ?
Ans: There are following three ways to create a object
1) using new operator 2) using newInstance( ) method 3) using clone( ) method
Packages are used to group the classes , interfaces, exceptions and errors
In java language, so many classes, interfaces, Exceptions and Errors are already available.
Ex: String, StringBuffer, StringBuilder, Arrays, BufferedReader, Scanner etc....
Sun people divided predefined classes, interfaces, Exceptions into several packages
1) java.lang 2) java.io 3) java.util 4) java.sql
java.lang package is default package and it is available for all java classes by default.
If we want to use any predefined class which is not part of java.lang package then we have to import that class using 'import' keyword.
// Example Of predefined package import
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Demo {
public static void main(String[] args) {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
}
}
In our project we will create our own packages to organize project related classes & interfaces
To create a package we will use 'package' keyword
In java class, package statement should be in first line and class should have only one package statement.
We can create user-defined package like below
package ashokit; package com.tcs.aadhar;
Sample package naming convention : company-name.project-name.module-name
com.ibm.irctc.admin AdminLogin.java AdminService.java Request.java com.ibm.irctc.user UserLogin.java UserService.java com.ibm.irctc.reports ReportService.java Request.java
Note: In project we can create 2 classes with same in using 2 different packages.
package com.oracle;
public class Engine {
public void start() {
System.out.println("Engine starting...");
}
}
package com.ibm;
import java.util.Scanner;
import com.oracle.Engine;
public class Car {
public void drive() {
Engine eng = new Engine();
eng.start();
Scanner s = new Scanner(System.in);
}
}
1) In class, package statement should be in first line (top) 2) After package statement we can write multiple import statements 3) import java.io.* (it means all classes, interface, exceptions of io package will be imported) - not recommended 4) If 2 classes are in same package then import not required.
package com.ibm.aadhar;
public class Person {
public static void speak() {
System.out.println("Hi, i am ashok");
}
public static void m1() {
System.out.println("hi, i am from m1()");
}
public static void m2() {
System.out.println("hi, i am from m2()");
}
}
// Java Program with Normal Import to use Person class
package in.ashokit;
import com.ibm.aadhar.Person;
public class Demo {
public static void main(String[] args) {
Person.speak();
Person.m1();
Person.m2();
}
}
// java program with static import
package in.ashokit;
import static com.ibm.aadhar.Person.*;
public class Demo {
public static void main(String[] args) {
speak();
m1();
m2();
}
}
Un-expected and Un-wanted situation in the program execution is called as Exception.
Exception will disturb normal flow of the program execution
When Exception occurred program will be terminated abnormally
Note: As a programmer we are responsible for programs graceful termination.
To achieve graceful termination we need to handle the exceptions occurred while program executing.
The process of handling Exceptions is called as Exception Handling.
The main aim of Exception Handling to achieve graceful termination of the program
In java we have so many predefined exceptions
ArithematicException NullPointerException FileNotFoundException SQLException
Exceptions are divided into 2 types
1) Checked Exceptions :: Will be identified at compile time (occurs at run time) Ex: IOException, FileNotFoundException, SQLException etc.... 2) Un-Checked Exceptions : Will occur at Run time ( Compiler can't identify these exception ) Ex: NullPointerException, ArithematicException etc...
Java provided 5 keywords to handle exceptions
1) try 2) catch 3) finally 4) throws 5) throw
// Syntax
try {
// stmts
}
Note: We can't write only try block. try block required catch or finally (it can have both also)
try with catch ------> valid combination try with multiple catch blocks ----> valid combination try with finally -----> valid combination try with catch & finally ---> valid combination only try block ----> invalid only catch block ---> invalid only finally block ---> invalid
// Syntax
try {
// logic
} catch ( Exception e ){
// logic to catch exception info
}
public class Demo {
public static void main(String[] args) {
System.out.println("main( ) method started...");
try {
System.out.println("try block start");
String s = null;
s.length(); // NPE
System.out.println("try block end");
} catch (Exception e) {
System.out.println("in catch block");
e.printStackTrace();
}
System.out.println("main( ) method ended...");
}
}
// In below scenario catch block will not be executed because there is no exception in try block
public class Demo {
public static void main(String[] args) {
System.out.println("main( ) method started...");
try {
System.out.println("try block start");
String s = "hi";
int i = s.length();
System.out.println("try block end");
} catch (Exception e) {
System.out.println("in catch block");
e.printStackTrace();
}
System.out.println("main( ) method ended...");
}
}
// We can write one try block with multiple catch blocks also like below
public class Demo {
public static void main(String[] args) {
System.out.println("main( ) method started...");
try {
System.out.println("try block start");
String s = "hi";
int i = s.length();
System.out.println("try block end");
} catch (ArithmeticException e) {
System.out.println("in catch block");
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("main( ) method ended...");
}
}
// below program will fail at compile time because of un-reachable second catch block
public class Demo {
public static void main(String[] args) {
System.out.println("main( ) method started...");
try {
System.out.println("try block start");
String s = "hi";
int i = s.length();
System.out.println("try block end");
} catch (Exception e) {
e.printStackTrace();
System.out.println("first catch");
} catch (NullPointerException ne) {
System.out.println("second catch");
}
System.out.println("main( ) method ended...");
}
}
It is used to perform resource clean up activities
Ex: file close, db connection close etc....
finally block will execute always ( irrespective of the exception )
try with finally : valid try with catch and finally : valid catch with finally : invalid only finally : invalid
// java program with try-catch-finally scenario
public class Demo {
public static void main(String[] args) {
System.out.println("main( ) method started...");
try {
System.out.println("try block - start");
int i = 10 / 2;
System.out.println("try block - end");
} catch (Exception e) {
System.out.println("catch block");
e.printStackTrace();
} finally {
System.out.println("finally - block");
}
System.out.println("main( ) method ended...");
}
}
// java program with try-finally scenario
public class Demo {
public static void main(String[] args) {
System.out.println("main( ) method started...");
try {
System.out.println("try block - start");
int i = 10 / 0;
System.out.println("try block - end");
} finally {
System.out.println("finally - block");
}
System.out.println("main( ) method ended...");
}
}
Q) What is the difference between final, finalize( ) and finally ?
Ans: final : it is a keyword which is used to declare final variables, final methods and final classes.
finalize ( ) : It is predefined method available in Object class, and it will be called by garbage collector before removing unused objects from heap area.
finally : it is a block we will use to execute some clean activities in exception handling.
try : it is used to keep our risky code catch : It is used to catch the exception occurred try block finally : to execute clean up activities
public class Demo {
public static void main(String[] args) throws FileNotFoundException {
FileReader fr = new FileReader("abc.txt");
}
}
public class Demo {
public static void main(String[] args) throws Exception {
FileReader fr = new FileReader("abc.txt");
Class.forName("");
}
}
throw new Exception("Msg");
package in.ashokit;
public class Demo {
public String getName(int id) throws Exception {
if (id == 100) {
return "raju";
} else if (id == 101) {
return "rani";
} else {
throw new Exception("Invalid Id");
}
}
public static void main(String[] args) throws Exception {
Demo d = new Demo();
String name = d.getName(101);
System.out.println(name);
String name1 = d.getName(200);
System.out.println(name1);
}
}
// Stack Over Flow Error
public class Demo {
void m1() {
m2();
}
void m2() {
m1();
}
public static void main(String[] args) {
System.out.println("main ( ) method - start");
Demo d = new Demo();
d.m1();
System.out.println("main( ) method - end");
}
}
In java language we have several pre-defined exception classes
IOException FileNotFoundException ClassNotFoundException SQLException AirthematicException ArrayNegativeSizeException NullPointerException ClassCastException etc...
Based on Project requirement, sometimes we need to create our own exceptions those are called as user defined exceptions
InvalidCredentialsExceptions NoRecordsFoundException NoDataFoundException InvalidInputException
To create our own Exception we need to extend the properties from Exception or RuntimeException class
public class NoDataFoundException extends RuntimeException {
public NoDataFoundException() {
// logic
}
public NoDataFoundException(String msg) {
super(msg);
}
}
package in.ashokit;
public class Demo {
private String getName(int id) {
if (id == 100) {
return "Raju";
} else if (id == 101) {
return "Rani";
} else {
throw new NoDataFoundException("Invalid Id");
}
}
public static void main(String[] args) {
Demo d = new Demo();
d.getName(200);
}
}
throws : It is used to ignore checked exceptions throw : It is used to create the exception
public class Demo {
void m1(int a, int b) {
System.out.println("m1() - started");
try {
int c = a / b;
System.out.println(c);
} catch (Exception e) {
// logic
}
System.out.println("m1() - ended");
}
public static void main(String[] args) throws Exception {
System.out.println("main() - method started");
Demo d = new Demo();
d.m1(10, 0);
System.out.println("main() - method ended");
}
}
package in.ashokit;
public class InvalidNumberException extends Exception {
public InvalidNumberException(String msg) {
super(msg);
}
}
package in.ashokit;
public class Demo {
void m2(int a, int b) throws Exception {
System.out.println("m2() - started");
try {
int c = a / b;
System.out.println(c);
} catch (Exception e) {
throw new InvalidNumberException("invalid number");
}
System.out.println("m2() - ended");
}
void m1(int a, int b) throws Exception {
System.out.println("m1() - started");
m2(a, b);
System.out.println("m1() - ended");
}
public static void main(String[] args) {
System.out.println("main() - method started");
try {
Demo d = new Demo();
d.m1(10, 0);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("main() - method ended");
}
}
public int add (int... x) {
// logic
}
1) Only 3 ellipses ( ... ) allowed to declare variable argument 2) Variable argument should be the last parameter of the method 3) A method should contain only one variable argument
package in.ashokit;
public class Calculator {
public void add(int... a) {
int sum = 0;
for (int x : a) {
sum = sum + x;
}
System.out.println(sum);
}
public static void main(String[] args) {
Calculator c = new Calculator();
c.add(10, 20);
c.add(10, 20, 30);
c.add(10, 20, 30, 40);
c.add(1, 2, 3, 4, 5);
}
}
public void m1 (String s, int... i) ; // valid public void m1 (String s, boolean... b) ; // valid public void m1 (int i, String... s) ; // valid public void m1( int... i ) ; // valid public void m1 ( double.... d) ; // invalid bcz 4 dots public void m1 (int... i , int j ) ; // invalid bcz var-arg shud be last public void m1 ( int i, int... j ) ; // valid
byte ----> Byte short ---> Short int ---> Integer long ---> Long float ----> Float double ----> Double char ---> Character boolean ---> Boolean
public class Calculator {
public static void main(String... args) {
byte b = 20;
System.out.println(b);
Byte b1 = new Byte(b); // Auto-boxing
System.out.println(b1);
byte b2 = b1; // Auto-un-boxing
System.out.println(b2);
}
}
Integer i1 = new Integer (10) ; Integer i2 = new Integer ("20"); Double d1 = new Double (10.05); Double d2 = new Double ("20.10"); Character c1 = new Character ('a'); Character c1 = new Character ("a"); // invalid
Converting data from one data type to another data type is called as Type casting.
Type Casting is divided into 2 types
1) Widening / Up Casting 2) Narrowing / Down Casting
The process of converting data from lower data type to higher data type is called as Widening.
As we are converting lower data type to higher data type there is no data loss
For widening no need to specify type casting explicitly (JVM will take care of that)
byte b = 20 ;
int i = b ; // widening
long num = 100 ;
int i = num ; // compile time error
int x = ( int ) num ; // narrowing
public class Calculator {
public static void main(String[ ] args) {
String s1 = "10" ;
String s2 = "20";
int i = Integer.parseInt ( s1 ) ;
int j = Integer.parseInt ( s2 );
System.out.println ( i + j ); // 30
}
}
String s1 = "10.56" ;
double d = Double.parseDouble (s1);
String s1 = "hi" ;
int i = Integer.parseInt ( s1 ) ; // NumberFormatException
// Converting int data to String data
public class Calculator {
public static void main(String[] args) {
int i = 10;
int j = 20;
String s1 = String.valueOf(i);
String s2 = String.valueOf(j);
System.out.println(s1 + s2); // 1020
}
}
public class Demo implements Cloneable {
public static void main(String[] args) throws Exception {
// child object
Demo d = new Demo();
// storing child obj into parent class reference variable
Object obj = d; // widening / up casting (low to high)
// cloning - getting parent object
Object object = d.clone();
// Storing parent object into child class reference variable
Demo d1 = (Demo) object; // narrowing (high to low)
}
}
File Handling is very important area in every programming language
Below are the common file operations in the project
1) Create a file 2) Write the data to file 3) Read the data from file 4) Delete the file
To perform File operations java language provided one predefined class java.io.File
java.io package contains set of classes & interfaces to perform input and output operations
File f = new File (String name);
File f1 = new File (File parent, String child);
We have several methods in the file class
boolean createNewFile ( ) : It is used to create a new empty file boolean mkdir ( ) : It is used to create new empty directory String[ ] list ( ) : It is used to read the content of the given path boolean delete ( ) : It is used to delete the file / directory based on given name isFile ( ) : To check weather it is a file or not isDirectory ( ) : To check weather it is a directory or not
import java.io.File;
import java.io.IOException;
public class Demo {
public static void main(String... args) throws IOException {
File f = new File("ashokit.txt");
boolean fstatus = f.createNewFile ( );
System.out.println(fstatus);
File f1 = new File("java.txt");
boolean f1status = f1.createNewFile ( );
System.out.println(f1status);
File f2 = new File("mywork");
boolean f2status = f2.mkdir( );
System.out.println(f2status);
File f3 = new File("data");
f3.mkdir ( );
File f4 = new File(f3, "test.txt");
f4.createNewFile ( );
}
}
// Java program to display all the files and directories in given path
import java.io.File;
import java.io.IOException;
public class Demo {
public static void main(String... args) throws IOException {
File f = new File ("C:\\Users\\ashok\\classes\\19-JRTP");
String [ ] arr = f.list ( );
for ( String name : arr) {
System.out.println (name);
}
}
}
// Write a java program to display content of given directory.
// For filename it should display prefix as 'File'.
// For directory name it should display prefix as 'Directory'.
package in.ashokit;
import java.io.File;
import java.io.IOException;
public class Demo {
public static void main(String... args) throws IOException {
File f = new File("C:\\Users\\ashok\\classes\\19-JRTP");
String[] arr = f.list();
for (String name : arr) {
File f1 = new File(f, name);
if (f1.isFile()) {
System.out.println("File :: " + name);
}
if (f1.isDirectory()) {
System.out.println("Directory :: " + name);
}
}
}
}
To perform operations on the file we need to use I/O Streams.
Using I/O streams we can establish link between java program and file (physical file )
write java program <--------------------> file read java program <--------------------> file
IO streams are divided into 2 types
1) Byte Stream : To read/write binary data (images, audios, videos, pdfs etc...) 2) Character Stream : To read/write character data (text files)
Byte Stream providing 2 types of classes
1) Input Stream Related Classes (Ex: FileInputStream) 2) Ouput Stream realted classes (Ex: FileOuputStream)
Character Stream providing 2 types of classes
1) Reader classes (Ex: FileReader) 2) Writer classes (Ex: FileWriter)
// Java Program to write the data to a file using FileWriter class
import java.io.*;
public class Demo {
public static void main(String... args) throws IOException {
FileWriter fw = new FileWriter("data.txt");
fw.write("Hi, good evening");
fw.write("\n"); // it represents new line
fw.write("How are you?");
fw.flush ( );
fw.close( ) ;
}
}
// Java program to read file data using FileReader class
import java.io.*;
public class Demo {
public static void main(String... args) throws IOException {
FileReader fr = new FileReader ("data.txt");
int i = fr.read ( );
while ( i != -1 ){
System.out.print( (char) i );
i = fr.read ( ); // read next character and re-initialize i var
}
fr.close ( );
}
}
// Java Program to read file data using BufferedReader
import java.io.*;
public class Demo {
public static void main(String... args) throws IOException {
FileReader fr = new FileReader("data.txt");
BufferedReader br = new BufferedReader(fr);
String line = br.readLine ( ); // reading first line data
while ( line != null ) {
System.out.println( line );
line = br.readLine ( ) ; // reading next line and re-initialzing line variable
}
}
}
Note: FileReader will read the data character by character where as BufferedReader will read the data Line by Line.
File Handling Assignments :
1) Write a java program to find how many characters, how many words and how many lines available in the file 2) Write a java program to read 2 files data and write 2 files content into 3rd file. 3) Write a java program to find names which are available in 2 files.
System.out.println ("hi"); System ----> It is a class available in java.lang package out ---> it is a static variable available in System class. - The data type of 'out' variable is PrintWriter class println ( ) ---> it is a method available in PrintWriter class
// Writing data to console using PrintWriter object
package in.ashokit;
import java.io.PrintWriter;
public class Demo {
public static void main(String[] args) {
PrintWriter pw = new PrintWriter(System.out);
pw.print("hi");
pw.println("hello");
pw.flush();
pw.close();
}
}
// Writing data to file using PrintWriter object
package in.ashokit;
import java.io.PrintWriter;
public class Demo {
public static void main(String[] args) throws Exception {
PrintWriter pw = new PrintWriter("f1.txt");
pw.write("this is my f1 file data");
pw.flush();
pw.close();
}
}
// Java program on Serialization & De-Serialization
package in.ashokit;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Person implements Serializable {
private static final long serialVersionUID = -100l;
int id;
String name;
public static void main(String[] args) throws Exception {
Person p = new Person();
p.id = 100;
p.name = "Raju";
System.out.println("====Serialization Started ========");
FileOutputStream fos = new FileOutputStream("person.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(p);
oos.flush();
oos.close();
System.out.println("====Serialization completed========");
System.out.println("==========De-Serialization Started==========");
FileInputStream fis = new FileInputStream("person.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Object object = ois.readObject();
Person p1 = (Person) object;
System.out.println("Id : " + p1.id);
System.out.println("Name : " + p1.name);
ois.close();
System.out.println("==========De-Serialization Ended==========");
}
}
public class Person implements Serializable {
private static final long serialVersionUID = -100l;
int id;
String name;
String email;
transient String pwd;
}
package in.ashokit;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Person implements Serializable {
private static final long serialVersionUID = -100l;
int id;
String name;
String email;
transient String pwd;
public static void main(String[] args) throws Exception {
Person p = new Person();
p.id = 100;
p.name = "Raju";
p.email = "raju@gmail.com";
p.pwd = "raj@123";
System.out.println("====Serialization Started ========");
FileOutputStream fos = new FileOutputStream("person.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(p);
oos.flush();
oos.close();
System.out.println("====Serialization completed========");
System.out.println("==========De-Serialization Started==========");
FileInputStream fis = new FileInputStream("person.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Object object = ois.readObject();
Person p1 = (Person) object;
System.out.println("Id : " + p1.id);
System.out.println("Name : " + p1.name);
System.out.println("Email : " + p1.email);
System.out.println("Pwd : " + p1.pwd);
ois.close();
System.out.println("==========De-Serialization Ended==========");
}
}
Task : Work
Single Tasking : Performing only one task at a time is called as Single Tasking
1) Explain the topic 2) Dictate the notes 3) Ask questions
If we perform single tasking then it will take lot of time to complete all our work.
Multi Tasking : Performing multiple tasks at a time is called as Multi Tasking
1) Walking & listening music 2) Speaking and Writing 3) Reading book & eating
If we perform multi tasking then we complete multiple works at a time.
Multi Tasking we can achieve in 2 ways
1) Process Based Multi Tasking Ex: Windows OS 2) Thread Based Multi Tasking
To execute our program logic parallelly then we need to go for Thread Based Multi Tasking
Using Thread Based Multi Tasking our program can complete the work quickly
To implement Thread Based Multi Tasking we will use Multi Threading
Java Supports Multi Threading
1) Send sms to all customers at a time 2) Send Email to all customers at a time 3) Generate & Send Bank Statements to all customers in email
// Java Program to get the details of Main thread
public class Demo {
public static void main(String... args) {
Thread currentThread = Thread.currentThread();
System.out.println(currentThread.getName()); // main
}
}
In Java we can create Thread in 2 ways
1) By extending Thread class 2) By Implementing Runnable interface
// Java program to create user defined thread using Thread class
public class Demo extends Thread {
public void run() {
System.out.println("run () method called...");
}
public static void main(String... args) {
Demo d = new Demo();
Thread t = new Thread(d);
t.start();
}
}
// Java program to create the thread using Runnable interface
public class Demo implements Runnable {
public void run() {
System.out.println("run () method called...");
}
public static void main(String... args) {
Demo d = new Demo();
Thread t = new Thread(d);
t.start();
}
}
Q) What is the difference between extending Thread class and implementing Runnable interface, which is recommended ?
Thread Schedular is a program in the JVM which is responsible to schedule Threads execution and resources allocation required for the thread.
When we call start ( ) method then Thread Schedular will start its operation.
1) Allocating Resources 2) Thread Scheduling 3) Thread Execution by calling run ( ) method
To start thread execution we will call start ( ) method
t.start ( )
once start ( ) method is called then Thread Schedular will come into picture to execute our thread
start ( ) method will call run ( ) method internally
Inside run ( ) method we will write the logic which should be executed by the thread.
// Calling run() vs calling start()
public class Demo implements Runnable {
public void run() {
System.out.println("run () method started...");
Thread t = Thread.currentThread();
System.out.println(t.getName());
System.out.println("run () method ended...");
}
public static void main(String... args) {
Demo d = new Demo();
Thread t = new Thread(d);
//t.start();
//t.run();
}
}
Thread Life cycle contains several phases of Thread execution
1) New 2) Runnable 3) Running 4) Blocked 5) Terminated
New : A thread begins its life cycle in the new state. Thread remains in the new state until we will call start ( ) method.
Runnable : After calling start ( ) method, thread comes from new state to runnable state.
Running : A thread comes to running state when Thread Schedular will pick up that thread for execution.
Blocked : A thread is in waiting state if it waits for another thread to complete its task.
Terminated : A thread enters into terminated state once it completes its task.
// Java Program on Thread Sleep
package in.ashokit;
public class Demo implements Runnable {
public void run() {
System.out.println("run () method started...");
try {
Thread.sleep(5000); // blocked state
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("run () method ended...");
}
public static void main(String... args) {
Demo d = new Demo();
Thread t = new Thread(d); // new state
t.start(); // runnable state
}
}
// Java program to start mutliple threads to perform same activity
package in.ashokit;
public class Demo implements Runnable {
public void run() {
System.out.println("run () method started..." + Thread.currentThread().getName());
try {
Thread.sleep(15000); // blocked state
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("run () method ended..." + Thread.currentThread().getName());
}
public static void main(String... args) {
Demo d = new Demo();
Thread t1 = new Thread(d);
t1.setPriority(Thread.MAX_PRIORITY); // 10
t1.setName("Thread-1");
Thread t2 = new Thread(d);
t2.setPriority(Thread.NORM_PRIORITY); // 5
t2.setName("Thread-2");
Thread t3 = new Thread(d);
t3.setPriority(Thread.MIN_PRIORITY); // 1
t3.setName("Thread-3");
t1.start(); // runnable state
t2.start(); // runnable state
t3.start(); // runnable state
}
}
Note: We shouldn't start one thread more than one time.
public static void main(String... args) {
Demo d = new Demo();
Thread t1 = new Thread(d);
t1.start();
t1.start(); // java.lang.IllegalThreadStateException
}
This interface introduced in java 1.5
Using Callable interface also we can create the Thread
This interface contains call ( ) method.
public Object call ( )
Runnable is a functional interface which contains run ( ) method Callable is a functional interface which contains call ( ) method Runnable run ( ) method returns void (no return type) Callable call ( ) method returns Object Runnable interface present in java.lang package Callable interface present in java.util.concurent package
// Java Program on Executor Service with Callable interface
package in.ashokit;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Demo implements Callable {
public Object call() throws Exception {
System.out.println("call ( ) - method executed...");
return "success";
}
public static void main(String[] args) throws Exception {
Demo d = new Demo();
ExecutorService exService = Executors.newFixedThreadPool(10);
for (int i = 1; i <= 15; i++) {
Future submit = exService.submit(d);
System.out.println(submit.get().toString());
}
exService.shutdown();
}
}
We have 3 types of threads in java
1) Default thread created by JVM ( main thread ) 2) User Defined Threads ( Thread class, Runnable interface, Callable interface ) 3) Daemon Threads
Note: The thread which runs in the background is called as Dameon Thread. Daemon Threads also called as low priority threads.
Ex: Garbage Collector is a daemon thread
// Java Program To Make thread as Daemon
package in.ashokit;
public class Demo implements Runnable {
@Override
public void run() {
if (Thread.currentThread().isDaemon()) {
System.out.println("Daemon Thread Executed...");
} else {
System.out.println("Normal Thread Executed...");
}
}
public static void main(String[] args) {
Demo d = new Demo();
Thread t1 = new Thread(d);
t1.setDaemon(true);
t1.start();
}
}
String ----> Immutable class StringBuffer ----> Mutable class & synchronized class (Thread safe class) StringBuilder ---> Mutable class & not-synchronized class (Not Thread Safe class) Synchronized means Thread safe ===> Only one thread can access the object / resource at a time Not-Synchronized means Not Thread Safe ===> Multiple threads can access same resource / object at a time
public class MovieTicketBooking {
int avilableTickets = 100;
public void run ( ) {
if ( availableTickets > 0 ) {
// logic to bookTicket;
-- avilableTickets ;
}
}
public static void main(String... args) {
Thread t1 = new Thread();
Thread t2 = new Thread();
Threa t20 = new Thread();
//t1..... t20 ---start
}
}
Using 'synchronized' keyword we can implement synchronization
synchronized keyword we can use at two places
1) At block level 2) At method level
// Syntax For Synchronized Block
public void m1( ){
// pre-logic
synchronized ( object ) {
// imp business logic
}
// post-logic
}
// Syntax For Synchronized Method
public synchronized void m1( ) {
// important business logic
}
// Java Program with Synchronized Method
public class Demo implements Runnable {
public synchronized void printNums() {
for (int i = 1; i <= 10; i++) {
System.out.println(Thread.currentThread().getName() + "=> " + i);
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void run() {
printNums();
}
public static void main(String[] args) {
Demo d = new Demo();
Thread t1 = new Thread(d);
t1.setName("Thread-1");
t1.start();
Thread t2 = new Thread(d);
t2.setName("Thread-2");
t2.start();
}
}
Note: In the above program we are starting 2 threads. two threads will access printNums ( ) method to print the numbers from 1 to 10.
// Working with Threads using Anonymous Implementation
package in.ashokit;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyThread {
public static void main(String[] args) {
Thread t1 = new Thread() {
public void run() {
System.out.println("run ( ) method logic-1");
}
};
t1.start();
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("run method() logic-2");
}
};
Thread t2 = new Thread(r);
t2.start();
Callable c = new Callable() {
public Object call() throws Exception {
System.out.println("call( ) method logic - 3");
return null;
}
};
ExecutorService exService = Executors.newFixedThreadPool(1);
exService.submit(c);
}
}
Dead Lock means ambiguity problem among the threads
If 2 threads are waiting for each other to release the resources is called as dead lock.
Once we get into dead lock situation then we can't do anything
Thread-1 holding resource-1 and waiting for resource-2 Thread-2 holding resource-2 and waiting for resource-1 Thread-1 will not release resource-1 hence thread-2 will be in waiting state forever for resource-1 Thread-2 will not release resource-2 hence thread-1 will be in waiting state forever for resource-2
// Java program which will give dead lock
package in.ashokit;
public class DeadLock {
public static void main(String[] args) {
String s1 = "hi";
String s2 = "hello";
Thread t1 = new Thread() {
public void run() {
synchronized (s1) {
System.out.println("Thread-1 locked resource-1");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (s2) {
System.out.println("Thread-1 waiting for resource-2");
}
}
}
};
Thread t2 = new Thread() {
public void run() {
synchronized (s2) {
System.out.println("Thread-2 locked resource-2");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (s1) {
System.out.println("Thread-2 waiting for resource-1");
}
}
}
};
t1.start();
t2.start();
}
}
// Java program with yield ( ) method
package in.ashokit;
public class Demo {
public static void main(String[] args) throws Exception {
Thread t1 = new Thread() {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " => " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t1.setName("Thread-1");
Thread t2 = new Thread() {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " => " + i);
try {
Thread.sleep(100);
Thread.yield();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t2.setName("Thread-2");
t1.start();
t1.join();
t2.start();
}
}
// Java program with yield ( ) method
package in.ashokit;
public class YieldDemo {
public static void main(String[] args) {
Thread producer = new Producer();
Thread consumer = new Consumer();
producer.start();
consumer.start();
}
}
class Producer extends Thread {
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println("Producer : Produced Item " + i);
Thread.yield();
}
}
}
class Consumer extends Thread {
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println("Consumer : Consumed Item " + i);
Thread.yield();
}
}
}
It is used to establish communication among the threads
To achieve inter thread communication we have below 3 methods in Object class
1) wait ( ) 2) notify ( ) 3) notifyAll ( )
Q) Why these 3 methods available in Object class, why not in Thread class ?
// Java Program to establish inter thread communication
package in.ashokit;
public class Customer {
int amount = 10000;
synchronized void withdraw(int amount) {
System.out.println("going to withdraw...");
if (this.amount < amount) {
System.out.println("Less balance; waiting for deposit...");
try {
wait();
} catch (Exception e) {
}
}
this.amount -= amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount) {
System.out.println("going to deposit...");
this.amount += amount;
System.out.println("deposit completed... ");
notify();
}
public static void main(String args[]) {
final Customer c = new Customer();
new Thread() {
public void run() {
c.withdraw(15000);
}
}.start();
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread() {
public void run() {
c.deposit(10000);
}
}.start();
}
}
// Getting Fields, Constructors and Methods information of a class
// Class Student
package in.ashokit;
public class Student {
private int id;
private String name;
public void display() {
System.out.println("hi");
}
public void m1() {
System.out.println("this is m1()");
}
public void m2() {
System.out.println("this is m2()");
}
}
// Class Demo
package in.ashokit;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Demo {
public static void main(String[] args) throws Exception {
Class clz = Class.forName("in.ashokit.Student");
Field[] fields = clz.getDeclaredFields();
for (Field f : fields) {
System.out.println(f.getName());
}
Method[] methods = clz.getDeclaredMethods();
for (Method m : methods) {
System.out.println(m.getName());
}
Constructor[] constructors = clz.getDeclaredConstructors();
for (Constructor c : constructors) {
System.out.println(c.getName());
}
}
}
// Accessing private variable outside of the class using Reflection API
// Class Student
package in.ashokit;
public class Student {
private int age = 20;
public void getAge() {
System.out.println("Age : " + age);
}
}
// Class Demo
package in.ashokit;
import java.lang.reflect.Field;
public class Demo {
public static void main(String[] args) throws Exception {
// loading class into jvm
Class clz = Class.forName("in.ashokit.Student");
// creating object for the loaded class
Object obj = clz.newInstance();
// getting the filed whose name is age
Field field = clz.getDeclaredField("age");
// making variable accessible outside of the class
field.setAccessible(true);
// set value to field
field.set(obj, 35);
Student s = (Student) obj;
s.getAge();
}
}
// Invoking the methods using Reflection API
package in.ashokit;
import java.lang.reflect.Method;
public class Demo {
public static void main(String[] args) throws Exception {
Class<?> clz = Class.forName("in.ashokit.Student");
Method method = clz.getDeclaredMethod("getAge");
Object obj = clz.newInstance();
method.invoke(obj, null);
}
}
Q) What is the difference between ClassNotFoundException and NoClassDefFoundError ?
// Garbage Collection
package in.ashokit;
public class Student {
public static void main(String[] args) {
// Object created
Student s1 = new Student();
// nullifying (making obj eligible for GC)
s1 = null;
System.gc();
}
protected void finalize() throws Throwable {
System.out.println("finalize( ) called...");
}
}
In java we have 2 ways to invoke GC
System.gc(); Runtime.getRuntime().gc();
Note: Even if we call above methods there is no guarantee that JVM will start GC immediately.
GC execution process will be managed by JVM only.
Garbage Collection works in below phases
1) Stop the world 2) Marking 3) Sweeping 4) Compaction
When GC starts it will trigger STOP THE WORLD (all running threads will be stopped for few mili secs)
GC will go to JVM Heap area and it will identify un-referenced objects and it will mark them for sweep.
GC will sweep marked objects
After sweeping completed memory holes will be created in Heap area to clear that GC will perform Compaction (it will adjust memory holes).
After Compaction, GC will give signal to JVM to continue the execution.
Note: GC process will slow down our program execution hence Sun Microsystem didn't give the chance for programmers to perform Garbage Collection. It will be managed by JVM.
public void m1 ( Integer i ){
// logic
}
m1 (10) ; // valid
m1 ("hi") ; // in-valid
// Java program using Generics
package in.ashokit;
public class Demo<T> {
public void m1(T arg) {
System.out.println("Param Recieved : " + arg);
}
public static void main(String[] args) throws Exception {
Demo d = new Demo();
d.m1(10); // passing int value
d.m1("hi"); // passing String value
d.m1(100.51); // passing double value
d.m1(true); // passing boolean value
}
}
// Java program with Generic Type to achieve Type Safety
package in.ashokit;
public class Demo<T> {
T obj;
void add(T obj) {
this.obj = obj;
}
T get() {
return obj;
}
public static void main(String[] args) throws Exception {
Demo<Integer> d1 = new Demo<>();
d1.add(10);
System.out.println(d1.get());
Demo<String> d2 = new Demo<>();
d2.add("Hi");
System.out.println(d2.get());
}
}
// Java Program with Generic Parameters for Constructor
package in.ashokit;
public class Demo<T1, T2> {
T1 obj1;
T2 obj2;
Demo(T1 obj1, T2 obj2) {
this.obj1 = obj1;
this.obj2 = obj2;
}
void print() {
System.out.println(obj1 + ", " + obj2);
}
public static void main(String[] args) throws Exception {
Demo<Integer, String> d1 = new Demo<>(101, "Ram");
d1.print();
Demo<String, Long> d2 = new Demo<>("Ashok", 798686868l);
d2.print();
Demo<String, Boolean> d3 = new Demo<>("Raju", true);
d3.print();
}
}
Demo< ? extends Number >
enum WEEKDAYS {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY;
}
enum WEEKENDDAYS {
SATURDAY, SUNDAY;
}
1) Enum constants we can't override 2) Enum doesn't support object creation 3) Enum can't extend classes 4) Enum can be created in seperate file or we can create in existing class also
// Program using Enum
// Course.java
package in.ashokit;
public enum Course {
JAVA, PYTHON, DEVOPS, AWS, DOCKER, KUBERNETES;
}
// Demo.java
package in.ashokit;
public class Demo {
public static void main(String[] args) throws Exception {
Course[] values = Course.values();
for (Course c : values) {
System.out.println(c);
}
}
}
class A {
class B {
// logic
}
}
class A - is called as outer class class B - is called as inner class
Non static inner classes
1.1 Regular Inner classes 1.2 Method local inner class 1.3 Anonymous inner class
Static inner classes
// Program using Inner Classes
package in.ashokit;
public class Outer {
void outerMethod() {
Inner i = new Inner();
i.innerMethod();
}
public static void main(String[] args) {
Outer o = new Outer();
o.outerMethod();
}
private class Inner {
void innerMethod() {
System.out.println("inner method called...");
}
}
}
Class Loaders are used to load .class files into JVMs memory
In java, we have 3 types of Class Loaders
1) Bootstrap Class Loader 2) Extension Class Loader 3) Application Class Loader
Bootstrap class loader is responsible to load all the predefined java classes available in rt.jar file
Note: rt.jar means Runtime Jar (java.lang, java.io, java.util etc all these packages related classes available in rt.jar file only)
rt.jar file will present in jre/lib folder
Extension Class Loader is responsible to load java classes which are part of ext folder
C:\Program Files\Java\jre1.8.0_202\lib\ext
Application Class Loader is responsible to load our application / project classes
1) Bootstrap Class Loader 2) Extension Class Loader 3) Application Class Loader
variables --> to store the data
data type --> type of data that we can store in variable
int a = 10; int b = 20 ; int c = 30 ;
I want to store 1000 values ? ---- 1000 variables we need
I wan to store 1 lakh values ? ----> 1 lakh variables ---> Not recommended
To overcome this problem we are using Arrays concept in java
We can store group of values in single variable
int [ ] a = new int [ 5000 ] ; arr[0] = 100; arr[1] = 200; arr[2] = 300; .... arr[4999] = 7799;
Limitations
1) Array size is fixed 2) We can store only homogeneous values (same type of values)
Student s [ ] = new Student [ 100 ];
s[0] = new Student(10, "Raju"); // valid
s[1] = new Student(11, "Rani"); // valid
s[2] = new Employee(101, "Ramesh"); // invalid
...
s[99] = new Student(999, "john"); // valid
Object [ ] a = new Object [ 100 ]; a[0] = new Student(101, "Raju"); a[1] = new Student(102, "Rani"); a[2] = new Employee(101, "Raju", 1000.00); a[3] = new Employee(102, "Rani", 2000.00); a[2] = new Customer(101, "Raju", 1000.00); a[3] = new Customer(102, "Rani", 2000.00);
Limitations
1) Size is fixed 2) no methods to insert, update, retrieve, sort the data
To overcome the problems of Arrays we are going to use Collections
Collections are used to store group of objects / values
Collections are growable in nature (dynamically collection size can be increased and decreased based on data)
We can store any type of data in Collection (homogeneous & heterogeneous)
Collections providing predefined methods to insert, update, delete, retrieve, sort etc.
Collections is a entity / container which is used to store group of Objects
Collections ----> Collections Framework Framework means ready made software
Collections is called as framework because it is providing predefined interfaces, classes and methods to perform operations on data.
1) Iterable (I) 2) Collection (I) 3) List (I) 4) Set (I) 5) Queue (I) 6) Map (I)
List : It is used to store group of objects ( duplicates are allowed )
1) ArrayList 2) LinkedList 3) Vector 4) Stack
Set : It is used to store group of objects ( duplicates are not allowed )
1) HashSet 2) LinkedHashSet 3) TreeSet
Queue : It is used to store group of objects ( FIFO )
1) PriorityQueue 2) ArrayDeque
Map : It is used to store group of objects ( Key - Value pair )
1) HashMap 2) LinkedHashMap 3) Hashtable 4) TreeMap 5) IdentityHashMap 6) WeakHashMap
Cursors are used to iterate collections (retrieve data from collections)
1) Iterator 2) ListIterator 3) Enumeration
Collections framework related classes & interfaces are part of java.util package
Extending properties from Collection interface
Allow duplicate objects
It will maintain objects insertion order
It is having 4 implementation classes
1) ArrayList 2) LinkedList 3) Vector 4) Stack
List l = new List ( ); // invalid
List l = new ArrayList ( ) ; // valid
List l = new LinkedList ( ) ; // valid
ArrayList Constructors
ArrayList al = new ArrayList ( ) ;
ArrayList al = new ArrayList (int capacity);
ArrayList al = new ArrayList (Collection c);
Methods of ArrayList
1) add(Object obj ) ---> add object at end of the collection 2) add(int index, Object) --> add object at given index 3) addAll(Collection c) ---> to add collection of objects at end of the collection 4) remove(Object obj) ---> To remove given object 5) remove(int index) ----> to remove object based on given index 6) get(int index) --> to get object based on index 7) contains(Object obj) ---> To check presense of the object 8) clear( ) ---> to remove all objects from collection 9) isEmpty( ) ---> to check collection is empty or not 10) retainAll(Collection c) --> keep only common elements and remove remaining object 11) indexOf(Object obj) --> to get first occurence of given obj 12) lastIndexOf(Object obj) ---> to get last occurance of given object 13) set(int index, Object obj) ---> replace the object based on given index 14) iterator( ) --> forward direction 15) listIterator( ) --> forward & back
// ArrayList Program using Primitive Types
public class Demo {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<>();
al.add(10);
al.add(20);
al.add(30);
al.add(40);
System.out.println("======For Loop Approach=======");
// Approach-1
for (int i = 0; i < al.size(); i++) {
System.out.println(al.get(i));
}
System.out.println("======For-Each loop Approach=======");
// Approach-2
for (Object obj : al) {
System.out.println(obj);
}
System.out.println("=====Iterator Approach=====");
// Approach-3
Iterator iterator = al.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
System.out.println("=====ListIterator Approach=====");
// Approach-4
ListIterator listIterator = al.listIterator();
while (listIterator.hasNext()) {
System.out.println(listIterator.next());
}
System.out.println("=====forEach ( ) Approach=====");
// Approach-5
al.forEach(i -> {
System.out.println(i);
});
}
}
// ArrayList Program using Referenced Type
public class Student {
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public String toString() {
return id + " - " + name;
}
}
public class Demo {
public static void main(String[] args) {
ArrayList<Student> al = new ArrayList<>();
al.add(new Student(1, "Raju"));
al.add(new Student(2, "John"));
al.add(new Student(3, "Smith"));
al.add(new Student(4, "Rani"));
ListIterator<Student> li = al.listIterator();
while (li.hasNext()) {
System.out.println(li.next());
}
System.out.println("=====================");
while (li.hasPrevious()) {
System.out.println(li.previous());
}
}
}
// LinkedList Program
public class Demo {
public static void main(String[] args) {
LinkedList<Integer> ll = new LinkedList<>();
ll.add(10); // 1 node
ll.add(20); // 1 node
ll.add(30); // 1 node
ll.add(40); // 1 node
System.out.println(ll); // 10, 20, 30, 40
ll.add(1, 15);
System.out.println(ll); // 10, 15, 20, 30, 40
System.out.println(ll.getLast());
}
}
// Vector Program
public class Demo {
public static void main(String[] args) {
Vector<Integer> v = new Vector<>();
v.add(100);
v.add(200);
v.add(300);
v.add(null);
Enumeration<Integer> elements = v.elements();
while (elements.hasMoreElements()) {
System.out.println(elements.nextElement());
}
}
}
Implementation class of List interface
Extending from Vector class
Data Structure of Stack is LIFO (last in first out)
push( ) ---> to insert object peek( ) ---> to get last element pop( ) ---> to remove last element 1) ArrayList ---------> Growable Array 2) LinkedList ----------> Double Linked List 3) Vector -------------> Growable Array & Thread Safe 4) Stack -----------> L I F O 5) Iterator ----> forward direction ( List & Set ) 6) ListIterator ---> forward & backward direction ( List impl classes ) 7) Enumeration ----> forward direction & supports for legacy collection classes
Set is a interface available in java.util package
Set interface extending from Collection interface
Set is used to store group of objects
Duplicate objects are not allowed
Supports homogeneous & heterogeneous
1) HashSet 2) LinkedHashSet 3) TreeSet
HashSet Constructors
HashSet hs = new HashSet( ); HashSet hs = new HashSet(int capacity); HashSet hs = new HashSet(int capacity, float loadFactor);
// Java Program on HashSet
public class Demo {
public static void main(String[] args) {
HashSet<String> hs = new HashSet<>(100, 10.05f);
hs.add("one");
hs.add("two");
hs.add("three");
hs.add("four");
hs.add("one");
hs.add(null);
System.out.println(hs);
hs.remove("three");
System.out.println(hs);
Iterator<String> iterator = hs.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
// HashSet Program using Reference Type
public class Demo {
public static void main(String[] args) {
HashSet<Student> hs = new HashSet<>();
hs.add(new Student(101, "Raju"));
hs.add(new Student(102, "Rani"));
hs.add(new Student(103, "John"));
Iterator<Student> iterator = hs.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
// Java Program ob LinkedHashSet
public class Demo {
public static void main(String[] args) {
LinkedHashSet<Integer> lhs = new LinkedHashSet<>();
lhs.add(10);
lhs.add(20);
lhs.add(30);
lhs.add(null);
lhs.add(40);
lhs.add(20);
System.out.println(lhs);
}
}
Note: HashSet will not maintain insertion order where as LinkedHashSet will maintain insertion order.
// Java Program using TreeSet
public class Demo {
public static void main(String[] args) {
TreeSet ts = new TreeSet();
ts.add("raja");
ts.add("raja");
ts.add("rani");
ts.add("ashok");
System.out.println(ts); // ashok, raja, rani
Iterator iterator = ts.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
List interface & implementation classes
- duplicates allowed - insertion order maintained - homogenious & heterogenious data allowed Ex: ArrayList, LinkedList, Vector & Stack
Set interface & implementation classes
- Duplicates not allowed - only LHS will maintain insertion order - TreeSet supports only homogenious data (For sorting) Ex: HashSet, LinkedHashSet & TreeSet
Map is an interface available in java.util package
Map is used to store the data in key-value format
One Key-Value pair is called as one Entry
One Map object can have multiple entries
In Map, keys should be unique and values can be duplicate
If we try to store duplicate keys in map then it will replace old key data with new key data
We can take Key & Value as any type of data
Ex:-1 : Map<Integer, String> 101 - John 102 - Smith 103 - David 104 - Robert 105 - Orlen 101 - Charles Ex:-2 : Map<String, Integer> India - 120 USA - 30 UK - 20
Map interface having several implementation classes
1) HashMap 2) LinkedHashMap 3) TreeMap 4) Hashtable 5) IdentityHashMap 6) WeakHashMap
Map Methods
1) put(k,v) ---> To store one entry in map object 2) get(k) ---> to get value based on given key 3) remove(k) ---> to remove one entry based on given key 4) containsKey(k) ---> to check presense of given key 5) keySet( ) ---> To get all keys of map 6) values( ) ----> To get all values of the map 7) entryset( ) --> to get all entries of map 8) clear( ) --> to remove all the entries of map 9) isEmpty( ) --> To check weather map obj is empty or not 10) size( ) --> to get size of the map (how many entries avaiable)
// Java Program on Map using Primitive Type
public class Demo {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(101, "John");
map.put(102, "Smith");
map.put(103, "Orlen");
map.put(102, "David");
System.out.println("Map size :: " + map.size()); // 3
System.out.println(map.get(101)); // john
System.out.println(map.get(300)); // null
Collection<String> values = map.values();
for(String v : values) {
System.out.println(v);
}
Set<Integer> keySet = map.keySet();
for (Integer key : keySet) {
System.out.println(key +"--"+map.get(key));
}
Set<Entry<Integer, String>> entrySet = map.entrySet();
Iterator<Entry<Integer, String>> iterator = entrySet.iterator();
while(iterator.hasNext()) {
Entry<Integer, String> entry = iterator.next();
System.out.println(entry.getKey()+"--"+entry.getValue());
}
for(Entry<Integer,String> entry : entrySet) {
System.out.println(entry.getKey()+"--"+entry.getValue());
}
System.out.println(map.containsKey(102));
System.out.println(map.containsKey(200));
System.out.println(map.isEmpty());
map.clear();
System.out.println(map.size());
}
}
// Java Program on Map using Reference Type
public class StudentMapDemo {
public static void main(String[] args) {
Student s1 = new Student(101, "John");
Student s2 = new Student(102, "Smith");
Student s3 = new Student(103, "Orlen");
Map<Integer, Student> map = new HashMap<Integer, Student>();
map.put(1, s1);
map.put(2, s2);
map.put(3, s3);
Set<Integer> keySet = map.keySet();
for(Integer key : keySet) {
System.out.println(map.get(key));
}
Set<Entry<Integer,Student>> entrySet = map.entrySet();
for(Entry<Integer,Student> entry : entrySet) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
}
// java program with Priority Queue
public class QueueDemo {
public static void main(String[] args) {
PriorityQueue<String> queue = new PriorityQueue<>();
queue.add("john");
queue.add("smith");
queue.add("orlen");
queue.add("charles");
System.out.println(queue);
System.out.println(queue.element());
System.out.println(queue.peek());
Iterator<String> iterator = queue.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
queue.remove();
queue.poll();
}
}
// Java program with ArrayDequeue
public class ArrayDequeueDemo {
public static void main(String[] args) {
ArrayDeque<String> ad = new ArrayDeque<>();
ad.add("one");
ad.add("two");
ad.add("three");
ad.addFirst("ashok");
System.out.println(ad);
ad.pollFirst();
System.out.println(ad);
ad.pollLast();
System.out.println(ad);
}
}
It is implementation class for Map interface
Default capacity is 11
Load factor 0.75
key-value format to store the data
Hashtable is legacy class (jdk 1.0 v)
Hashtable is synchronized
If thread safety is not required then use HashMap instead of Hastable. If thread safety is important then go for ConcurrentHashMap instead of hashtable.
If java application wants to communicate with database, then we need to configure database credentials in java program.
If we hardcode database credentials in java program then project maintenance will become difficult why because in future if database credentials modified then we need to modify our java program also.
If java program is modified then we need to re-compile and re-execute our program/project which will take lot of time and it may break existing code.
To overcome above problems we should not do hardcoding.
To avoid hard coding in java projects we will use java.util.Properties class.
Properties class is used to read the data from properties file
properties file contains data in key-value format (like map)
Note: Properties file extension will be .properties
Create database.properties file with below data in project folder
------------ database.properties ------------ uname=ashokit pwd=ashokit@123 ---------------------------------------------
Create below java class to read data from properties file
// Java Program using Properties Class
package in.ashokit;
import java.io.FileInputStream;
import java.util.Properties;
public class DatabaseApp {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("database.properties");
Properties p = new Properties();
p.load(fis); // load all the properties from properties file
System.out.println(p);
String uname = p.getProperty("uname");
String pwd = p.getProperty("pwd");
String driver = p.getProperty("driver"); // key not present
System.out.println("Username: " + uname);
System.out.println("Password: " + pwd);
System.out.println("Driver: " + driver); // null
fis.close();
}
}
Collection is a container which is used to store group of objects
Note: Collection interface is available in java.util package
List, Set & Queue interfaces are extending properties from Collection interface
In Collections framework we have a class called Collections class
Note: Collections is a predefined class available in java.util package
Collections class provided several static methods to perform operations on data like below
Collections.sort(al); Collections.reverse(al);
Q) What is the difference between Collection, Collections & Collections Framework ?
Collection is a container to store group of objects. We have an interface with a name Collection (java.util). It is root interface in Collections framework.
Collections is a class available in java.util package (Providing ready made methods to perform operations on objects)
Collection interface & Collections class are part of Collections framework. Along with these 2 classes there are several other classes and interfaces in Collections framework.
// Java program on Collections class
package in.ashokit;
import java.util.ArrayList;
import java.util.Collections;
public class Demo {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<>();
al.add(5);
al.add(3);
al.add(4);
al.add(1);
al.add(2);
System.out.println("Before Sort : " + al);
// Sort the collection
Collections.sort(al);
System.out.println("After Sort : " + al);
// Reverse the collection
Collections.reverse(al);
System.out.println("After Reverse : " + al);
}
}
Note: In the above program we have added Integer values in the collection. Integer is a class wrapper and it is implementing Comparable interface already.
If we want apply sorting on User-Defined objects like Student, Employee, Product, Customer etc... then we have 2 approaches
1) Comparable (java.lang) 2) Comparator (java.util)
Comparable is a predefined interface available in java.lang package
Comparable interface having compareTo ( Object obj ) method
compareTo ( ) method is used to compare an object with itself and returns int value
if( obj1 > obj2 ) ----> returns +ve no if( obj1 < obj2 ) ----> return -ve no if ( obj1 == obj2 ) ----> return zero (0)
// Java Program using Comparable
// Student class
package in.ashokit;
public class Student implements Comparable<Student> {
int id;
String name;
int rank;
public Student(int id, String name, int rank) {
this.id = id;
this.name = name;
this.rank = rank;
}
@Override
public int compareTo(Student s) {
return this.id - s.id;
// return this.name.compareTo(s.name);
// return this.rank - s.rank;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", rank=" + rank + "]";
}
}
// StudentDemo class
package in.ashokit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class StudentDemo {
public static void main(String[] args) {
List<Student> al = new ArrayList<>();
al.add(new Student(101, "John", 3));
al.add(new Student(104, "Anil", 4));
al.add(new Student(102, "Smith", 2));
al.add(new Student(103, "Robert", 1));
Collections.sort(al);
for (Student s : al) {
System.out.println(s);
}
}
}
Note: Comparable interface will allow us to sort the data based on only one value. If we want to change our sorting technique then we need to modify the class which is implementing Comparable interface. Modifying the code everytime is not recommended.
// Java Program using Comparator
// Employee class
package in.ashokit;
public class Employee {
int id;
String name;
double salary;
public Employee(int id, String name, double salary) {
super();
this.id = id;
this.name = name;
this.salary = salary;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", salary=" + salary + "]";
}
}
// EmpIdComparator class
package in.ashokit;
import java.util.Comparator;
public class EmpIdComparator implements Comparator<Employee> {
@Override
public int compare(Employee e1, Employee e2) {
return e1.id - e2.id;
}
}
//EmpNameComparator
package in.ashokit;
import java.util.Comparator;
public class EmpNameCompartor implements Comparator<Employee> {
@Override
public int compare(Employee e1, Employee e2) {
return e1.name.compareTo(e2.name);
}
}
// EmpDemo class
package in.ashokit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class EmpDemo {
public static void main(String[] args) {
ArrayList<Employee> emps = new ArrayList<>();
emps.add(new Employee(101, "David", 15000.00));
emps.add(new Employee(105, "Putin", 25000.00));
emps.add(new Employee(103, "Cathy", 45000.00));
emps.add(new Employee(104, "Anny", 35000.00));
// Collections.sort(emps, new EmpIdComparator());
// Collections.sort(emps, new EmpNameCompartor());
Collections.sort(emps, new Comparator<Employee>() {
@Override
public int compare(Employee e1, Employee e2) {
if (e1.salary > e2.salary) {
return -1;
} else if (e1.salary < e2.salary) {
return 1;
} else {
return 0;
}
}
});
for (Employee e : emps) {
System.out.println(e);
}
}
}
Collections are divided into 2 types
1) Fail Fast Collections 2) Fail Safe Collections
Fail Fast collections will throw error immediately when we modify collection object while traversing the collection
Ex: ArrayList, LinkedList, Vector, HashSet, LHS etc...
Note: Fail Fast collections will throw concurrent modification exception when collection is modified
Fail Safe collections will not throw any error even if we modify collection object data (Add / Remove) while traversing
Ex: CopyOnWriteArrayList, ConcurrentHashMap etc...
// Fail Fast Collection
public class Demo {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<>();
al.add(100);
al.add(200);
al.add(300);
al.add(400);
for (int i : al) {
System.out.println(i);
if (i == 100) {
al.add(150);
}
}
}
}
// Fail Safe Collection
public class Demo {
public static void main(String[] args) {
CopyOnWriteArrayList<Integer> al = new CopyOnWriteArrayList<>();
al.add(100);
al.add(200);
al.add(300);
al.add(400);
for (int i : al) {
System.out.println(i);
if (i == 100) {
al.add(150);
}
}
System.out.println(al);
}
}
// Fail First Example
package in.ashokit;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class Demo {
public static void main(String[] args) {
HashMap<Integer,String> map = new HashMap<>();
map.put(101, "one");
map.put(102, "two");
map.put(103, "three");
Set<Integer> keySet = map.keySet();
Iterator<Integer> iterator = keySet.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
map.put(104, "four");
}
}
}
// Fail Safe Example
package in.ashokit;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class Demo {
public static void main(String[] args) {
ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>();
map.put(101, "one");
map.put(102, "two");
map.put(103, "three");
Set<Integer> keySet = map.keySet();
Iterator<Integer> iterator = keySet.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
map.put(104, "four");
}
System.out.println(map);
}
}
// Java Program on IdentityHashMap
package in.ashokit;
import java.util.HashMap;
import java.util.IdentityHashMap;
public class Demo {
public static void main(String[] args) {
HashMap<String, Integer> hm = new HashMap<>();
// HM will compare content of keys to find duplicate keys (equals())
hm.put("ashok", 101); // 1 entry added
hm.put("raja", 102); // 1 entry added
hm.put("rani", 103); // 1 entry added
hm.put(new String("ashok"), 104); // it will replace first entry value bcz key is duplicae
System.out.println("HM - Size :: " + hm.size());
System.out.println(hm);
System.out.println("=================");
IdentityHashMap<String, Integer> ihm = new IdentityHashMap<>();
// IHM will compare address of keys to find duplicate keys (==)
ihm.put("ashok", 101); // 1 entry added (scp)
ihm.put("raja", 102); // 1 entry added
ihm.put("rani", 103); // 1 entry added
ihm.put(new String("ashok"), 104); // 1 entry added
ihm.put("ashok", 105); // it will replace first entry value
System.out.println("IHM - Size :: " + ihm.size());
System.out.println(ihm);
}
}
// Java Program on WeakHashMap
import java.util.HashMap;
import java.util.WeakHashMap;
public class Demo {
public static void main(String[] args) {
// Create a HashMap
HashMap<Object, String> hashMap = new HashMap<>();
Object key1 = new Object();
hashMap.put(key1, "Value 1");
// Create a WeakHashMap
WeakHashMap<Object, String> weakHashMap = new WeakHashMap<>();
Object key2 = new Object();
weakHashMap.put(key2, "Value 2");
// Make the keys eligible for garbage collection
key1 = null;
key2 = null;
// Run garbage collection
System.gc();
// Check the maps
System.out.println("HashMap size: " + hashMap.size()); // Output: 1
System.out.println("WeakHashMap size: " + weakHashMap.size()); // Output: 0
}
}
java.util.Scanner java.util.StringTokenizer java.util.Date java.util.Calendar
// Java Program on Scanner class
import java.util.Scanner;
class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first num : ");
int a = sc.nextInt();
System.out.println("Enter second num : ");
int b = sc.nextInt();
System.out.println("Result : "+(a+b));
sc.close();
}
}
// Java Program on String Tokenizer class
import java.util.StringTokenizer;
class Test {
public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("Java Programming Course", " ");
while(st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
// Java Program on Date and Calendar class
import java.util.Calendar;
import java.util.Date;
class Test {
public static void main(String[] args) {
Date d = new Date();
System.out.println(d);
Calendar c = Calendar.getInstance();
System.out.println(c.YEAR);
System.out.println(c.HOUR_OF_DAY);
}
}
Java 1.0 Java 1.1 Java 1.2 (Collection Framework) .. Java 1.5 (Big Release) .. Java 1.8 (Big Release) ------- Functional Programming .. Java 19
Java 1.8v introduced lot of new features in java
Java 1.8v new features changed java programming style
1) Interface changes 1.1 ) Default Methods 1.2 ) Static Methods 2) Functional Interfaces (@FunctionalInterface) 2.1 ) Predicate & BiPredicate 2.2 ) Consumer & BiConsumer 2.3 ) Supplier 2.4 ) Function & BiFunction 3) Lambda Expressions 4) Method References & Constructor References 5) Stream API 6) Optional class (to avoid null pointer exceptions) 7) Spliterator 8) StringJoiner 9) forEach ( ) method 10) Date & Time API 11) Nashron Engine 12) I/O Stream Changes (Files.lines(Path p)) 13) Base64 Encoding & Decoding
// Multiple classes implementing same interface
interface Vehicle {
public abstract void startVechicle ( );
}
class Car implements Vehicle {
public void startVehicle ( ) {
// logic to start car
}
}
class Bus implements Vehicle {
public void startVehicle ( ) {
// logic to start bus
}
}
class Bike implements Vehicle {
public void startVehicle ( ) {
// logic to start bike
}
}
If we add new method in interface then Car, Bike and Bus will fail at compile time.
To overcome above problem we will use Default & Static methods
1) Interface can have concreate methods from 1.8v 2) Interface concrete method should be default or static 3) interface default methods we can override in impl classes 4) interface static methods we can't overide in impl classes 5) We can write multiple default & static methods in interface 6) Default & Static method introduced to provide backward compatibility
forEach ( ) method added in java.util.Iterable interface as default method in 1.8v
// Program using default and static method of interface
package in.ashokit;
interface Vehicle {
public void start();
public default void m1() {
// logic
}
public default void m2() {
// logic
}
public static void clean() {
System.out.println("cleaning completed...");
}
}
public class Car implements Vehicle {
public void start() {
System.out.println("car started...");
}
public static void main(String[] args) {
Car c = new Car();
Vehicle.clean();
c.start();
}
}
Lambda is an anonymous function
- No Name - No Modifier - No Return Type
// Example-1
public void m1 ( ){
s.o.p("hi");
}
( ) -> { s.o.p ("hi") }
( ) -> s.o.p ("hi");
// Example-2
public void add (int a, int b){
s.o.p(a+b);
}
(int a, int b) -> { s.o.p (a+b) };
(int a, int b) -> s.o.p (a+b);
(a, b) -> s.o.p(a+b);
// Example-3
public int getLength (String name) {
return name.length ( );
}
(String name) -> { return name.length ( ) };
(String name) -> return name.length ( ) ;
(name) -> return name.length ( );
name -> name.length ( ) ;
// Example-4
public Double getEmpSalary (Employee emp) {
return emp.getSalary ( );
}
emp -> emp.getSalary ( );
The interface which contains only one abstract method is called as Functional Interface
Functional Interfaces are used to invoke Lambda expressions
Below are some predefined functional interfaces
Runnable ------------> run ( ) method Callable ----------> call ( ) method Comparable -------> compareTo ( )
To represent one interface as Functional Interface we will use @FunctionalInterface annotation.
@FunctionalInterface
public interface MyInterface {
public void m1( );
}
Note: When we write @FunctionalInterface then our compiler will check interface contains only one abstract method or not.
In Java 8 several predefined Functional interfaces got introduced they are
1) Predicate & BiPredicate 2) Consumer & BiConsumer 3) Supplier 4) Function & BiFunction
The above interfaces are provided in java.util.function package
interface Predicate {
boolean test(T t);
}
// Predicate Example
package in.ashokit.java8;
import java.util.function.Predicate;
public class PredicateDemo {
public static void main(String[] args) {
Predicate<Integer> p = i -> i > 10;
System.out.println(p.test(5));
System.out.println(p.test(15));
}
}
Q: Declare names in an array and print names which are starting with 'A' using lambda expression.
String[ ] names = {"Anushka", "Anupama", "Deepika", "Kajol", "Sunny" };
package in.ashokit.java8;
import java.util.function.Predicate;
public class PredicateDemo2 {
public static void main(String[] args) {
String[ ] names = { "Anushka", "Anupama", "Deepika", "Kajol", "Sunny" };
Predicate<String> p = name -> name.charAt(0) == 'A';
for (String name : names) {
if ( p.test(name) ) {
System.out.println(name);
}
}
}
}
Q: Take list of persons and print persons whose age is >= 18 using lambda expression.
package in.ashokit.java8;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public class PredicatePersonsDemo {
public static void main(String[] args) {
Person p1 = new Person("John", 26);
Person p2 = new Person("Smith", 16);
Person p3 = new Person("Raja", 36);
Person p4 = new Person("Rani", 6);
List<Person> persons = Arrays.asList(p1, p2, p3, p4);
Predicate<Person> predicate = p -> p.age >= 18;
for (Person person : persons) {
if (predicate.test(person)) {
System.out.println(person.name);
}
}
}
}
To combine multiple predicates we will use Predicate Joining
and ( ) method or ( ) method
Q: Print emp names who are working in Hyd location in DB team.
package in.ashokit.java8;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
class Employee {
String name;
String location;
String dept;
Employee(String name, String location, String dept) {
this.name = name;
this.location = location;
this.dept = dept;
}
}
public class PredicateJoinDemo {
public static void main(String[] args) {
Employee e1 = new Employee("Anil", "Chennai", "DevOps");
Employee e2 = new Employee("Rani", "Pune", "Networking");
Employee e3 = new Employee("Ashok", "Hyd", "DB");
Employee e4 = new Employee("Ganesh", "Hyd", "DB");
List<Employee> emps = Arrays.asList(e1, e2, e3, e4);
Predicate<Employee> p1 = (e) -> e.location.equals("Hyd");
Predicate<Employee> p2 = (e) -> e.dept.equals("DB");
Predicate<Employee> p3 = (e) -> e.name.startsWith("A");
// Predicate Joining
Predicate<Employee> p = p1.and(p2).and(p3);
for (Employee e : emps) {
if (p.test(e)) {
System.out.println(e.name);
}
}
}
}
// OTP Generation Program using Supplier
package in.ashokit.java8;
import java.util.function.Supplier;
public class SupplierDemo {
public static void main(String[] args) {
Supplier<String> s = () -> {
String otp = "";
for (int i = 1; i <= 6; i++) {
otp = otp + (int) (Math.random() * 10);
}
return otp;
};
System.out.println(s.get());
System.out.println(s.get());
System.out.println(s.get());
System.out.println(s.get());
System.out.println(s.get());
System.out.println(s.get());
}
}
// Java Program using Consumer
package in.ashokit.java8;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class ConsumerDemo {
public static void main(String[] args) {
Consumer<String> c = (name) -> System.out.println(name + ", Good Evening");
c.accept("Ashok");
c.accept("John");
c.accept("Rani");
List<Integer> numbers = Arrays.asList(10, 20, 30, 40);
numbers.forEach(i -> System.out.println(i));
}
}
Predicate ------> takes inputs ----> returns true or false ===> test ( ) Supplier -----> will not take any input---> returns output ===> get ( ) Consumer ----> will take input ----> will not return anything ===> accept ( ) Function -----> will take input ---> will return output ===> apply ( )
interface Function<R,T>{
R apply (T t);
}
// Java Program using Function unactional interface
package in.ashokit.java8;
import java.util.function.Function;
public class FunctionDemo {
public static void main(String[] args) {
Function<String, Integer> f = (name) -> name.length();
System.out.println(f.apply("ashokit"));
System.out.println(f.apply("hyd"));
System.out.println(f.apply("sachin"));
}
}
Q: Take 2 inputs and perform sum of two inputs and return output.
BiFunction<Integer,Integer,Integer> bif = (a,b) -> a+b; Integer sum = bi.apply(10,20);
// Invoking static method using Method Reference
package in.ashokit.java8;
@FunctionalInterface
interface MyInterface {
public void m1();
}
public class MethodRef {
public static void m2() {
System.out.println("This is m2( ) method");
}
public static void main(String[] args) {
MyInterface mi = MethodRef::m2;
mi.m1();
}
}
// Invoking instance method using Method Reference
package in.ashokit.java8;
public class InstanceMethodRef {
public void m1() {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
public static void main(String[] args) {
InstanceMethodRef im = new InstanceMethodRef();
Runnable r = im::m1;
Thread t = new Thread(r);
t.start();
}
}
// Program using Constructor Reference
class Doctor {
public Doctor() {
System.out.println("Doctor constructor....");
}
}
public class Test {
public static void main(String[] args) {
Supplier<Doctor> s = Doctor::new;
Doctor doctor = s.get();
System.out.println(doctor.hashCode());
}
}
Q: WAJP to print numbers from 1 to 5 using Thread with the help of Runnable interface.
// Approach-1
public class ThreadDemo1 implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
public static void main(String[] args) {
ThreadDemo1 td = new ThreadDemo1();
Thread t = new Thread(td);
t.start();
}
}
// Approach-2
public class ThreadDemo2 {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
};
Thread t = new Thread(r);
t.start();
}
}
// Approach-3
public class ThreadDemo3 {
public static void main(String[] args) {
Runnable r = () -> {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
};
Thread t = new Thread(r);
t.start();
}
}
Q: WAJP to store numbers in ArrayList and sort numbers in descending order.
// Approach-1 (without Lambda)
package in.ashokit.java8;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class NumberComparator implements Comparator<Integer> {
@Override
public int compare(Integer i, Integer j) {
if (i > j) {
return -1;
} else if (i < j) {
return 1;
}
return 0;
}
}
public class NumbersSort1 {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<>();
al.add(5);
al.add(3);
al.add(4);
al.add(1);
al.add(2);
System.out.println("Before Sort :: " + al);
Collections.sort(al, new NumberComparator());
System.out.println("After Sort :: " + al);
}
}
// Approach-2 (with Lambda)
package in.ashokit.java8;
import java.util.ArrayList;
import java.util.Collections;
public class NumbersSort1 {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<>();
al.add(5);
al.add(3);
al.add(4);
al.add(1);
al.add(2);
System.out.println("Before Sort :: " + al);
Collections.sort(al, (i, j) -> (i > j) ? -1 : 1);
System.out.println("After Sort :: " + al);
}
}
// Java Program using forEach(Consumer c)
package in.ashokit.java8;
import java.util.ArrayList;
public class NumbersSort1 {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<>();
al.add(5);
al.add(3);
al.add(4);
al.add(1);
al.add(2);
al.forEach(i -> System.out.println(i));
}
}
java.util.StringJoiner class introduced in java 1.8v
It is used to join more than one String with specified delimiter
We can concat prefix and suffix while joining strings using StringJoiner
StringJoiner sj = new StringJoiner (CharSequence delim); StringJoiner sj = new StringJoiner (CharSequence delim, CharSequence prefix, CharSequence suffix);
// Java Program on String Joiner
package in.ashokit.java8;
import java.util.StringJoiner;
public class StringJoinerDemo {
public static void main(String[] args) {
StringJoiner sj1 = new StringJoiner("-");
sj1.add("ashok");
sj1.add("it");
sj1.add("java");
System.out.println(sj1); // ashok-it-java
StringJoiner sj2 = new StringJoiner("-", "(", ")");
sj2.add("ashok");
sj2.add("it");
sj2.add("java");
System.out.println(sj2); // (ashok-it-java)
}
}
java.util.Optional class introduced in java 1.8v
Optional class is used to avoid NullPointerExceptions in the program
Q) What is NullPointerException (NPE) ?
Ans: When we perform some operation on null value then we will get NullPointerException
String s = null; s.length ( ) ; // NPE
To avoid NullPointerExceptions we have to implement null check before performing operation on the Object like below.
String s = null;
if( s! = null ) {
System.out.println(s.length ( ));
}
Note: In project there is no guarantee that every programmer will implement null checks. If any body forgot to implement null check then program will run into NullPointerException.
// How to avoid NPE using Optional class
package in.ashokit.java8;
import java.util.Optional;
import java.util.Scanner;
class User {
// Without Optional object
public String getUsernameById(Integer id) {
if (id == 100) {
return "Raju";
} else if (id == 101) {
return "Rani";
} else if (id == 102) {
return "John";
} else {
return null;
}
}
// with Optional Object
public Optional<String> getUsername(Integer id) {
String name = null;
if (id == 100) {
name = "Raju";
} else if (id == 101) {
name = "Rani";
} else if (id == 102) {
name = "John";
}
return Optional.ofNullable(name);
}
}
public class MsgService {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter User ID");
int userId = s.nextInt();
User u = new User();
/*String userName = u.getUsernameById(userId);
String msg = userName.toUpperCase() + ", Hello";
System.out.println(msg);*/
Optional<String> username = u.getUsername(userId);
if(username.isPresent()) {
String name = username.get();
System.out.println(name.toUpperCase()+", Hello");
}else {
System.out.println("No Data Found");
}
}
}
In java we have below 2 classes to represent Date
1) java.util.Date 2) java.sql.Date
Note: When we are performing database operations then we will use java.sql.Date class.
For normal Date related operations we will use java.util.Date class
Date d = new Date ( ); System.out.prinln(d);
Note: When we create Object for Date class, it will represent both date and time.
If we want to get only date or only time then we need to format it using SimpleDateFormat class.
SimpleDateFormat is a predefined class in java.text pacakage
This class provided methods to perform Date conversions
Date to String conversion ===> String format (Date d) String to Date conversion ===> Date parse(String str)
// Date Conversions Example
package in.ashokit.java8;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateDemo {
public static void main(String[] args) throws Exception {
Date date = new Date();
System.out.println(date);
// Converting Date to String
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
String format1 = sdf1.format(date);
System.out.println(format1);
SimpleDateFormat sdf2 = new SimpleDateFormat("MM/dd/yyyy");
String format2 = sdf2.format(date);
System.out.println(format2);
// Convert String to Date
SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");
Date parsedDate = sdf3.parse("2022-12-20");
System.out.println(parsedDate);
}
}
To overcome the problems of java.util.Date class java 1.8 introduced Date API changes
In java 1.8 version, new classes got introduced to deal with Date & Time functionalities
1) java.time.LocalDate (it will deal with only date) 2) java.time.LocalTime (it will deal with only time) 3) java.time.LocalDateTime (it will deal with both date & time)
// Java 1.8 Date API Example
package in.ashokit.java8;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
public class NewDateDemo {
public static void main(String[] args) {
LocalDate of = LocalDate.of(2021, 1, 20);
System.out.println(of);
LocalDate date = LocalDate.now();
System.out.println(date);
date = date.plusDays(3);
System.out.println(date);
date = date.plusMonths(1);
System.out.println(date);
date = date.plusYears(2);
System.out.println(date);
boolean leapYear = LocalDate.parse("2020-12-22").isLeapYear();
System.out.println("Leap Year :: " + leapYear);
boolean before = LocalDate.parse("2021-12-22").isBefore(LocalDate.parse("2022-12-22"));
System.out.println("Before Date : " + before);
LocalTime time = LocalTime.now();
System.out.println(time);
time = time.plusHours(2);
System.out.println(time);
LocalDateTime datetime = LocalDateTime.now();
System.out.println(datetime);
Period period = Period.between(LocalDate.parse("1991-05-20"), LocalDate.now());
System.out.println(period);
Duration duration = Duration.between(LocalTime.parse("18:00"), LocalTime.now());
System.out.println(duration);
}
}
Few Important Points About Streams
1) Stream is not a data structure. Stream means bunch of operations applied on source data. Source can be collection or array. 2) Stream will not change original data structure of the source (It will just process the data given by the source.)
In Java we can create Stream in 2 ways
1) Stream.of (e1, e2, e3, e4.....) 2) stream ( )
// Java Program to Create Stream
package in.ashokit.streams;
import java.util.ArrayList;
import java.util.stream.Stream;
public class FirstDemo {
public static void main(String[] args) {
// Approach-1
Stream<Integer> stream1 = Stream.of(1, 2, 3, 4, 5);
ArrayList<String> names = new ArrayList<>();
names.add("John");
names.add("Robert");
names.add("Orlen");
// Approach-2
Stream<String> stream2 = names.stream();
}
}
Stream API provided several methods to perform Operations on the data
We can divide Stream api methods into 2 types
1) Intermediate Operational Methods 2) Terminal Operational Methods
Intermediate Operational methods will perform operations on the stream and returns a new Stream
Ex: filter ( ) , map ( ) etc....
Terminal Operational methods will take input and will provide result as output.
Ex: count ( )
Filtering means getting required data from original data
Ex: get only even numbers from given numbers Ex: get emps whose salary is >= 1,00,000 Ex: get Mobiles whose price is <= 15,000
To apply filter on the data, Stream api provided filter ( ) method
Ex: Stream filter (Predicate p)
// Example-1
package in.ashokit.streams;
import java.util.Arrays;
import java.util.List;
public class FirstDemo {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(66, 32, 45, 12, 20);
/*for (Integer i : list) {
if (i > 20) {
System.out.println(i);
}
}*/
/*Stream<Integer> stream = list.stream();
Stream<Integer> filteredStrem = stream.filter(i -> i > 20);
filteredStrem.forEach(i -> System.out.println(i));*/
list.stream().filter(i -> i > 20).forEach(i -> System.out.println(i));
}
}
// Example-2
package in.ashokit.streams;
import java.util.Arrays;
import java.util.List;
public class FirstDemo {
public static void main(String[] args) {
List<String> names = Arrays.asList("John", "Anushka", "Anupama", "Smith", "Ashok");
names.stream().filter(i -> i.startsWith("A")).forEach(i -> System.out.println(i));
}
}
// Example-3
package in.ashokit.streams;
import java.util.stream.Stream;
class User {
String name;
int age;
User(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "User [name=" + name + ", age=" + age + "]";
}
}
public class FirstDemo {
public static void main(String[] args) {
User u1 = new User("Anushka", 25);
User u2 = new User("Smith", 30);
User u3 = new User("Raju", 15);
User u4 = new User("Rani", 10);
User u5 = new User("Charles", 35);
User u6 = new User("Ashok", 30);
Stream<User> stream = Stream.of(u1, u2, u3, u4, u5, u6);
stream.filter(u -> u.age >= 18)
.filter(u -> u.name.startsWith("A"))
.forEach(u -> System.out.println(u));
}
}
Mapping operations are belongs to intermediate operations in the Stream api
Mapping operations are used to transform the stream elements and return transformed elements as new Stream
Ex : Stream map (Function function);
// Example-1
public class FirstDemo {
public static void main(String[] args) {
List<String> names = Arrays.asList("india","usa","uk", "japan");
/*for(String name : names) {
System.out.println(name.toUpperCase());
}*/
names.stream().map(name -> name.toUpperCase()).forEach(n -> System.out.println(n));
names.stream().mapToInt(name -> name.length()).forEach(i -> System.out.println(i));
}
}
// Print name with its length which are starting with 'A' using Stream API
public class FirstDemo {
public static void main(String[] args) {
List<String> names = Arrays.asList("Ashok", "Anil", "Raju", "Rani", "John", "Akash", "Charles");
names.stream()
.filter(name -> name.startsWith("A"))
.map(name -> name + "-" +name.length())
.forEach(name -> System.out.println(name));
}
}
// Print Emp Name with Emp age whose salary is >= 50,000 using Stream API
class Employee {
String name;
int age;
double salary;
public Employee(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
}
public class FirstDemo {
public static void main(String[] args) {
Employee e1 = new Employee("John", 35, 55000.00);
Employee e2 = new Employee("David", 25, 45000.00);
Employee e3 = new Employee("Buttler", 35, 35000.00);
Employee e4 = new Employee("Steve", 45, 65000.00);
Stream<Employee> stream = Stream.of(e1, e2, e3, e4);
/*stream.filter(e -> e.salary >= 50000.00)
.map(e -> e.name+" - " +e.age)
.forEach(e -> System.out.println(e));*/
stream.filter(e -> e.salary >= 50000.00)
.forEach(e -> System.out.println(e.name + "-" + e.age));
}
}
// Java Program using flatMap(Function f)
public class FirstDemo {
public static void main(String[] args) {
List<String> javacourses = Arrays.asList("core java", "adv java", "springboot");
List<String> uicourses = Arrays.asList("html", "css", "bs", "js");
List<List<String>> courses = Arrays.asList(javacourses, uicourses);
//courses.stream().forEach(c -> System.out.println(c));
Stream<String> fms = courses.stream().flatMap(s -> s.stream());
fms.forEach(c -> System.out.println(c));
}
}
1) distinct ( ) => To get unique elements from the Stream 2) limit ( long maxSize ) => Get elements from the stream based on given size 3) skip (long n) => It is used to skip given number of elements from starting position of the stream
Note: All the above 3 methods are comes under Intermediate Operational Methods. They will perform operation and returns new Stream.
// How to perform slicing operations on streams
package in.ashokit.streams;
import java.util.Arrays;
import java.util.List;
public class FirstDemo {
public static void main(String[] args) {
List<String> javacourses = Arrays.asList("corejava", "advjava", "springboot", "restapi", "microservices");
javacourses.stream().limit(3).forEach(c -> System.out.println(c));
javacourses.stream().skip(3).forEach(c -> System.out.println(c));
List<String> names = Arrays.asList("raja", "rani", "raja", "rani", "guru");
names.stream().distinct().forEach(name -> System.out.println(name));
}
}
1) boolean anyMatch (Predicate p ) 2) boolean allMatch (Predicate p ) 3) boolean noneMatch (Predicate p )
Note: The above 3 methods are belongs to Terminal Operations because they will do operation and they will return result directly (they won't return stream)
// How to perform matching operations on streams
package in.ashokit.streams;
import java.util.Arrays;
import java.util.List;
class Person {
String name;
String country;
public Person(String name, String country) {
this.name = name;
this.country = country;
}
}
public class FirstDemo {
public static void main(String[] args) {
Person p1 = new Person("John", "USA");
Person p2 = new Person("Steve", "JAPAN");
Person p3 = new Person("Ashok", "INDIA");
Person p4 = new Person("Ching", "CHINA");
List<Person> persons = Arrays.asList(p1, p2, p3, p4);
boolean status1 = persons.stream().anyMatch(p -> p.country.equals("INDIA"));
System.out.println("Any Indian Available ? :: " + status1);
boolean status2 = persons.stream().anyMatch(p -> p.country.equals("CANADA"));
System.out.println("Any Canadian Available ? :: " + status2);
boolean status3 = persons.stream().allMatch(p -> p.country.equals("INDIA"));
System.out.println("All Persons from India ? :: " + status3);
boolean status4 = persons.stream().noneMatch(p -> p.country.equals("MEXICO"));
System.out.println("No Persons from Mexico ? :: " + status4);
}
}
// Example-1
package in.ashokit.streams;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
class Person {
String name;
String country;
public Person(String name, String country) {
this.name = name;
this.country = country;
}
@Override
public String toString() {
return "Person [name=" + name + ", country=" + country + "]";
}
}
public class FirstDemo {
public static void main(String[] args) {
Person p1 = new Person("John", "USA");
Person p2 = new Person("Steve", "JAPAN");
Person p3 = new Person("Ashok", "INDIA");
Person p4 = new Person("Ching", "CHINA");
Person p5 = new Person("Kumar", "INDIA");
List<Person> persons = Arrays.asList(p1, p2, p3, p4, p5);
List<Person> indians = persons.stream()
.filter(p -> p.country.equals("INDIA"))
.collect(Collectors.toList());
indians.forEach(i -> System.out.println(i));
}
}
// Example-2
package in.ashokit.streams;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
class Person {
String name;
String country;
public Person(String name, String country) {
this.name = name;
this.country = country;
}
@Override
public String toString() {
return "Person [name=" + name + ", country=" + country + "]";
}
}
public class FirstDemo {
public static void main(String[] args) {
Person p1 = new Person("John", "USA");
Person p2 = new Person("Steve", "JAPAN");
Person p3 = new Person("Ashok", "INDIA");
Person p4 = new Person("Ching", "CHINA");
Person p5 = new Person("Kumar", "INDIA");
List<Person> persons = Arrays.asList(p1, p2, p3, p4, p5);
// collect names of persons who are belongs to india and store into names collection
List<String> names = persons.stream()
.filter(p -> p.country.equals("INDIA"))
.map(p -> p.name)
.collect(Collectors.toList());
System.out.println(names);
}
}
Set - 1 : Intermediate Operations (will return Stream)
Filters ----> filter ( ) Mappings ----> map ( ) & flatMap ( ) Slicing ----> distinct ( ) & limit () & skip ( )
Set - 2 : Terminal Operations (will return result)
Finding ---> findFirst ( ) & findAny ( ) Matching ---> anyMatch ( ) & allMatch ( ) & noneMatch ( ) Collecting ---> collect ( )
// Write a java program to get MAX, MIN and AVG salary from given employees data using Stream API.
package in.ashokit.streams;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
class Employee {
int id;
String name;
double salary;
public Employee(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
}
public class FirstDemo {
public static void main(String[] args) {
Employee e1 = new Employee(1, "Robert", 26500.00);
Employee e2 = new Employee(2, "Abraham", 46500.00);
Employee e3 = new Employee(3, "Ching", 36500.00);
Employee e4 = new Employee(4, "David", 16500.00);
Employee e5 = new Employee(5, "Cathy", 25500.00);
List<Employee> list = Arrays.asList(e1, e2, e3, e4, e5);
Optional<Employee> max = list.stream()
.collect(Collectors.maxBy(Comparator.comparing(e -> e.salary)));
System.out.println("Max Salary :: " + max.get().salary);
Optional<Employee> min = list.stream()
.collect(Collectors.minBy(Comparator.comparing(e -> e.salary)));
System.out.println("Min Salary :: " + min.get().salary);
Double avgSalary = list.stream().collect(Collectors.averagingDouble(e -> e.salary));
System.out.println(avgSalary);
}
}
package in.ashokit.streams;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class Employee {
int id;
String name;
double salary;
String country;
public Employee(int id, String name, double salary, String country) {
this.id = id;
this.name = name;
this.salary = salary;
this.country = country;
}
}
public class FirstDemo {
public static void main(String[] args) {
Employee e1 = new Employee(1, "Robert", 26500.00, "USA");
Employee e2 = new Employee(2, "Abraham", 46500.00, "INDIA");
Employee e3 = new Employee(3, "Ching", 36500.00, "CHINA");
Employee e4 = new Employee(4, "David", 16500.00, "INDIA");
Employee e5 = new Employee(5, "Cathy", 25500.00, "USA") ;
List<Employee> list = Arrays.asList(e1, e2, e3, e4, e5);
Map<String, List<Employee>> data = list.stream()
.collect(Collectors.groupingBy(e -> e.country));
System.out.println(data);
}
}
// Java Program on Parallel Streams
package in.ashokit.streams;
import java.util.stream.Stream;
public class ParallelDemo {
public static void main(String[] args) {
System.out.println("====== Serial Stream ========");
Stream<Integer> ss = Stream.of(1, 2, 3, 4);
ss.forEach(n -> System.out.println(n + " :: " + Thread.currentThread()));
System.out.println("====== Parallel Strem =======");
Stream<Integer> ps = Stream.of(1, 2, 3, 4);
ps.parallel().forEach(n -> System.out.println(n + " :: " + Thread.currentThread()));
}
}
// Java Program on Spliterator
package in.ashokit.streams;
import java.util.Arrays;
import java.util.List;
import java.util.Spliterator;
public class ParallelDemo {
public static void main(String[] args) {
List<String> names = Arrays.asList("sachin", "sehwag", "dhoni");
Spliterator<String> spliterator = names.stream().spliterator();
spliterator.forEachRemaining(n -> System.out.println(n));
}
}
// Java Program on Stream Reduce
package demo;
import java.util.Arrays;
public class Sum {
public static void main(String[] args) {
int[] nums = { 1, 2, 3, 4, 5 };
/*int sum = 0;
for(int i : nums) {
sum = sum + i;
}
System.out.println(sum);*/
int reduce = Arrays.stream(nums).reduce(0, (a,b) -> a+b);
System.out.println(reduce);
}
}
Nashorn is a Java Script Engine which is used to execute Java Script code using JVM
Create a javascript file like below (filename : one.js)
--------------------- one.js --------------------- var hello = function(){ print("Welcome to JavaScript"); } hello(); ---------------------------------------------------
Open command prompt and execute below command
syntax : jjs one.js
We can execute above Java Script file using Java program like below
// How to execute js code using java program
import java.io.*;
import javax.script.*;
public class Demo {
public static void main(String... args) throws Exception {
ScriptEngine se = new ScriptEngineManager().getEngineByName("Nashorn");
se.eval(new FileReader("one.js"));
}
}
To read file data we can use FileReader & BufferedReader classes
FileReader ----> It will read the data character by character (slow performance) BufferedReader ---> It will read the data line by line Files.lines(Path path) ---> It will read all lines at a time and returns as a Stream
// Task : Write a java program to read a file data and print it on the console
package demo;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class ReadFileData {
public static void main(String[] args) throws Exception {
/*FileReader fr = new FileReader(new File("info.txt"));
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
br.close();*/
String filename = "info.txt";
try (Stream<String> stream = Files.lines(Paths.get(filename)))
stream.forEach(line -> System.out.println(line));
} catch(Exception e) {
e.printStackTrace();
}
}
}
// Java Program using Base64
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;
class Test {
public static void main(String[] args) {
String pwd = "Ashokit@123";
Encoder encoder = Base64.getEncoder();
byte[] encode = encoder.encode(pwd.getBytes());
String encodedPwd = new String(encode);
System.out.println(encodedPwd);
Decoder decoder = Base64.getDecoder();
byte[] decode = decoder.decode(encodedPwd);
String decodedPwd = new String(decode);
System.out.println(decodedPwd);
}
}
package stream.api;
import java.util.ArrayList;
import java.util.List;
class Employee {
int id;
String name;
int age;
String gender;
String department;
int yearOfJoining;
double salary;
public Employee(int id, String name, int age, String gender, String department, int yearOfJoining, double salary) {
super();
this.id = id;
this.name = name;
this.age = age;
this.gender = gender;
this.department = department;
this.yearOfJoining = yearOfJoining;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public int getYearOfJoining() {
return yearOfJoining;
}
public void setYearOfJoining(int yearOfJoining) {
this.yearOfJoining = yearOfJoining;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", age=" + age + ", gender=" + gender + ", department="
+ department + ", yearOfJoining=" + yearOfJoining + ", salary=" + salary + "]";
}
}
class EmployeeStreamAPI {
public static void main(String[] args) {
List<Employee> emplist = new ArrayList<Employee>();
emplist.add(new Employee(1, "Jhansi", 32, "Female", "HR", 2011, 25000.0));
emplist.add(new Employee(2, "Smith", 25, "Male", "Sales", 2015, 13500.0));
emplist.add(new Employee(3, "David", 29, "Male", "Infrastructure", 2012, 18000.0));
emplist.add(new Employee(4, "Orlen", 28, "Male", "Development", 2014, 32500.0));
emplist.add(new Employee(5, "Charles", 27, "Male", "HR", 2013, 22700.0));
emplist.add(new Employee(6, "Cathy", 43, "Male", "Security", 2016, 10500.0));
emplist.add(new Employee(7, "Ramesh", 35, "Male", "Finance", 2010, 27000.0));
emplist.add(new Employee(8, "Suresh", 31, "Male", "Development", 2015, 34500.0));
emplist.add(new Employee(9, "Gita", 24, "Female", "Sales", 2016, 11500.0));
emplist.add(new Employee(10, "Mahesh", 38, "Male", "Security", 2015, 11000.5));
emplist.add(new Employee(11, "Gouri", 27, "Female", "Infrastructure", 2014, 15700.0));
emplist.add(new Employee(12, "Nithin", 25, "Male", "Development", 2016, 28200.0));
emplist.add(new Employee(13, "Swathi", 27, "Female", "Finance", 2013, 21300.0));
emplist.add(new Employee(14, "Buttler", 24, "Male", "Sales", 2017, 10700.5));
emplist.add(new Employee(15, "Ashok", 23, "Male", "Infrastructure", 2018, 12700.0));
emplist.add(new Employee(16, "Sanvi", 26, "Female", "Development", 2015, 28900.0));
}
}
Q1. How many male and female employees are there in the organization ?
Map<String, Long> map1 = emps.stream().collect(Collectors.groupingBy(Employee::getGender, Collectors.counting()));
System.out.println(map1);
Q2. Print the name of all departments in the organization ?
emps.stream()
.map(Employee::getDepartment)
.distinct()
.forEach(name -> System.out.println(name));
Q3. What is the average age of male and female employees ?
Map<String, Double> map = emps.stream()
.collect(Collectors.groupingBy(Employee::getGender, Collectors.averagingInt(Employee::getAge)));
System.out.println(map);
Q4. Get the details of highest paid employee in the organization ?
Optional<Employee> optional = emps.stream()
.collect(Collectors.maxBy(Comparator.comparingDouble(Employee::getSalary)));
if(optional.isPresent()) {
Employee employee = optional.get();
System.out.println(employee);
}
Q5. Get the names of all employees who have joined after 2015 ?
emps.stream()
.filter(e -> e.yearOfJoining > 2015)
.map(e -> e.name)
.forEach(name -> System.out.println(name));
Q6. Count the number of employees in each department ?
Map<String, Long> map = emps.stream()
.collect(Collectors.groupingBy(Employee::getDepartment, Collectors.counting()));
System.out.println(map);
Q7. What is the average salary of each department ?
Map<String, Double> map = emps.stream()
.collect(Collectors.groupingBy(Employee::getDepartment, Collectors.averagingDouble(Employee::getSalary)));
System.out.println(map);
Q8. Get the details of youngest male employee in the Development department ?
Optional<Employee> optional = emps.stream()
.filter(e -> e.getGender().equals("Male") && e.getDepartment().equals("Development"))
.min(Comparator.comparing(Employee::getAge));
if(optional.isPresent()) {
System.out.println(optional.get());
}
Q9. Who has the most working experience in the organization ?
Optional<Employee> optional = emps.stream()
.collect(Collectors.minBy(Comparator.comparing(Employee::getYearOfJoining)));
if(optional.isPresent()) {
System.out.println(optional.get());
}
Q10. How many male and female employees are there in the Sales team ?
Map<String, Long> map = emps.stream()
.filter(e -> e.getDepartment().equals("Sales"))
.collect(Collectors.groupingBy(Employee::getGender, Collectors.counting()));
System.out.println(map);
Q11. What is the average salary of male and female employees ?
Map<String, Double> map = emplist.stream()
.collect(Collectors.groupingBy(Employee::getGender, Collectors.averagingDouble(Employee::getSalary)));
System.out.println(map);
Q12. List down the names of all employees in each department ?
emplist.stream().collect(Collectors.groupingBy(Employee::getDepartment))
.entrySet().forEach(en -> {
System.out.println("===== "+en.getKey()+" =====");
en.getValue().forEach(n -> System.out.println(n.getName()));
System.out.println();
});
Q13. What is the average salary and total salary of the whole organization ?
Double avg = emplist.stream().collect(Collectors.averagingDouble(Employee::getSalary));
System.out.println("Avg Sal : "+avg);
Double sos = emplist.stream().map(e -> e.getSalary()).reduce(0.0, (a,b) -> a+b);
System.out.println("Sum of Sal : "+sos);
Q14. Separate the employees who are younger or equal to 25 years from those employees who are older than 25 years ?
// Interpretation - 1
emplist.stream().filter(e -> e.getAge() <= 25).forEach(e -> System.out.println(e.getName()+" : "+e.getAge()));
// Interpretation - 2
emplist.stream().collect(Collectors.groupingBy(e -> e.getAge() <= 25))
.entrySet().forEach(en -> {
if(en.getKey()) {
System.out.println("Employees with Age <= 25");
} else {
System.out.println("Employees with Age > 25");
}
en.getValue().forEach(e -> System.out.println(e.getName()+" : "+e.getAge()));
System.out.println();
});
Q15. Who is the oldest employee in the organization?
Optional<Employee> max = emplist.stream().max(Comparator.comparingInt(Employee::getAge));
System.out.println(max.get());