Chapter 1

What is Full Stack

Frontend Technologies

	HTML & CSS
	Java script
	Bootstrap
	Angular
	React

Backend Technologies

	Java
	Python
	PHP
	.Net
	Node JS

Servers

	Tomcat
	JBoss
	Glassfis
	Oracle Weblogic
	IBM WebSphere
	IIS

Databases

	Oracle
	MySQL
	SQL Server
	Postgres
	Mongo DB
	Casandra
	Hbase
	Hive

Tools

	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)

Cloud

	Amazon  ---> AWS
	Microsoft  ---> Azure
	Google -----> GCP
	Oracle Cloud
	IBM Cloud
	VM Ware Cloud
	Alibaba CLoud etc.....

Roles & Responsibilities of Fullstack Developer

	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

What is Java

Java is divided into 3 parts

	1) J2SE
	2) J2EE
	3) J2ME

J2SE / JSE ---> JAVA STANDARD EDITION

J2EE / JEE ---> JAVA ENTERPRISE EDITION

J2ME / JME ---> JAVA MICRO / MOBILE EDITION

What we can do using Java

	1) Stand-alone applications
	2) Web applications
	3) Mobile Applications

Java Features

Simple

Platform Independent

Robust (Strong)

OOPS (Object Oriented Programming System)

Secure

Distributed

Portable

Dynamic

Java Slogan : WORA (Write Once Run Anywhere)

Environment Setup

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

Java Programs Development

Java Program Structure

	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");
		}
	}

Translators

JVM

JVM Architecture

  1. Classloader subsystem : It will load .class file into JVM
  2. Method Area : Class code will be stored here
  3. Heap area : Objects will be stored into heap area
  4. Java Stack : Method execution information will be stored here
  5. PC Register : It will maintain next line information to execute
  6. Native Stack : It will maintain non-java code execution information
  7. Execution Engine ( Interpreter + JIT ) : It is responsible to execute the program and provide output/result
  8. Native Interface : It will load native libraries into jvm
  9. Native Libraries : Non-java libraries which are required for native code execution

JVM Architecture

Data Types

Integral Data Types

	// Intergral Data Type
	age = 30;
	phno = 66868686868;
	studentscnt = 40;
	balance = - 3000;

Decimal Data Types

	// Decimal Data Types
	petrol price  = 110.567979;
	stockPrice = 334.3279797979797979;
	percentage = 9.8;
	weight = 55.6;
	height = 5.6;
	length = 10.2;

Character Data Type

	// Character Data Type
	gender = 'm';
	rank = '1';

Boolean Data Type

	// Boolean Data Type
	isPass = true;
	isFail = false;
	isMarried = true;
	isOdd = true;
	isEven = false;

Variables

	// ============ 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);
		}
	}

Identifiers

	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

Java Naming Conventions

Naming Convention for Classes

	// Naming Conventions for Class
	class Hello  {
	}

	class HelloWorld {
	}

	class UserManagementService{
	}

	class WelcomeRestController {
	}

Naming Convention for Variables

	// Naming Convention for Variables
	int age ;

	int  userAge;

	long creditCardNumber ;

Naming Convention for Methods

	// Naming Convention for Methods
	main ( )  {
	}

	save ( ) {
	}

	saveUser( ) {
	}

	getWelcomeMsg ( ) {
	}

Naming Convention for Constants

	// Naming Conventions for Constants
	final int MIN_AGE = 21;

	final int MAX_AGE = 60 ;

	int PI = 3.14;

Naming Convention for Packages

	// Naming Conventions for Packages
	java.lang
	java.io
	java.util
	in.ashokit
	com.oracle
	com.ibm

Chapter 2

Operators

	int a  = 10 ;
	int b = 20 ;
	int c = a + b;

Arithmetic Operators

	// 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 );
		}
	}

Relational Operators

    >, < , >= , <=, !=, ==

Logical Operators

	AND  ---->  &&
	OR -----> ||
	NOT -----> !

Assignment Operator

	int a  = 10 ;

new operator

	ClassName refVar = new ClassName( );

Note: Creating object means allocating memory in heap area

Dot (.) Operator

	System.out.println ( );
	java.lang.String;
	java.util.ArrayList;

Ternary Operator / Conditional Operator

	// Conditional Operator Syntax
	( condition ) ? expression-1 : expression-2

instanceof Operator

	String str = "ashokit";
	if (str instanceof String ) {
		//logic
	}

Control Statements

Conditional Statements

Simple if

	// 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

	// 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

swtich case

	// 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'

Looping Statements

while loop

	// 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

	// 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

	// 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);
			}
		}
	}

Nested Loops

	 // 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();
			}
		}
	}

Branching Statements

break

continue

return

	// 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);
			}
		}
	}

Logical Programs

	// 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();
			}
		}
	}

Chapter 3

	// 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)

Arrays

	// 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] + " ");
				}
			}
		}
	}

Types of Arrays

	// 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);
				}
			}
		}
	}

Strings

	String name = "abc" ;
	// approach - 1  (string literal)
	String  name = "ashokit";

	// approach -2 (using new operator)
	String str = new String ("ashokit");

String Constant Pool

	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 class Methods

charAt ( )

	String s1 = "ashokit";
	System.out.println(s1.charAt(0));

length ( )

	String s1 = "ashokit";
	System.out.println(s1.length( ) );

concat ( )

	String s1 = "ashok";
	String s2 = "it";
	String s3 = s1.concat(s2);
	// String s4 = s1 + s2 ;
	System.out.println(s3);

equals ( )

	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.

replace ( )

	String s1 = "hyderabad";
	String s2 = s1.replace("bad", "good");
	System.out.println(s2);

toUpperCase ( )

	s1.toUpperCase( );

toLowerCase ( )

	s1.toLowerCase( );

indexOf ( )

	System.out.println(s1.indexOf('a'));

lastIndexOf ( )

	System.out.println(s1.lastIndexOf('a'));

Note: If given char is not available then it will return '-1'

substring ( )

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

split ( )

	String s2  = "hi@hello@how are@you";
	String [ ] arr = s2.split ("@");
	System.out.println(Arrays.toString(arr));

valueOf ( )

	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.

startsWith ( )

	String str = "ashokit";

	str.startsWith("a");  =====> true

	str.startsWith("z");  =====> false

endsWith ( )

	String str = "ashokit";

	str.endsWith("it");   ===> true

	str.endsWith("good") ===> false

trim ( )

	String str = "     hello    ";

	str.trim ( );

intern ( )

	String s1 = "hi";

	String s2 = s1.intern ( );

	s1 == s2 ===> true

toString ( )

toCharArray ( )

	String s1 = "java";
	char arr[ ]  = s1.toCharArray ( );

StringBuffer

	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

	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

Command Line Arguments

	// 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);
		}
	}

Chapter 4

IDE Notes

IDE

Advantages with IDE

Working with IDE

	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

Chapter 5

OOPS Principles

	1) Encapsulation
	2) Abstraction
	3) Polymorphism
	4) Inheritance

Encapsulation

	class  Demo {
		//variables
		// methods
	}

Abstraction

Polymorphism

Inheritance

Class

	class ClassName {
		// variables
		// methods
	}

Object

	ClassName   refVariable = new ClassName ( );

	User  u1  = new User ( );

	User u2 = new User ( ) ;

What is Hash Code

	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());
		}
	}

Variables

	int a  = 10 ;

	User u1 = new User ( );

	Student s1 = new Student ( );

Instance 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();
		}
	}

Static Variables

	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 ?

Local Variables

	class Demo {
		public static void main(String[ ] args){
			int a = 20;
			int b = 20;
			System.out.println(a);
			System.out.prinltn(b);
		}
	}

Methods

	returnType methodName (param1, param2, para3..... paramN) {
		//logic
		return value;
	}

What is Method Declaration ?

	returntype  methodname (list of parameters);

What is returntype ?

What is method name ?

What are method parameters ?

Method body / Method Definition / Method implementation

	returntype methodname(list of parameters) {
		//statements;
		return value;
	}
	return value;
	// 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;
		}
	}

Types of Methods

	// 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;
		}
	}

Working with Methods using Objects

	// 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);
			}
		}
	}

Constructors

	class Demo {
		Demo ( ) {
			// logic
		}
	}
	javap classname
	// 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);
		}
	}

this keyword

	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");
		}
	}

Constructor Overloading

	class Employee {
		Employee(int id){
			// logic
		}

		Employee(double d){
			// logic
		}
	}

Access Specifiers / Modifiers

public

private

protected

default

OOPS

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

Encapsulation

	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);
		}
	}

Inheritance

	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);
		}
	}

Types of Inheritance

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);
		}
	}

Methods Execution Flow w.r.t Inheritance

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.

Polymorphism

Method Overloading

	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)

Method Overriding

	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);
		}
	}

Abstraction

Method Types

	public void m1( ){
		// logic
	}
	public abstract void m2( );

Types of Relations in Java Classes

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 ( );
		}
	}

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 keyword

	public class User extends String { // invalid because String is final class
		// logic
	}
	public final int pi = 3.14;
	pi = 4.32; // invalid

Interfaces

	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
	}
	// 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 Classes

	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

Blocks in java

Instance Block

	// instance block syntax
	{
		// stmts
	}

Static Block

	// static block syntax
	static
	{
		// stmts
	}

Static Control Flow

Instance Control Flow

	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();
		}
	}

java.lang.Object class

public String toString ( )

	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;
		}
	}

int hashCode ( )

	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;
		}
	}

boolean equals (Object obj)

	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
		}
	}

Class getClass ( )

	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);
		}
	}

clone ( )

	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

finalize ( )

Chapter 6

Packages

	// 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);
		}
	}

User Defined 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.

Static Imports

	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();
		}
	}

Exception Handling

What is Exception ?

Exception Hierarchy

Exception Types

Handling Exceptions

try

	// Syntax
	try {
		// stmts
	}

catch

	// 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...");
		}
	}

finally

	// 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

throws

	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

	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");
		}
	}

User Defined Exceptions

	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

Method Stack

	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");
		}
	}

Variable Arguments (Var-Args)

	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

Wrapper Classes

Wrapper Class Hierarchy

Wrapper-Class-Hierarchy

	byte  ----> Byte
	short  ---> Short
	int  --->   Integer
	long  ---> Long
	float   ----> Float
	double   ----> Double
	char   ---> Character
	boolean   ---> Boolean

What is Boxing & Un-Boxing ?

	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

Type Casting

	byte  b = 20 ;
	int i = b ; // widening
	long  num = 100 ;

	int  i = num ;  // compile time error

	int x = ( int ) num ; // narrowing

Working with String type

	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
		}
	}

Type casting w.r.t to Reference Types

	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)
		}
	}

Chapter 7

File Handling

	File  f = new File (String name);
	File f1 = new File (File parent, String child);
	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);
				}
			}
		}
	}

IO Streams

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

PrintWriter

	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();
		}
	}

Serialization & De-Serialization

	// 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==========");
		}
	}

What is SerialVersionUID ?

transient Keyword

	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==========");
		}
	}

Chapter 8

Multi Threading

Use case to go for 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
		}
	}

User Defined Threads

	// 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 ?

What is Thread Schedular

start ( ) vs run ( )

Can we call run ( ) directly without calling start ( ) ?

	// 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();
		}
	}

What is Thread Life Cycle

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.

Thread Life Cycle

	// 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
	}

Callable Interface

What is the difference between Runnable & Callable interfaces

	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

ExecutorService

	// 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();
		}
	}

Daemon Thread

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();
		}
	}

Synchronization

	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
		}
	}

How to achieve synchronization

	// 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

	// 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

	// 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();
		}
	}

join ( )

	// 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();
		}
	}

yield ( )

	// 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();
			}
		}
	}

Inter Thread Communication

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();
		}
	}

Chapter 9

Reflection API

	// 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

Garbage Collection

	// 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...");
		}
	}

How to invoke GC in java?

How GC works internally in JVM ?

Chapter 10

Generics

	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();
		}
	}

Generics with wild Cards

	Demo< ? extends Number >

Enums

	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);
			}
		}
	}

Inner Classes

	class  A {
		class B {
			// logic
		}
	}
	class A - is called as outer class
	class B - is called as inner class

Types of Inner classes

  1. Non static inner classes

    	1.1  Regular Inner classes
    	1.2  Method local inner class
    	1.3  Anonymous inner class
    
  2. 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...");
			}
		}
	}

Chapter 11

Class Loaders

Class Loaders Hierarchy

	1) Bootstrap Class Loader
	2) Extension Class Loader
	3) Application Class Loader

Class Loaders hierarchy

Chapter 12

Approach-1 : Primitive Data Type

Approach-2 : Arrays

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

Approach-3 : Object Array

	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

Collections

Collection Framework Hierarchy

	1) Iterable (I)
	2) Collection (I)
	3) List (I)
	4) Set (I)
	5) Queue (I)
	6) Map (I)

Collection Framework Hierarchy

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

Collection Interface

List Interface

	List l = new List ( );   // invalid
	List l = new ArrayList ( ) ; // valid
	List l = new LinkedList ( ) ;  // valid

ArrayList

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

	// 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

	// 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());
			}
		}
	}

Stack

Set Interface

HashSet

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());
			}
		}
	}

LinkedHasSet

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

TreeSet

	// 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 Interface

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());
			}
		}
	}

HashMap

LinkedHashMap

TreeMap

Queue Interface

	// 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);
		}
	}

Hashtable

Properties Class In Java

Use Case

	// 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();
		}
	}

Collections Sorting

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

Comparable

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

Comparator

	// 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);
			}
		}
	}

Fail Fast and Fail Safe Collections

	// 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);
		}
	}

What is the difference between HashMap and IdentityHashMap ?

	// 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);
		}
	}

What is the difference between HashMap and WeakHashMap ?

	// 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
		}
	}

Chapter 13

java.util Package

	java.util.Scanner
	java.util.StringTokenizer
	java.util.Date
	java.util.Calendar

Scanner

	// 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();
		}
	}

String Tokenizer

	// 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.util.Date & java.util.Calendar

	// 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);
		}
	}

Chapter 14

Java Versions

	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 Features

Objective of Java 1.8v

Interface Changes

	// 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
		}
	}
	// 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 Expressions

What is Lambda

	// 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 ( );

Functional Interfaces

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

Predicate

	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);
				}
			}
		}
	}

Predicate Joining

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);
				}
			}
		}
	}

Supplier

	// 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());
		}
	}

Consumer

	// 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 ( )

Function

	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);

Method Reference

	// 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();
		}
	}

Constructor Reference

	// 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);
		}
	}

forEach (Consumer c)

	// 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));
		}
	}

StringJoiner

	// 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)
		}
	}

Optional Class

	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");
			}
		}
	}

Date & Time API Changes

java.text.SimpleDateFormat (Legacy)

	// 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);
		}
	}

LocalDate, LocalTime & LocalDateTime Class

	// 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);
		}
	}

Stream API

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

Stream Creation

	// 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 Operations

Filtering with Streams

	// 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

	// 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));
		}
	}

What is flatMap(Function f) method ?

	// 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));
		}
	}

Slicing Operations with Stream

	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));
		}
	}

Matching Operations with Stream

	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);
		}
	}

Collectors with Stream

	// 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);
		}
	}

Group By using Stream

	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);
		}
	}

Parallel Streams

	// 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 Spliterator

	// 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));
		}
	}

Stream Reduce

	// 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 Engine

	// 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"));
		}
	}

I/O Streams Changes in Java 8

	// 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 8 Base64 Changes

	// 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);
		}
	}

Chapter 15

Stream API Questions

	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());

Chapter 1

Data Types

Java Naming Conventions

Chapter 2

Operators

Control Statements

Chapter 3

Strings

Chapter 4

Chapter 5

Variables

Methods

Access Specifiers / Modifiers

OOPS

Types of Relations in Java Classes

Blocks in java

java.lang.Object class

Chapter 6

Packages

Exception Handling

Wrapper Classes

Type Casting

Chapter 7

Serialization & De-Serialization

Chapter 8

Chapter 9

Garbage Collection

Chapter 10

Generics

Enums

Inner Classes

Chapter 11

Class Loaders

Chapter 12

Collection Interface

Properties Class In Java

Collections Sorting

Chapter 13

java.util Package

Chapter 14

Lambda Expressions

Functional Interfaces

Date & Time API Changes

Stream API

Chapter 15