0% found this document useful (0 votes)
29 views220 pages

Core Java

The document provides a comprehensive overview of Java, including its importance, history, and various programming language types. It covers Java's architecture, features, installation, and how to write basic programs using Java, along with control statements and user input handling. Additionally, it discusses the evolution of Java and its platforms, emphasizing its role in software development and job opportunities.

Uploaded by

Amit Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views220 pages

Core Java

The document provides a comprehensive overview of Java, including its importance, history, and various programming language types. It covers Java's architecture, features, installation, and how to write basic programs using Java, along with control statements and user input handling. Additionally, it discusses the evolution of Java and its platforms, emphasizing its role in software development and job opportunities.

Uploaded by

Amit Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 220

CORE JAVA

Day-1 (9/7/24)

Why we should learn Java?


1. Job Opportunities/Freelancing
2. Highly Secured and Scalable
3. Rich Features

Car Manf: 1 warehouse 1 showroom: APPLICATION: code


100 warehouse: Scaled Application

What is Java?
 Java is a platform and a programming language
What is Programming Language?

Why do computer understand only 0 and 1?


Day-2 (10/7/24)
Types of Programming Language
1.Low Level Programming Language
->Machine Friendly Not Human friendly
010101010101010101111100000------>COMPUTER
a.Machine Language (0 1)
->The first ever programming language
->1883: ADA Lovelace (Charles Babbage) : First Programmer Lady ( 0 1 )
->Fastest Programming
->Difficult to read write and understand
->No need of any translator ( Machine Friendly)

b.Assembly Language(1949)
->First useful programming language which consist human readable
commands ( MNEMONICS )
->Easier than Machine Language
->Machine Friendly
->Still Complex language

->Assembler is a program which is used to convert Assembly language


into binary language (0 1 )

 FORTAN : Scientific , Math


 ALGOL
 LISP
 BASIC
 Plankalkül (German pronunciation: [ˈplaːnkalkyːl]) is a programming
language designed for engineering purposes by Konrad Zuse between 1942 and
1945. It was the first high-level programming language to be designed for a
computer.
 C LANGUAGE ( FIRST GENERAL PURPOSE PROGRAMMING LANGUAGE ):
1972

2.High Level Programming Language


->High Level Features : software dev
->English like Statement
->A-Z a-z 0-9 @#$%^&*()
->10+20
->Human friendly but not machine friendly
->Hardware interaction is not feasible
->Java python..etc

3.Middle Level Programming Language


->High Level Features: software dev
->English like Statement
->A-Z a-z 0-9 @#$%^&*()
->10+20
->Human friendly as well as machine friendly
->Hardware interaction is feasible
->C and C++
->WIN LINUX drivers
->Embedded C

Day-3 (12/7/24)

Language Translators ( ------------> 0 1 )


1. Compiler
2. Interpreter
3. Assembler (Assembly Language------------>0 1)
How data travel through wires/circuit

 Platform dependent / Independent


 Machine dependent / Independent
 Portability
Day-4 (15/7/24)

 Java is a Programming Language


 Java is also a Software Platform
Java Platforms:
1.J2SE ( Java to Standard Edition ) : CORE JAVA
Java SE (Java Standard Edition)
->Desktop GUI Application
->Fundamental Concepts

2.J2EE (Java to Enterprise Edition) : Advanced Java


Java EE ---> Jakarta EE
->This platform is built on the top of JavaSE
->It provides API for building large scale application
->Servlets , JSP , Ejb ...etc
========================================
3.J2ME( Java to Micro Edition )
->Java ME
->Mobile Phones, Embedded Systems
4.JavaFX
->To create Rich Internet Application with lightweight UI
==================================================

History of Java
Before Java C and C++ was very famous
 Problem: Both are Platform Dependent Programming Languages

Java was created by SUN MICROSYSTEM (IT COMPANY)


Sun Microsystem got on project to create Software for a set of box
Java was accidently created language
They was trying to clean up the C++ => END RESULT: LANGUAGE
Java was created in C++
Project was initiated in 1991
GREEN TEAM --> GREEN PROJECT (This team was lead by James
Gosling) OtherPerson: Mike Sheredon, Patrick Naughton...and many
more
1995 (Time Magazine : Top 10 product)
 1000 Invention that changed the world
 1995: Java
1996 : 23rd Jan : Java 1.0

Java Naming:
 GREENTALK(.gt)--->OAK ( TREE ) (Pre Existing Company)
 Dynamic, Silk , Jolt. Etc
 Java name was chosen by James gosling
 Java name was picked from a name of COFFEE
 Espresso Bean ( Nick Name: Java Coffee )
 Java is the name of an ISLAND in Indonesia (COFFEE PLATNTATION )
 1600’s DUTCH
 JAVA SEA
 ORACLE TAKEOVER SUN

On April 20, 2009, it was announced that Oracle would acquire


Sun for US$7.4 billion.

Day-5 (16/7/24)
 Popularity of Java
 Installation

Popularity of Java
 Before Java: C and C++
 Platform Dependent
 WWW

Java Installation
1.You need to install Java : Complete Development Kit : Java Development Kit
( JDK )
 JDK-8 / Java 8 / JDK 1.8 / Java 1.8
 Download JDK17( 1->17)
 Higher to Lower Compatibility
 JDK does not provide Code Editor
2. Download Integrated Development Environment (IDE)
 Download Eclipse Latest Version
Download JDK17
https://www.oracle.com/java/technologies/javase/jdk17-archive-downloads.html
Download Eclipse
https://www.eclipse.org/downloads/download.php?file=/technology/epp/
downloads/release/2024-06/R/eclipse-jee-2024-06-R-win32-x86_64.zip

Java Installation Directory:

To check installation:
->Open CMD and java -version
Eclipse: just you need to extract
===================================================
First Program
->Without Eclipse: Notepad
->With Eclipse

Day-6 (16/7/24)
First Program
->To Print something
1.NOTEPAD
2.ECLIPSE
.java file => Code Write
 In Java programming language to create a program you must have a
class
 class is just a block of code
 JDK provides compiler , libraries and set of tools
Compiler Location:
C:\Program Files\Java\jdk-17\bin
First Program using Eclipse
1.select workspace / folder
2.change perspective from JavaEE to java

3.create a Java project (file->new->java project)


4.create a class with main method under src folder
Day-7 (19/7/24)
Java Architecture
JDK : Java Development Kit
 Compiler , debugger and necessary tools
 Java Runtime Environment

JRE : Java Runtime Environment


 Standard Libraries
 JVM ( Java Virtual Machine ) :

JVM : Java Virtual Machine


 It Manage overall control flow of a java program
 It calls main method

Java program: Platform Independent


JRE : Platform Dependent ( dev in C++ )
Day-8 (22/7/24)
Features of Java
1. Simple
2. Object Oriented
3. Portable
4. Platform Independent Language (JVM)
5. Secured Language
6. Robust Language
7. High Performance (speed)
8. Architectural Neutral

9. Multithreaded Language
10. Distributed Language
11. Dynamic Language
12. Interpreted Language
How to configure JDK-17 (how to change OPEN
JDK from eclipse)
Windows->preferences->java->installedJREs

Eclipse download
->In Build OPEN JDK ( 17 )

Day-9 (25/7/24)
How to write a program in Java ?
Keyword : reserved word ( meaning has been defined already)
 In Java if you are creating a variable you must provide its data
type
 In java data type checks at Compile time and that is why it is
called statically typed language

 Dynamically typed language: Python Javascript..etc


 Statically typed language: C C++ Java..etc

Program: Declaration and Initialization


In a block you can’t declare two variable with same name

Java Identifier
1.Allowed : A-Z a-z 0-9 $ _
2.You can’t starts with digits
3.You can’t take space
4.there is no limit of length but try to take between 4-15
5.you can’t take keyword as a variable name
Rule : A-Z a-z 0-9 $ _
Convention : Java follows Camel Convention
Ex.
 Class Name: ThisIsMyCar
 Method Name: thisIsMyCar

 Class : first charated Upper case


 Method : first character lower case
 Keyword : all character are lower case alphabet

Day-10 (26/7/24)

 Programming Language: Java


 Software : Employee Management System
 Name : dsfchdu dscfhdscdschsdiuc
 Address : sdhfcsdkg sdafgj dfbgdsdjhfbdfsdvdsvd dsvdsv
 Gender : m
 Height : 5.8
 adhaarNo : 8545454543547

Types of Data types


1.Primitive data type
2.Non Primitive data type ( Later )

Primitive data type


 Integer
 Decimal
 Other
Why range is fixed?
Byte -128 to +127
 Size: 1 byte : 8 bit
 127: binary(01) : string -> 8 or less
package firstpro;
public class my_launch {
public static void main(String[] args) {

byte v1=-128; //8bit


short v2=4455;
int v3=34543545;
long v4=343434343553l; // l OR L

float v5=1983.67679212343456561f; //f OR F


System.out.println(v5);

double v6=1983.67679212343456561;
System.out.println(v6);

char v7='M';

boolean v8=true;
}
}
Day-11 (29/7/24)

 Java Control Statement


 User Input

How to take user input in java ?


 C Langugae : scanf() %d %f
 In Java : Scanner class
 No need to import classes from java.lang package

package firstpro;
import java.util.Scanner;
public class Launch {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in); //Now u can use


Scanner class through scan var

System.out.print("ENTER A BYTE VALUE:");


byte v1=scan.nextByte();
System.out.println(v1);
short v2=scan.nextShort();
int v3=scan.nextInt();
long v4=scan.nextLong();

float v5=scan.nextFloat();
double v6=scan.nextDouble();

char v7=scan.next().charAt(0);
boolean v8=scan.nextBoolean();
}
}

//Scanner : need to import -> import java.util.Scanner;


//System : automatically java.lang.System
//String : automatically java.lang.String

if statement
1.simple if statement
if(condition){
}

Day-12 (30/7/24)
2. if else statement
->you can use only if but u cannot use only else
package firstpro;
public class Launch {
public static void main(String[] args) {

int k=1000;
boolean b=true;

if(b) {
System.out.println("inside if");
}
else {
System.out.println("inside else");
}

System.out.println(k);

}
}
If there is no curly bracket with if or else then the first statement after
if() will be considered inside
Java is a free form language
package firstpro;
public class Launch {
public static void main(String[] args) {

int k=1000;
//true
if(k<10000);
{
System.out.println("inside if");
}
else //compile time error
{
System.out.println("inside else");
}
}
}
package firstpro;
public class Launch {
public static void main(String[] args) {
//if else if ladder
//Nested if else

/*
* Student-->Admission
* USER INPUT:
* age
* per
* pincode
*
* Eligible : age>=18 per>=50
* Not Eligible : Reason (either age or per)
*
* if per is less than 50
* if pincode is eq to 121212---->Eligible
* otherwise not Eligible
*
*/

int age=10;
if(age<5) {
if(age<3) {

}
else
{

}
}
else
{
if(age>10) {

}
}
}
}

Logic building: ans(waste)

Day-13 (31/7/24)
Nested if else
Example: if you have to print success message by checking multiple
condition and we have to provide error message for each condition
Problem:
 bracket matching
 Program creeps to right side
Solution: Logical operator
package firstpro;
import java.util.Scanner;
public class Launch {
public static void main(String[] args) {

// if else if ladder
// Nested if else
/*
* Student-->Admission USER INPUT: age per pincode
*
* Eligible : age>=18 per>=50 => Eligible Not Eligible : Reason
(either age or
* per)
*
* if per is less than 50 if pincode is eq to 121212---->Eligible
otherwise not
* Eligible
*
*/

int age, per, pin;


Scanner scan = new Scanner(System.in);

System.out.print("Enter age: ");


age = scan.nextInt();

System.out.print("Enter per: ");


per = scan.nextInt();

System.out.print("Enter pin: ");


pin = scan.nextInt();

if (age >= 18) {


if (per >= 50) {
System.out.println("U R ELIGIBLE");
} else {
if (pin == 121212) {
System.out.println("U R ELIGIBLE");
} else {
System.out.println("NE:age & pin");
}
}
} else {
System.out.println("NE:age");
}
}
}

if else if statement (ladder)


Example: if you have to print success message on each condition and
we have to provide common error message
package firstpro;
import java.util.Scanner;
public class Launch {
public static void main(String[] args) {

/*
* USER : pin
* 1234->pune
* 3456->banglore
* 9898->bhopal
* Not exist
*/

Scanner scan = new Scanner(System.in);


System.out.println("Enter PIN");
int pin=scan.nextInt();

if(pin==1234) {
System.out.println("pune");
}
else if(pin==3456) {
System.out.println("banglore");
}
else if(pin==9898) {
System.out.println("bhopal");
}
else {
System.out.println("NOT EXIST");
}
}
}

Multiple If vs If else
if (pin == 1234) {
System.out.println("pune");
}
if (pin == 3456) {
System.out.println("banglore");
}
if (pin == 9898) {
System.out.println("bhopal");
}

// if(pin==1234) {
// System.out.println("pune");
// }
// else if(pin==3456) {
// System.out.println("banglore");
// }
// else if(pin==9898) {
// System.out.println("bhopal");
// }

 If else will be efficient coz it will not check further condition if


the condition true

psvm {
int a=10;
if ( a < 20 ) {
sop(“hello”);
break;
sop(“hiiii”);
}
}
ANS: compile time error

Day-14 (3/7/24)
Switch statement
->it is a statement which is almost similar like if else if but it provides an
efficient way to dispatch execution flow to different part of program
->Generally Switch is used to create Menu
->With switch case you can use byte short int char
Non primitive: enum String (Since Java 7) Wrapper class
->If you are creating a switch statement then try to take cases in contiguous order
->When u use contiguous number( 1 ,2 ,3..etc ) the internally java compiler uses JUMP
TABLE to store those conditions and then control will directly jump on the case which u
want to execute and that is why it is more efficient that if else if
->For non-contiguous cases then compile will use lookup table and still it is more efficient
that if else if
->case value of switch must be either literals or constant
->Case value must be unique
->You can create Nested Switch
IF ELSE IF is useful in many cases
 Complex expression
 Support Non Decimal Values
 Simple statement

package firstpro;
import java.util.Scanner;
public class Launch {
public static void main(String[] args) {

int num1,num2;
Scanner sc = new Scanner(System.in);
System.out.print("Enter Num1: ");
num1=sc.nextInt();
System.out.print("Enter Num2: ");
num2=sc.nextInt();

System.out.println("Press 1->add\nPress 2->sub\nPress


3->mul\nPress 4->div");

System.out.print("Enter Your Choice: ");


int choice = sc.nextInt();
switch (choice) {

case 1:
System.out.println("OUTPUT: "+(num1+num2));
break; //jump control statement : break
statement
case 2:
System.out.println("OUTPUT: "+(num1-num2));
break;
case 3:
System.out.println("OUTPUT: "+(num1*num2));
break;
case 4:
System.out.println("OUTPUT: "+(num1/num2));
break;
default:
System.out.println("WRONG CHOICE");
}

System.out.println("EXIT");
//
// if ( ! (choice*choice==1 || choice==11 ) ) {
// System.out.println("OUTPUT: "+(num1+num2));
// }
// else if (choice==2) {
// System.out.println("OUTPUT: "+(num1-num2));
// }
// else if (choice==3) {
// System.out.println("OUTPUT: "+(num1*num2));
// }
// else if (choice==4) {
// System.out.println("OUTPUT: "+(num1/num2));
// }
// else {
// System.out.println("WRONG CHOICE");
// }
}
}
Loop Control Flow Statement
In Java loop is used to iterate a part of program multiple times

1.for loop
->when the number of iteration is fixed

Labeled For Loop


Scanner scanner = new Scanner(System.in);

int i,j;
Upper:
for( i=1 ; i<=5 ; i++) { //5
Lower:
for( j=1 ; j<=5 ; j++) {

System.out.println("Hello");
System.out.println("DO U WANT TO PRT AGAING Y->1/N-
>2");
int choice=scanner.nextInt();
if(choice==2) {
break Upper;
}
}
}
Day-15 (5/8/24)

i++ : post increment


++i : pre increment
i-- : post decrement
--i : pre decrement
int a=10;
System.out.println(a);
System.out.println(a++); //p->10 then 10->11
System.out.println(a);
System.out.println(++a); //11->12 then p->12
System.out.println(a);
System.out.println(a--); //p->12 then 12->11
System.out.println(a);
System.out.println(--a); //11->10 then p->10

while Loop:
->when we don’t know the condition
while(condition){
}

do-while loop
->when we don’t know the condition but you want to run at least
once
package firstpro;
import java.util.Scanner;
public class Launch {
public static void main(String[] args) {

// int i;
// for( i=10 ; i<=10 ; i++) {
//
// System.out.println("Hello");
// }

// int i;
// for( i=1 ; i<=10 ; i=i+1) {
//
// System.out.println("Hello");
//
// }

// int i;
// for( i=1 ; i<=10 ; i=i+1);
// System.out.println("Hello");
// System.out.println("HIII");

// int i=1;
// for( ; i<=5 ; ) {
//
// System.out.println("Hello");
// i++;
//
// }

// int i=1;
// for( ; i<=5 ; i++ ) {
//
// System.out.println("Hello");
// i++;
// }
//1 3 5

// int i=1;
// for( ; i<=5 ; ) {
//
// System.out.println("Hello");
// i=i+3;
// }

// int i;
// for( i=15 ; i>=10 ; i--) {
//
// System.out.println("Hello");
//
// }
//Post decrement operation : i-- => (i=i-1)

//NESTED FOR LOOP


// int i,j,count=1;
// for( i=1 ; i<=5 ; i++) { //5
//
// for( j=1 ; j<=5 ; j++) {
// System.out.println("Hello"+count);
// count++;
// }
// }

// Scanner scanner = new Scanner(System.in);


// int i;
// for( i=1 ; i<=10 ; ) {
//
// System.out.println("Hello");
// System.out.println("DO U WANT TO PRT AGAING Y->1/N->2");
// int choice=scanner.nextInt();
// if(choice==2) {
// break;
// }
// }

// Scanner scanner = new Scanner(System.in);


// int i,j;
// Upper:
// for( i=1 ; i<=5 ; i++) { //5
// Lower:
// for( j=1 ; j<=5 ; j++) {
//
// System.out.println("Hello");
// System.out.println("DO U WANT TO PRT AGAING Y->1/N-
>2");
// int choice=scanner.nextInt();
// if(choice==2) {
// break Upper;
// }
// }
// }

// for(int i=1 ; i<=10 ; i++) {


//
// if(i==5) {
// continue;
// }
// System.out.println("Hello"+i);//1 2 3 4
// }

// for(int i=1 ; i<=10 ; ++i) {


//
// System.out.println("Hello"+i);
// }

// for(int i=1 ; i<=10 ; i++) {


//
// System.out.println("Hello"+i);
// }

// for(int i=10 ; i>=1 ; --i) {


//
// System.out.println("Hello"+i);
// }

// int a=10;
// System.out.println(a);
// System.out.println(a++); //p->10 then 10->11
// System.out.println(a);
// System.out.println(++a); //11->12 then p->12
// System.out.println(a);
// System.out.println(a--); //p->12 then 12->11
// System.out.println(a);
// System.out.println(--a); //11->10 then p->10

// Scanner scanner = new Scanner(System.in);


//
// while(true) {
//
// System.out.println("Hello");
// System.out.println("DO U WANT TO PRT AGAING Y->1/N->2");
// int choice=scanner.nextInt();
// if(choice==2) {
// System.out.println("STOPPED");
// break;
// }
// }

// Scanner scanner = new Scanner(System.in);


// int i;
// for( i=1 ; i<=2 ; ) {
//
// System.out.println("Hello");
// System.out.println("DO U WANT TO PRT AGAING Y->1/N->2");
// int choice=scanner.nextInt();
// if(choice==2) {
// break;
// }
// }

// int k=10;
// while(k<20) {
// System.out.println("hello");
// k++;
// }

// int k=10;
// while(k<20) {
// System.out.println("hello");
// k++;
// }
// System.out.println("hiii");

// int k=10;
// while(k>20) {
// System.out.println("hello");
// k++;
// }
// System.out.println("hiii");

// int k=10;
// do
// {
// System.out.println("Hello");
// k++;
// }
// while(k<5);//11-19

}
}
Problem:
WAP to create a Calculator
***Welcome to xyz****
Press1->add
Press2->sub
Press3->mul
Press4->div
Press5->exit
Enter your choice: 1
Enter Num1: 10
Enter Num2: 2
OUTPUT: 12

Press1->add
Press2->sub
Press3->mul
Press4->div
Press5->exit
Enter your choice: 2
Enter Num1: 10
Enter Num2: 2
OUTPUT: 8

Press1->add
Press2->sub
Press3->mul
Press4->div
Press5->exit
Enter your choice: 5
Thanks for using…

Day-16 (6/8/24)
Methods in Java
->Method is just a block of code
->It is used to perform code reusability

Types of Method:
1. Inbuilt method/Predefined/Built-in/System defined
Ex. nextInt() nextFloat()…etc
2. User defined method
Ex. main method

User defined method


->Method must be inside a class in Java
->Access modifier : public private protected default
->Access modifier : scope
->Any no of method you can create inside the class
Public method : you can access from anywhere within the project
whether inside or outside the package
Private method: you can only call this method from inside the class
Ways to create a Method:
1. No Parameter No Return
2. Parameter No Return
3. No Parameter Return
4. Parameter Return

 Recursion
 StackoverflowError
 Method Overloading

Day-17 (7/8/24)
No Parameter No Return
Parameter No Return
No Parameter Return
Parameter Return

package firstpro;
public class Launch {

public static void main(String[] args) {

MyClass myClass = new MyClass();


myClass.m1();
myClass.m2(10, 20);

int result=myClass.m3();
System.out.println("MAIN:="+result);

result=myClass.m4(10, 20);
System.out.println("MAIN:="+result);
}
}

package firstpro;
public class MyClass {

//No Parameter No Return

public void m1() {


System.out.println("MY LOGIC-1");
}

//Parameter No Return

public void m2(int a , int b) {


System.out.println("SUM="+(a+b));
}

//No Parameter Return

public int m3() {


//int a=10,b=20,c=a+b;
//Free to write any logic
//return c;

// int a=10,b=20;
// return a+b;

return 10;
}

//Parameter Return

public int m4(int a, int b) {


return a+b;
}
}
//int a, int b => parameters
//10, 20 => arguments

Note: int / int = always int

Task
WAP to create a Calculator
***Welcome to xyz****
Press1->add
Press2->sub
Press3->mul
Press4->div
Press5->exit
Enter your choice: 1 ===>Switch case 1: call a sum<=method(num1,num2)
Enter Num1: 10
Enter Num2: 2
OUTPUT: 12

Press1->add
Press2->sub
Press3->mul
Press4->div
Press5->exit
Enter your choice: 2 Switch case 1: call a sub<=method(num1,num2)
Enter Num1: 10
Enter Num2: 2
OUTPUT: 8

Press1->add
Press2->sub
Press3->mul
Press4->div
Press5->exit
Enter your choice: 5
Thanks for using…

Day-18 (8/8/24)
Recursion
->it is a programming technique in which a method calls itself
Amazon Ecommerce
Software development:
10,000 classes------------------------------->
 Payment : 5 class
 Product : 10 class
 Review : 3 class
 Search and filter : 4 class
 Login and logout : 2 class
Package is used to categorize the classes
On Web-> uniquely identify (domain name)

Types of variable
Static
Local :
 Declare inside a method
 Scope : withing the block
 You cant use access modifier
 You cant use it before initialization
 It does not have any default value

Instance:
 Declare outside the method inside the class
 Scope: decided by access modifier
 We must use access modifier, by default it is default only
Default access modifier : within the package
 You can use it before initialization
Default values : integer : 0 , decimal: 0.0 , char -> blank ,
boolean : false , Non primitive : null

Type Casting
->Converting one data type into another
1.Widening type casting(Implicit type Casting)
No Data Loss
2.Narrowing type casting(Explicit type Casting)
Data Loss

Character Encoding
->it is way to convert character into its numeric form, this allows text
to be stored and transmitted in digital form

1ASCII (American Standard Code for Information Interchange)


 Alphabets
 Digits and useful symbol
 Total 128 character
 A-Z(65-90) a-z(97-122)
2.UNICODE : 1.5lakh
->ASCII is like a subset
->European Language: French Italian..etc
->Devanagari: hindi, Sanskrit, nepali..etc
->Chinese, Korean , Japanese..etc
->Maths, emojis
https://www.ssec.wisc.edu/~tomw/java/unicode.html
Day-19 (9/8/24)

package com.methods;
public class Recursion {

public void m1() {

// byte target=100;
// char target2=65535;
//
// System.out.println(target2);

// short v1=target;
// int v2=target;
// long v3=target;
// float v4=target;
// double v5=target;

// byte v0=target2;
// short v1=target2;

// int v2=target2; //4->(2^31)-1


// long v3=target2;
// float v4=target2;
// double v5=target2;

int x=100;
byte b=(byte)x;
System.out.println(b);

float f=14.77f;
byte b1=(byte) f;
System.out.println(b1);

//Double float long int short byte

int k=100;
char c=(char)k;
System.out.println(c);

}
}

Limit size of recursive call


->WIN /mac (32/64) : 1mb stack size
->linux: 320kb -> stack size
Command : java –Xss2m com\start\Launch.java

Day-20 (12/8/24)
 Before Java
 Java History
 Java Features
 Java Arch
 Data types
 Control statement
 Method

OOP (Object Oriented Programming)


 Raju’s car
 OOP’s concepts
 Programming Paradigm
 Programming philosophy
 Way of programming
 Approach of programming

In OOP you can relate concepts through real-world entities

Ex. class : In java class is used to categorize the


problem
Concept------------------->Real World
OOP’s concepts
 Class
 Object
 Encapsulation
 Inheritance
 Polymorphism
 Abstraction

Object Oriented Programming Language:


 All the concepts of OOP (java)
 Primitive data types

Object Based Programming Language


 All the concepts of OOP exception inheritance or
polymorphism (VbScript, JavaScript(Before ECMA-6))
 Primitive data types

Pure Object Oriented Programming Language


 Everything is in the form of Object (Small Talk)

Java supports primitive data type but java is a flexible language in


which we can convert primitive into its object form

class
->class is a fundamental building block in OOP
->class is used for categorization
->C supports procedural oriented programming

=======================================================

 When you create a class it won’t take any memory space inside
the RAM
 Class is JUST a blueprint
 Object is a real-time existence of a class inside the memory
 Object is an instance of a class

INSTANCE : Murt roop


Day-21 (14/8/24)
Object
->An object is a basic unit of OOP
->To create an object in java we can use new keyword
Characteristics of Object
 State : instance variable
 Behavior : methods
 Identity : hashcode
->Java does not reveal its object’s memory address
->Java uses pointer internally
->CLASS IS ALSO A USER DEFINE DATA TYPE
DOG : scooby , barking , [Color/2ft/15kg]
->In java Objects are treated as First class citizen
First class citizen
->you can hold inside a variable
->we can pass it inside a method
->we can return it from a method

Blueprint: CAR
->BMW--------------->LONDON
->MAHINDRA------->MUMBAI
->TATA--------------->AHMADABAD

Dog d1=new Dog();


Dog d2=new Dog();
Dog d3=new Dog();

Java Memory Management


->It is a process of allocation and deallocation of Objects

CLASS LOADING:
->Classes are loaded into the JVM by class loader (Part of JRE)
->byte verification (.class)
->Method Area: store Meta data (class name, method name, static
data,
Modifiers...etc.)

Object Creation:
->JVM allocated memory for the object (Instance variable) inside the
Heap memory
->After memory allocation, JVM puts some default values
->constructor call ()

Object Reference
->a reference var is assigned and pointer to the object
->If your ref variable is a local variable then it will get stored inside
the stack with activation record
->Activation record: local var, method parameter,controls..etc

Object Usage:
 Field access
 Method access

Garbage Collection ( It is a process )


The JVM keeps track of references of Objects, if an object becomes
unreachable or references less then it is eligible for Garbage
collection
Then a component of JVM called Garbage collector will clean up the
unused memory

Day-22 (15/8/24)
this keyword in java
->this is a keyword in java which provides current class object
->Generally in java we use this keyword to diff between local and
instance variable
->you can use it inside the method as well as constuctor

Encapsulation
->It is a fundamental concept of oop
->it is used to bind data member and method as a single unit
->In encapsulation instance variables are private to hide its access
from anther class and this is only called data hiding
Program: data hiding
DATA BINDING

Day-23 (16/8/24)
->Class->Revision->Notes

Constructor
->constructor is a block of code like a method
->constructor is used to initialize the Object

->Constructor Name must be same as class name(Launch, Launch)


->Constructor has no return type
->you can use any access modifier, public private..etc
->You need not to call constructor but it will get called automatically
by JVM while object creation or you can call one constructor
explicitly from another constructor
->If you don’t have any constructor inside your class then JVM will
create a constructor-> Default Constructor
Constructor Chaining
What is the diff between this and this()

this->keyword
this()->Constructor call
 ->Only allowed inside the constructor
 ->It is used to call one constructor from another constructor of same
class
 ->this() must be first statement inside the constructor
 ->Recursion is not allowed while constructor chaining

Day-24 (18/8/24)
Array
->Array is an Object in Java
->Array is a collection of similar/homogeneous data
->By using array we can hold multiple values in a single variable
->it uses contiguous memory location
->It is immutable

Types of Array:
1. Single Dimensional Array (1D)
a.Input by programmer
b.Input by user
2. Multi-Dimensional Array(2D,3D..etc)

1D array(Input by programmer)

package databind;
public class Launch {

public static void main(String[] args) {

int arr[]= {11,22,33,44,55};

// for(int i=0 ; i<arr.length ; i++) {


//
// System.out.print(arr[i]+" ");
// }
//
// System.out.println();
//
// for(int i=arr.length-1 ; i>=0 ; i--) {
//
// System.out.print(arr[i]+" ");
// }

// int sum=0;
// for(int i=0 ; i<arr.length ; i++) {
//
// sum=sum+arr[i];
//
// //sum=0+11=>11
// //sum=11+22=>33
// }
// System.out.println(sum);

}
}

1D Array(Input by user)
Day-25 (20/8/24)
Multi-Dimensional Array
Raju roll: 18
 Int roll=18;
10 std roll:
 1D array
4dep-> cs(10) it(10) mech(10) civ(10)
[0-9 , 10-19 , 20-29 , 30-39]
 2D array
3clg->4dept->10
 3D array
2state->5clgs->4deps->10
 4D array

->2D array:
 2D array is the set of 1D array
 For 2D array 1D array acts like an element
a.Regular Array->prog/user
b.Jagged Array->prog/user
->3D array:
 3D array is the set of 2D array
a.Regular Array->prog/user
b.Jagged Array->prog/user

2D Regular Array | Prog input


2D Jagged Array | Prog input
For each loop in 2D

2D Regular Array | User input


2D Jagged Array | User input

TASK-1:

TASK-2
 Num1>num2
 0<Num1 & num <100
Enter num1: 10
Enter num2: 14
10+11+12+13+14=60

Day-26 (22/8/24)
3D Regular Array | Prog input
->3D array is the set of 2D array
->for 3D array 2D array acts like an element
Ex. 2-CLG 3-DEP 4-STD
3D Jagged Array | Prog input

3D Regular Array | User input


Enter no of clg
2
Enter no of dept
3
Enter no of std
4
Enter roll no of std-0 of clg-0 dep-0
11
Enter roll no of std-1 of clg-0 dep-0
23
Enter roll no of std-2 of clg-0 dep-0
45
Enter roll no of std-3 of clg-0 dep-0
33
Enter roll no of std-0 of clg-0 dep-1
23
Enter roll no of std-1 of clg-0 dep-1
34
Enter roll no of std-2 of clg-0 dep-1
53
Enter roll no of std-3 of clg-0 dep-1
56
Enter roll no of std-0 of clg-0 dep-2
234
Enter roll no of std-1 of clg-0 dep-2
34
Enter roll no of std-2 of clg-0 dep-2
34
Enter roll no of std-3 of clg-0 dep-2
34
Enter roll no of std-0 of clg-1 dep-0
423
Enter roll no of std-1 of clg-1 dep-0
43
Enter roll no of std-2 of clg-1 dep-0
54
Enter roll no of std-3 of clg-1 dep-0
43
Enter roll no of std-0 of clg-1 dep-1
53
Enter roll no of std-1 of clg-1 dep-1
64
Enter roll no of std-2 of clg-1 dep-1
24
Enter roll no of std-3 of clg-1 dep-1
65
Enter roll no of std-0 of clg-1 dep-2
64
Enter roll no of std-1 of clg-1 dep-2
646
Enter roll no of std-2 of clg-1 dep-2
35
Enter roll no of std-3 of clg-1 dep-2
75
11 23 45 33
23 34 53 56
234 34 34 34

423 43 54 43
53 64 24 65
64 646 35 75

3D Jagged Array | User input


Day-27 (23/8/24)
package databind;
import java.util.Scanner;
public class Launch {
public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


System.out.println("Enter no of clg");
int clg=scanner.nextInt();

int arr[][][]=new int[clg][][]; // 2 CLG

for(int i=0 ; i<clg ; i++) { //0 1

System.out.println("Enter no of dept in clg"+i);


int dept=scanner.nextInt();
arr[i]=new int[dept][]; //3,4
}

for(int i=0 ; i<arr.length ; i++) { //0 1


for(int j=0 ; j<arr[i].length ; j++) {
System.out.println("Enter no of std in
clg"+i+",dept"+j);
int std=scanner.nextInt();
arr[i][j]=new int[std];
}
}

for(int i=0 ; i<arr.length ; i++)


{
for(int j=0 ; j<arr[i].length ; j++)
{
for(int k=0 ; k<arr[i][j].length ; k++)
{
System.out.println("Enter roll no of
std-"+k+" of clg-"+i+" dep-"+j);
arr[i][j][k]=scanner.nextInt();
}
}
}
for(int i=0 ; i<arr.length ; i++)
{
for(int j=0 ; j<arr[i].length ; j++)
{
for(int k=0 ; k<arr[i][j].length ; k++)
{
System.out.print(arr[i][j][k]+" ");
}
System.out.println();
}
System.out.println();
}
}
}

Enter no of clg
2
Enter no of dept in clg0
3
Enter no of dept in clg1
4
Enter no of std in clg0,dept0
2
Enter no of std in clg0,dept1
3
Enter no of std in clg0,dept2
4
Enter no of std in clg1,dept0
3
Enter no of std in clg1,dept1
2
Enter no of std in clg1,dept2
1
Enter no of std in clg1,dept3
3
Enter roll no of std-0 of clg-0 dep-0
11
Enter roll no of std-1 of clg-0 dep-0
12
Enter roll no of std-0 of clg-0 dep-1
13
Enter roll no of std-1 of clg-0 dep-1
14
Enter roll no of std-2 of clg-0 dep-1
15
Enter roll no of std-0 of clg-0 dep-2
16
Enter roll no of std-1 of clg-0 dep-2
17
Enter roll no of std-2 of clg-0 dep-2
18
Enter roll no of std-3 of clg-0 dep-2
19
Enter roll no of std-0 of clg-1 dep-0
20
Enter roll no of std-1 of clg-1 dep-0
21
Enter roll no of std-2 of clg-1 dep-0
22
Enter roll no of std-0 of clg-1 dep-1
23
Enter roll no of std-1 of clg-1 dep-1
24
Enter roll no of std-0 of clg-1 dep-2
25
Enter roll no of std-0 of clg-1 dep-3
26
Enter roll no of std-1 of clg-1 dep-3
27
Enter roll no of std-2 of clg-1 dep-3
28
11 12
13 14 15
16 17 18 19

20 21 22
23 24
25
26 27 28
How to pass an Array to a method

Anonymous Array

Neil Sardesai owns Kiddeo corp, a shop for kid's accessories. There are two categories of items with
an id number associated with them as follows:

If the first digit in the id is 1, then the item cost is 50 each.

If the first digit in the id is 2, then the item cost is 100 each.

He also provides a discount of 10% if the total purchase cost is more than 5,000.

Given the item id and the number of items, display the total amount to be paid by the customer.

Input

Single line containing item id followed by a number of items. Both values must be given space-
separated

as shown in the example.

Output:

Single integer displaying the total amount to be paid.

Example 1

Input: 12345 12

Output: 600

Example 2

Input: 26951 60

Output: 5400
package databind;
public class Launch {
public static void main(String[] args) {

int id=22345,item=60,totalprice=0,start=id/10000;
if(start==1) {
totalprice=50*item;
}else {
totalprice=100*item;
}
if(totalprice>5000) {
System.out.println(totalprice-totalprice/10);
}
else
{
System.out.println(totalprice);
}
}
}
Ema Harper, a teacher, uses an array to track student attendance in a class.
The array contains a series of 1s and 0s, where:

1 represents that the student was present.


0 represents that the student was absent.
The variable k represents the minimum percentage of classes the student must attend
to be eligible for an upcoming examination.

Write a program to determine if the student is eligible for the exam based on the attendance
record.

Input:
A string attendance consisting of 1s and 0s, representing the attendance record.
An integer k representing the minimum percentage of classes the student must attend.
Output:
Output "YES" followed by the actual attendance percentage if the student is eligible for the
exam.
Output "NO" followed by the actual attendance percentage if the student is not eligible for the
exam.

Example 1:
Input: attendance = [1,0,1,0,1,0,1], k = 70
Output: NO 57

Example 2:
Input: attendance = [1,1,1,0,1,0,1], k = 60
Output: YES 71

int arr[]= {1,1,1,0,1,1,1,1,1,0};


int k=70;
//OUTPUT : YES 80

package databind;
public class Launch {
public static void main(String[] args) {

int arr[]= {0,1,0,0,1,1,0,1,1,0};


int k=70;

int presentCount=0;
for (int i = 0; i < arr.length; i++) {

if(arr[i]==1) {
presentCount++;
}
}
int per=(presentCount*100)/arr.length;

if(per>=70) {
System.out.println("YES "+per);
}else {
System.out.println("NO "+per);
}
}
}

There are 8 prison cells in a row and each cell is either occupied or
vacant.

Each day, whether the cell is occupied or vacant changes according to


the following rules:

If a cell has two adjacent neighbors that are both occupied or both
vacant, then the cell becomes occupied.
Otherwise, it becomes vacant.
Note that because the prison is a row, the first and the last cells in the
row can't have two adjacent neighbors.

You are given an integer array cells where cells[i] == 1 if the i-th cell is
occupied and cells[i] == 0
if the i-th cell is vacant, and you are given an integer n.

Return the state of the prison after n days (i.e., n such changes
described above).

Example 1:
Input: cells = [0,1,0,1,1,0,0,1], n = 7
Output: [0,0,1,1,0,0,0,0]

========================================================
==========

[0,1,0,1,1,0,0,1] after 7 days


[0,1,1,0,0,0,0,0] day-1
[0,0,0,0,1,1,1,0] day-2
[0,1,1,0,0,1,0,0] day-3
[0,0,0,0,0,1,0,0] day-4
[0,1,1,1,0,1,0,0] day-5
[0,0,1,0,1,1,0,0] day-6
[0,0,1,1,0,0,0,0] day-7

Day-28 (26/8/24)
1.Logic building ( long term )
2.Concept building ( MUST )

String
->String are set of Characters in Java enclosed within double quote
->Widely used (Human) name age eye color, weigh height address
->Strings are object in Java

Types of String
1.Mutable String Ex. Address
2.Immutable String Ex. AdharNo

Immutable
We can create immutable String in two ways
1.with new Keyword
2.without new keyword
String methods
1.concat() Return type: String
2.equals() Return type: boolean

Day-29 (27/8/24)
Practice program for project
development
Ex. Employee Management System
 INSERT (create)
 READ
 UPDATE
 DELETE
//CRUD Operation // CURD Operation
Employee Data:
eid,ename,eaddress,esalary
Database/Storage->Array[Binding]
USER INPUT:- ========>Validation======>Store
Layers in Enterprise Application
Day-30 (28/8/24)
3.length() Return type: int
4.chatAt() Return type: char

5.toCharArray() Return type: char[]


6.endsWith () Return type: boolean
7.startsWith () Return type: boolean

8.equalsIgnoreCase () Return type: boolean


9.toUpperCase () Return type: String
10.toLowerCase () Return type: String

11.split () Return type: String[]


12.getBytes () Return type: byte[]
Problem: Write a program to check whether
the given string is palindrome or not
mam,dad,malayalam,paap

You are given a string and a shift value. Your task is to shift each
character in the string by the given shift value in the alphabet.
The shift value should be less than or equal to 26. If the shift moves
past 'z', it should wrap around to the beginning of the alphabet.
Input and Output
Input:
 A string s: "abcdz"
 An integer shift: 5
Output:
 A new string where each character in the original string is
shifted by the given shift value: "fghie"
Day-31 (30/8/24)
13.substring() return type:String

Task:
String s=”this is my car”;
Output: This Is My Car
14.contains() return type:boolean
15.contains() return type:boolean

16.indexOf() return type:int


17.lastIndexOf() return type:int
You are given a string s and an integer p. Your task is to reverse the
pth word in the string. Words are separated by spaces.
If p exceeds the number of words in the string, the output should be
the string unchanged.
Input and Output
Input:
A string s: "This is my car"
An integer p: 2
Output:
A new string where the pth word is reversed: "This si my car"

18.replace() return type:String

19.trim() return type:String


20.compareTo() return type:int
Lexicographically
You are given an array of integers and a target sum. Your task is to find two
distinct indices in the array such that the values at those indices add up to the
target sum. The function should return the indices of these two numbers.
You can assume that there will be exactly one solution and you may not use
the same element twice.
Input:
 An array of integers: {5, 6, 3, 1, 5}
 A target sum: 10
Output:
 Indices of the two numbers whose values add up to the target sum: 0 4

Day-32 (1/9/24)
How to take String input from user?
1.next() , nextInt() -> Single String token (Ex. word)
->nextInt() reads numbers from input buffer
->it reads only integer and \n remains inside the input buffer
2.nextLine() -> To take complete line
->it reads complete line and discard \n from input buffer
Where String user input get stored?
->Ans: NON CONSTANT POOL
->In java any dynamically created strings are stored inside the non
constant pool
1.String pool lookups are computationally expensive
2.Java ensure that String literals and dynamically created String are
managed separately

String literals
 String name=”raju”;
3.when u create String using concat(),replace(),substring()..etc it will
store inside non constant pool

4.if you create a String using new keyword it will store inside non
constant pool
//it is mostly used within inbuilt methods of String
5.We can push a string from non constant pool to constant pool and
this is called String interning

Mutable String
->we can create mutable String in two ways in java
1. StringBuffer class : synchronized: multithreading
2. StringBuilder class : non synchronized: multithreading
PAYTM BOX: 5-> scan->pay
Day-33 (3/9/24)

 StringBuffer->Synchronized (slow in performance)


(In Multithreaded Env)
 StringBuilder->Non Synchronized
(In SingleThreaded Env)
 Java basic
 Methods
 Class Object
 Encapsulation
 Constructor
 this this()
 Array String
 OCT,HEXA,BINARY,OPERATOS
TEST:-MCQ PATTERN,CODING QUES

Day-34 (4/9/24)
Java Operators:
b+c; + is a operator || a,b->Operands
Arithmetic operator
+ - * / % ++ --
Relational operator
== != > < >= <=
Logical operator
 && -> AND
 || -> OR
 ! -> NOT

Assignment operator
= += -= *= /=
Unary operator(on single operand)
+ - ++ -- ! ~
Ternary operator(shorthand for an if-else)
instanceOf operator

Bitwise operator
Bitwise AND (&)
 1&1=1
 1&0=0
 0&1=0
 0&0=0
Bitwise OR ( | )
 1&1=1
 1&0=1
 0&1=1
 0&0=0

Bitwise XOR ( ^ )
 1&1=0
 1&0=1
 0&1=1
 0&0=0

BITWISE NOT ( ~ )

Right Shift (>>)


Left Shift (<<)

Java Number System


1.decimal(0-9)
2.binary(0-1)
3.Octal(0-7)
4.Hexadecimal(0-9 ABCDEF)

Day-35 (6/9/24)
Inheritance
Types of Inheritance

Note: In java multiple inheritance is not possible through class but


you can achieve it through an Interface
What is Diamond shape problem?
 Problem occurred by multiple inheritance
Day-36 (9/9/24)
Rule: Constructor cannot be inherited
super()->Constructor call : it is used to call parents’ class constructor
final keyword
 ->method : we cannot override
 ->class: we cannot extends
 ->variable : local var (cant update its value) or instance(cant update its value and we
can initialize the value through constructor)

Day-37 (10/9/24)
 Method Overloading
public void xyz() {
System.out.println("xyz1");
}
public void xyz(int a,float b) {
System.out.println("xyz2");
}
public void xyz(String s) {
System.out.println("xyz3");
}
public void xyz(float a,int b) {
System.out.println("xyz4");
}

 Method Overriding
public class B extends A{

@Override
public void xyz() {
System.out.println("xyz");
}
}

Polymorphism (Many Forms)


 It is a technique in which you can perform diff
diff task with a same statement
 Reduces line of code
a.Compile Time polymorphism/early binding/static binding :
Achieved at Compile time , Method Overloading
b.Runtime polymorphism/late binding/dynamic
binding/dynamic method dispatch: Achieved at Runtime time,
Method Overriding, Upcasting

Compile Time polymorphism


Runtime Time polymorphism
 Create a non polymorphic program
Calculation:
 10 CARS : 20 METHODS
 Launch: 10CAR OBJECT + 200 METHOD CALL = 210

Day-38 (11/9/24)
STATIC KEYWORD
->it is used for memory management (save memory)
->variable, method, block, nested class

Static Variable (Class Variable)


->local variable cant be static
->at the time of Class Loading

Ex. 5000 -> Employee (id ,name,age,salary,companyId)


Day-39 (13/9/24)
Static Block : used to initialize the static var/Class var
(execute before static method)
 You can’t access not static things inside the static
area
Day-40 (13/9/24)
Interface
->Interface is just a block of Code
public interface Demo{
}
->Interface is just a blueprint of your class
->Interface is used to achieve STANDARDIZATION (NAAM HAMARA
KAAM TUMHARA)
->Through interface we can achieve multiple inheritance
->Through interface we can achieve loose coupling
->through an interface we can achieve abstraction(SEE DAY 44)
Point:
Interface can’t contain method with its body but inside an interface
we can only create abstract method
Abstract method: method without body
public interface MyInterface {
public abstract void abc();
//abstract method
}
Abstract keyword is optional
 We cannot instantiate an interface
 We use implements keyword to implement an interface
Day-41 (16/9/24)
Multiple Inheritance

Coupling:
a.loose coupling
b.tight coupling
Marker interface : empty interface (USED
BY JVM Internally)
Ex. Serializable
public interface Test implement Serializable{
}

Day-42 (18/9/24)
public Interface Demo {
public void xyz();
}
public Interface Femo extends Demo {
public void pqrs();
}
 Interface is an immutable block of code
public Interface Standard { ====>100 IMPL CLASS
public void crud();
}

Pending:
Access modifier
Abstraction:
 Interface (100%)
 Abstract class (0 to 100%)

Practice Mini Project:


Employee:
 companyId;
 eid;
 name;
 age;
 salary
 address

Day-43 (20/9/24)
Access Modifier
->it defines access level or scope
 public : inside and outside the package
 default: within the package
 private: within the class
 protected: within the package, and outside the package from
subclass
While method overriding u can increase the scope
level
 Upper Level class can be either public or default
but inner class supports all access modifier

Day-44 (22/9/24)
Abstraction
-> END USER : showing only essential thing and hiding
the implementation
->We can achieve abstractions in two ways
1. Interface ( 100 % )
2. abstract class ( 0 to 100% )
Abstract class

package thiskey;
public class Launch {
public static void main(String[] args) {

new Gpay(1000).policy();
new Paytm(2000).policy();

}
}

package thiskey;
public abstract class PaymentGateway {

public int code;

public PaymentGateway(int code) {


System.out.println("PGC");
this.code=code;
}

public void policy() {


System.out.println("COMMON POLICY"+code);
}

public abstract void checkBal();


public abstract void sendMoney();
}

package thiskey;
public class Gpay extends PaymentGateway {

public Gpay(int code) {


super(code);
}

@Override
public void checkBal() {
}
@Override
public void sendMoney() {
}
}

package thiskey;
public class Paytm extends PaymentGateway{

public Paytm(int code) {


super(code);
}

@Override
public void checkBal() {
}
@Override
public void sendMoney() {
}
}
Abstraction with factory design pattern (Through
Abstract class) :

package thiskey;
public class Launch {
public static void main(String[] args) {

// PaymentGateway pg=new Ppay();


// pg.checkBal();
// pg.sendMoney();
//
// pg=new Gpay();
// pg.checkBal();
// pg.sendMoney();
//
// pg=new Paytm();
// pg.checkBal();
// pg.sendMoney();

PaymentGateway paymentGateway = ObjectFactory.get("432");


if(paymentGateway!=null) {
paymentGateway.checkBal();
paymentGateway.sendMoney();
paymentGateway.policy();
paymentGateway.test();
}
else {
System.out.println("WRONG NAME");
}

}
}

package thiskey;
public abstract class PaymentGateway {

public void policy() {


System.out.println("COMMON POLICY");
}

public void test() {


System.out.println("test");
}

public abstract void checkBal();


public abstract void sendMoney();
}
//50%

package thiskey;
public class Ppay extends PaymentGateway {

@Override
public void checkBal() {
System.out.println("PPAY CHECK BAL");
}
@Override
public void sendMoney() {
System.out.println("PPAY SEND MONEY");
}
}

package thiskey;
public class Paytm extends PaymentGateway{

@Override
public void checkBal() {
System.out.println("PAYTM CHECK BAL");
}
@Override
public void sendMoney() {
System.out.println("PAYTM SEND MONEY");
}
}

package thiskey;
public class Gpay extends PaymentGateway {

@Override
public void checkBal() {
System.out.println("GPAY CHECK BAL");
}
@Override
public void sendMoney() {
System.out.println("GPAY SEND MONEY");
}

package thiskey;
public class ObjectFactory {

public static PaymentGateway get(String name) {

if(name.equalsIgnoreCase("paytm")) {
return new Paytm();
}
else if(name.equalsIgnoreCase("googlepay")) {
return new Gpay();
}
else if(name.equalsIgnoreCase("phonepay")) {
return new Ppay();
}
else {
return null;
}
}
}

Day-45 (23/9/24)
Exception Handling
->An Exception in Java is an unexpected event or condition
occurs during the execution of a program
->Abnormal termination of a program due to faulty inputs
->Exception Handling is a mechanism to handle Runtime Errors
Types of Exception:
1.checked Exception (Compile time exception) : later
2.unchecked Exception (Runtime exception)
How to Handle Exception:
 1.try catch block(BEST WAY)
 2.try finally block
 3.throws keywords
try catch block

One try One catch with multiple Exceptions


Exception Hierarchy
package com.mainapp;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Launch {
public static void main(String[] args) {

try
{
Scanner scanner = new Scanner(System.in);
System.out.println("ENTER NUM1");
int num1=scanner.nextInt(); //TEN ---
>INPUTMISEXP
System.out.println("ENTER NUM2");
int num2=scanner.nextInt();
int c=num1/num2;
System.out.println(c);

String s=null;
System.out.println(s.length());
}
catch(ArithmeticException e) {
System.out.println("DO NOT DIVIDE BY ZERO");
}
catch(InputMismatchException e) {
System.out.println("TAKE INT VALUE");
}
catch(Exception e) {
System.out.println("Something went wrong");
}

System.out.println("WORK...");
}
}

Day-46 (23/9/24)
Try catch block can be nested
 Try alone : INVALID
 catch alone : INVALID

finally block
->it is used to close the resources

package com.mainapp;
public class Launch {

public static void main(String[] args) {


Calculator c=new Calculator();
int res=c.add();
System.out.println(res);

}
}

package com.mainapp;
import java.util.Scanner;
public class Calculator {

public int add() {


try
{
try {

} catch (Exception e) {
// TODO: handle exception
}
finally {

}
Scanner scanner = new Scanner(System.in);
System.out.println("ENTER A:");
int a = scanner.nextInt();//ten
System.out.println("ENTER B:");
int b = scanner.nextInt();
//
return a+b;
}
// catch (Exception e)
// {
// System.out.println("SOMETHING WENT WRONG");
// try {
//
// } catch (Exception e1) {
// // TODO: handle exception
// }
// finally {
//
// }
// return 0;
// }
finally {
System.out.println("EXIT");

try {

} catch (Exception e) {
// TODO: handle exception
}
finally {

}
}
}
}

Checked Exception:
->At compile time
JDBC: mostly code->checked exception
HIBERNATE: mostly code->no checked exception
throw throws Throwable
Day-47 (27/9/24)
throw keyword : it is used to invoke an
exception(Inbuilt OR Custom)
 It is used to create your own exception( CUSTOM
EXCEPTION )
10/0->Arithmetic Exception
GYM APPLICATION:
 Age<18 : Exception ->
How to create your own
exception
Day-48 (29/9/24)
MultiTheading
->Multithreading is a technique to perform multitasking
->In software dev field -> Multitasking:
1. Multithreading
2. Multiprocessing

Multiprocessing:
 Process : Process in computing is an instance of a program that is
being executed by OS
 Process is heavyweight
 Memory sharing : Each process has its own memory space, no
sharing.
 Context Switching : Heavy weight due to separate memory and
resource
( SWITCHING DONE BY OS )
 Communication: Inter process commincation(IPC) is heavier

4 CORE:-> 4 processes (MULTITASKING)


1 CORE:-> 1 process (MULTITASKING->CONTEXT SWITCHING)

Multithreading:
->It is a technique through which we can achieve multitasking
->Through multithreading we can utilize CPU time efficently
->Multithreading in java is a process of executing multiple threads
simultaneously
->Thread is just a light weight process(subprocess)
->by default every program is single threaded (main thread created
by JVM)
->Threads are independent on each other

->THREAD IS LIGHT WEIGHT


 Memory sharing : Common memory sharing
 Context Switching : Light
 Communication: Light

HOW TO CREATE A THREAD?

Day-49 30/9/24)
HOW TO CREATE A THREAD?
 Why? For Multitasking
 In java Threads are created by JVM
 In java we can create Threads in two ways
a.Thread class
b.Runnable interface (Multiple Inheritance)
Program: ONE CLASS ONE THREAD (Thread Class)
Program: ONE CLASS MULTIPLE THREAD (Thread Class)
package com.mainapp;
public class Launch {

public static void main(String[] args) {

Table t1 = new Table();


Table t2 = new Table();
Table t3 = new Table();

t1.setName("raju");
t2.setName("kaju");
t3.setName("maju");

t1.start();
t2.start();
t3.start();
}
}

package com.mainapp;
public class Table extends Thread {

@Override
public void run() {

String name = Thread.currentThread().getName();

if(name.equalsIgnoreCase("raju")) {
five();
}
else if(name.equalsIgnoreCase("kaju")) {
seven();
}
else {
eleven();
}
}

public void five() {

for(int i=1;i<=10;i++)
{
System.out.println(5*i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
public void seven() {

for(int i=1;i<=10;i++)
{
System.out.println(7*i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
public void eleven() {
for(int i=1;i<=10;i++)
{
System.out.println(11*i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
}

Day-50 (2/10/24)
Program: ONE CLASS ONE THREAD (Runnable Interface)
package com.mainapp;
public class Launch {

public static void main(String[] args) {

Runnable five = new Five(); //t1


Runnable seven = new Seven(); //t2

Thread t1 = new Thread(five);


Thread t2 = new Thread(seven);

t1.start();
t2.start();
}
}
package com.mainapp;

public class Five implements Runnable {

@Override
public void run() {

String name = Thread.currentThread().getName();


System.out.println(name+"five");

for(int i=1;i<=10;i++)
{
System.out.println(5*i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
package com.mainapp;

public class Seven implements Runnable {

@Override
public void run() {
String name = Thread.currentThread().getName();
System.out.println(name+"seven");

for(int i=1;i<=10;i++)
{
System.out.println(7*i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Program: ONE CLASS MULTIPLE THREAD (Runnable


Interface)
package com.mainapp;
public class Launch {

public static void main(String[] args) {

Runnable r1 = new Table();


Runnable r2 = new Table();
Runnable r3 = new Table();

Thread t1 = new Thread(r1);


Thread t2 = new Thread(r2);
Thread t3 = new Thread(r3);

t1.start();
t2.start();
t3.start();
}
}

package com.mainapp;
public class Table implements Runnable {

@Override
public void run() {

String name = Thread.currentThread().getName();


if(name.equalsIgnoreCase("raju")) {
five();
}
else if(name.equalsIgnoreCase("kaju")) {
seven();
}
else {
eleven();
}
}

public void five() {

for(int i=1;i<=10;i++)
{
System.out.println(5*i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
public void seven() {

for(int i=1;i<=10;i++)
{
System.out.println(7*i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
public void eleven() {
for(int i=1;i<=10;i++)
{
System.out.println(11*i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
}
join()
it will pause the current thread until other threads finishes their
execution

Thread Priority
 Range: min-1 max-10
 High priority: more CPU cycle
 Thread scheduler generally picks high priority thread first

package com.mainapp;
public class Launch {

public static void main(String[] args) throws


InterruptedException {

Database1 database1 = new Database1();


Database2 database2 = new Database2();

// database1.setPriority(1);
// database2.setPriority(10);//

database1.setPriority(Thread.MIN_PRIORITY);
database2.setPriority(Thread.MAX_PRIORITY);
//Thread.NORM_PRIORITY

database1.start(); //finish
database2.start(); //finish

// System.out.println(database1.getPriority());
// System.out.println(database2.getPriority());

database1.join();
database2.join();

//main pause

process(database1.collect,database2.collect);

private static void process(String[] collect1, String[] collect2)


{
for( String d: collect1)
System.out.println(d);

for( String d: collect2)


System.out.println(d);
}
}

package com.mainapp;
public class Database1 extends Thread {

public String collect[]=new String[4];

@Override
public void run() {

String data[]= {"d1","d2","d3","d4"};


int i=0;
for( String d: data) {
collect[i]=d;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("DATA"+i+" COLLECTED FROM DB1");
i++;
}
}
}

package com.mainapp;
public class Database2 extends Thread {

public String collect[]=new String[4];

@Override
public void run() {

String data[]= {"xd1","xd2","xd3","xd4"};


int i=0;
for( String d: data) {
collect[i]=d;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("DATA"+i+" COLLECTED FROM DB2");
i++;
}
}
}

Day-51 (2/10/24)
Race Condition
->A race condition in java occurs when two or more
threads access common data simultaneously and the
outcome of program might be unexpected.
Solution: Synchronization (Thread Safe Env)
->If a thread T is using a Resource R, at that point of time
no other thread can access the same recourse until the
Thread T completed its execution
1.SYNCHRONIZED BLOCK : custom scope
2.SYNCHRONIZED METHOD : broad scope

package com.mainapp;
public class Launch {

public static void main(String[] args) throws


InterruptedException {

Account account = new Account();

Card card1 = new Card(account);


Card card2 = new Card(account);

card1.setName("CARD1");
card2.setName("CARD2");

card1.start();
card2.start();
card1.join();
card2.join();

account.get();
}
}

package com.mainapp;
public class Card extends Thread {

private Account account;

public Card(Account account) {


this.account=account;
}

//CARD1 CARD2
@Override
public void run() {

String name = Thread.currentThread().getName();


System.out.println(name);

for(int i=1;i<=100000;i++) {
account.deduct(2,name );
}
}
}

package com.mainapp;
public class Account extends Thread {

private int bal=500000;

public synchronized void deduct(int bal,String cardName) {

this.bal=this.bal-bal;
System.out.println("DEBIT SUCCESSFULLY"+cardName);

public void get() {


System.out.println(bal);
}
}

Day-52 (5/10/24)
SYNCHRONIZED BLOCK : custom scope
package com.mainapp;
public class Launch {

public static void main(String[] args) throws InterruptedException {

Account account = new Account();

Card card1 = new Card(account);


Card card2 = new Card(account);

card1.setName("CARD1");
card2.setName("CARD2");

card1.start();
card2.start();

card1.join();
card2.join();

account.get();
}
}

package com.mainapp;
public class Card extends Thread {

private Account account;

public Card(Account account) {


this.account=account;
}

//CARD1 CARD2
@Override
public void run() {

String name = Thread.currentThread().getName();


System.out.println(name);

for(int i=1;i<=100000;i++) {
account.change();
}
}
}

package com.mainapp;
public class Account extends Thread {

private StringBuffer xyz=new StringBuffer("pqr") ; //mutable

//Mutable: StringBuffer StringBuilder

private int change=0;


private int k=0;

public void change() {

xyz=xyz.append("a"); //CARD1

synchronized (this) {
//CRITICAL CODE
change++;
}

k++; //RACE CONDITION


}

public void get() {

int count=0;
for(char c : xyz.toString().toCharArray()) {
if(c=='a') {
count++;
}
}
System.out.println("a count: "+count);
System.out.println("value of change: "+change);
System.out.println("value of k: "+k);
System.out.println("THREAD OVERLAP: "+(change-k));

}
}

Easy Example

Level of Synchronization
1.Object Level Lock 2.Class Level Lock
Day-53 (5/10/24)
Dead lock
When two threads are in block/wait state for each other
Sol: access multiple res through multiple thread in same
order
package com.mainapp;
public class Launch {

public static void main(String[] args) {

Resource resource1 = new Resource();


Resource resource2 = new Resource();

resource1.setName("raju");
resource2.setName("kaju");
resource1.start();
resource2.start();
}
}
package com.mainapp;

public class Resource extends Thread {

private String res1="RES1";


private String res2="RES2";
private String res3="RES3";

@Override
public void run() {

String name = Thread.currentThread().getName();


if(name.equals("raju")) {
rajuAccess(name);
}
else {
kajuAccess(name);
}
}

private void rajuAccess(String name) {

synchronized (res1) {
System.out.println(name+" using "+res1);
timeWait();

synchronized (res2) {
System.out.println(name+" using "+res2);
timeWait();

synchronized (res3) {
System.out.println(name+" using "+res3);
timeWait();
}
}
}
}

private void kajuAccess(String name) {

synchronized (res3) {
System.out.println(name+" using "+res3);
timeWait();

synchronized (res2) {
System.out.println(name+" using "+res2);
timeWait();

synchronized (res1) {
System.out.println(name+" using "+res1);
timeWait();
}
}
}
}

private void timeWait() {

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Daemon Thread
->Supportive task or background task done by daemon
thread for user thread

Inter Thread Communication


wait() notify()
package com.mainapp2;
public class Launch {

public static void main(String[] args) {

Message message = new Message();

User u1 = new User(message);


User u2 = new User(message);

u1.setName("raju");
u2.setName("kaju");

u1.start();
u2.start();
}
}

package com.mainapp2;
public class User extends Thread {

private Message message;


public User(Message message) {
this.message=message;
}

@Override
public void run() {

String name=getName();
if(name.equals("raju")) {

int i=0;
while(i<100) {
message.sendMessage("Good Morning"+i, name);
i++;
}
}
else
{
int i=0;
while(i<100) {
message.readMessage(name);
i++;
}
}
}

}
package com.mainapp2;
public class Message {

private String message;


private boolean messageSent; //false

public synchronized void sendMessage(String message,String name) {

while(messageSent==true) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

System.out.println("MSG SENT:-"+message+" by "+name);


this.message=message;

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
messageSent=true;
notify();
}

public synchronized void readMessage(String name) {

while(messageSent==false) {

try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

System.out.println("MSG READ:-"+message+" by "+name);

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

messageSent=false;
notify();

}
}

notify()
package com.mainapp2;
public class Launch {
public static void main(String[] args) {

Message message = new Message();

User u1 = new User(message);


User u2 = new User(message);
User u3 = new User(message);

u1.setName("raju");
u2.setName("kaju");
u3.setName("maju");

u1.start();
u2.start();
u3.start();
}
}

package com.mainapp2;

public class User extends Thread {

private Message message;

public User(Message message) {


this.message=message;
}

@Override
public void run() {

String name=getName();
if(name.equals("raju") || name.equals("kaju")) {

int i=0;
while(i<100) {
message.sendMessage("Good Morning"+i, name);
i++;
}
}
else
{
int i=0;
while(i<100) {
message.readMessage(name);
i++;
}
}
}

package com.mainapp2;
public class Message {

private String message;


private boolean messageSent; //false

//RAJU OR KAJU
public synchronized void sendMessage(String message,String name) {
System.out.println(name+"send method......");

while(messageSent==true) {
try {
System.out.println(name+"send method while......");
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

System.out.println("MSG SENT:-"+message+" by "+name);


this.message=message;

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

messageSent=true;
notifyAll();
}

public synchronized void readMessage(String name) {

System.out.println(name+"read method......");

while(messageSent==false) {

try {
System.out.println(name+"read method while......");

wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

System.out.println("MSG READ:-"+message+" by "+name);

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

messageSent=false;
notifyAll();

}
}
Day-54 (14/10/24)
Collection Framework
Array:
 Size: fixed in size
 Homogeneous
 Type safety

Real-world : Application
 Data: Not in fixed sized
 Data type: Hetrogeneous
->In java, a collection is a framework that provides an architecture to
store and manipulate the group of Data (Object)

Collection vs Array
ARRAY
COLLECTION
SIZE : FIXED Dynamic
DATA TYPE: Primitive & Object Only
Object
TYPE SAFETY: type-safe type
safety (java 5+) GENRICS
ITERATION: No Built-IN
Iterator
Features Basic RICH
Flexible: No YES
Performance: FAST SLOW

USE ARRAY WHEN U NEED A FIXED SIZE, TYPE-SAFE


GROUP OF ELEMENETS
COLLECTION HIERARCHY

 In Collection, we can only hold Object we can’t


hold/store primitive
int age=sc.next();
 No we need to convert primitive into its object
form and for that we use WRAPPER CLASSES
 Int -> Integer
 char -> Character
 float short byte long boolean

OLD WAY(Before Java 5)


package com.mainapp2;
public class Launch {
public static void main(String[] args) {

//Deprecated
int a=10;
Integer i = new Integer(a); //MANUAL BOXING
int k = i.intValue(); //MANUAL UNBOXING

// String k = i.toString();
// System.out.println(k);
}
}

New Way(Java 5): Auto boxing & Auto unboxing


package com.mainapp2;
public class Launch {

public static void main(String[] args) {

//Deprecated
int a=10;
Integer i =a; //Auto Boxing
int k=i; //Auto Unboxing
}
}

Day-55 (14/10/24)
ArrayList
1.Generic :
2.Non Generic :
package com.mainapp;
import java.util.ArrayList;
public class Launch {

public static void main(String[] args) {


//JAVA 5: Collection (Generics)

//NON GENERIC
ArrayList al=new ArrayList();

al.add("raju");
al.add(123); //Autoboxing
al.add(false);
al.add('a');

System.out.println(al);

//GENERIC: type safety


ArrayList<String> al2=new ArrayList<String>();
al2.add("raju");
al2.add("kaju");
al2.add("maju");

System.out.println(al2);

//GENERIC: type safety


ArrayList<Object> al3=new ArrayList<Object>();
al3.add("raju");
al3.add(123);
al3.add(false);
al3.add('a');

System.out.println(al3);

//WILD CARD GENERIC: unknown type


//READ ONLY (LATER)
ArrayList<?> al4=new ArrayList();
al4.add(null);

}
}

 Insertion order: Preserved


 Index supported: YES
 Random Access: YES
 Non Synchronized
 Duplicates : Allowed
 Null : Allowed
 Best suitable for fast data access
 Do not use it for data modification

ArrayList<Object> al=new ArrayList<Object>();


//initial capacity : 10
//New capacity=initial capacity+ initial capacity>>1
=>10 + (10>>1)
=>10 + (1010 >> 1)
=>10+ (101=5) => 15

When u create an ArrayList it will create dynamic Array inside

package com.mainapp;
import java.util.ArrayList;
public class Launch {

public static void main(String[] args) {

ArrayList<Object> al=new ArrayList<Object>();


//ArrayList<Object> al=new ArrayList<Object>(20);
//default capacity=20

al.add("raju");
al.add(123);
al.add(123);
al.add(null);
//
al.add(false);
al.add('a');
System.out.println(al);

al.add(2,"xyz");

System.out.println(al);

System.out.println(al.get(2));

}
}

Program:
package com.mainapp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Launch {

public static void main(String[] args) {

ArrayList<Object> x=new ArrayList<Object>();


x.add("pqrs");
x.add("raju");

ArrayList<Object> al=new ArrayList<Object>();


//->
al.add("raju");
al.add(123);
al.add(123);
al.add(null);
al.add(false);
al.add('a');

System.out.println(al);

List<Object> subList = al.subList(1, 3); //1 2


System.out.println(subList);

// Iterator<Object> itr = al.iterator();


// while(itr.hasNext()) {
// System.out.println(itr.next());
// }

// for(int i=0; i<al.size() ; i++) {


// System.out.println(al.get(i));
// }
//
// for(Object o : al) {
// System.out.println(o);
// }

// al.add(2,"xyz");
// System.out.println(al);
//
// al.addAll(x);
// System.out.println(al);
//
// al.addAll(0,x);
// System.out.println(al);
//
// al.remove("raju");
// System.out.println(al);
//
// Integer k=123;
// al.remove(k);
// System.out.println(al);
//
// al.remove(0);
// System.out.println(al);
//
// al.removeAll(x);
// System.out.println(al);
//
// al.clear();
// System.out.println(al);

///////////////////////////////////////////////////////////////////
///

// System.out.println(al.get(0));
// System.out.println(al.contains("xraju"));
// System.out.println(al.isEmpty());
// System.out.println(al.indexOf(6123));
// System.out.println(al.lastIndexOf(123));
//
// Object[] array = al.toArray();

}
}

Day-56 (15/10/24)
LinkedList
->Best suitable for data manipulation

 Insertion order: Preserved


 Index supported: YES
 Random Access: YES
 Non Synchronized
 Duplicates : Allowed
 Null : Allowed
 Best suitable data modification
package com.mainapp;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class Launch {

public static void main(String[] args) {

LinkedList x0=new LinkedList(); //NON GENERIC

LinkedList<?> x00=new LinkedList(); //WILD CARD GENERIC : null

LinkedList<Object> x=new LinkedList<Object>(); //GENERIC


x.add("pqrs");
x.add("raju");

LinkedList<Object> ll=new LinkedList<Object>();


//->
ll.add("raju");
ll.add(123);
ll.add(123);
ll.add(null);
ll.add(false);
ll.add('a');

System.out.println(ll);

List<Object> subList = ll.subList(1, 3); //1 2


System.out.println(subList);

Iterator<Object> itr = ll.iterator();


while(itr.hasNext()) {
System.out.println(itr.next());
}

for(int i=0; i<ll.size() ; i++) {


System.out.println(ll.get(i));
}

for(Object o : ll) {
System.out.println(o);
}

ll.add(2,"xyz");
System.out.println(ll);

ll.addAll(x);
System.out.println(ll);

ll.addAll(0,x);
System.out.println(ll);

ll.remove("raju");
System.out.println(ll);

Integer k=123;
ll.remove(k);
System.out.println(ll);

ll.remove(0);
System.out.println(ll);

ll.removeAll(x);
System.out.println(ll);

ll.clear();
System.out.println(ll);

///////////////////////////////////////////////////////////////////
///

// System.out.println(al.get(0));
// System.out.println(al.contains("xraju"));
// System.out.println(al.isEmpty());
// System.out.println(al.indexOf(6123));
// System.out.println(al.lastIndexOf(123));
//
// Object[] array = al.toArray();

}
}

Vector:
 Legacy class (1.0)
 Same as ArrayList
 Insertion order: Preserved
 Index supported: YES
 Random Access: YES
 Synchronized
 Duplicates : Allowed
 Null : Allowed
 Best suitable for fast data access in thread safe env
package com.mainapp;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
public class Launch {

public static void main(String[] args) {

Vector x0=new Vector(); //NON GENERIC

Vector<?> x00=new Vector(); //WILD CARD GENERIC : null

Vector<Object> x=new Vector<Object>(); //GENERIC


x.add("pqrs");
x.add("raju");

Vector<Object> ll=new Vector<Object>();


//->
ll.add("raju");
ll.add(123);
ll.add(123);
ll.add(null);
ll.add(false);
ll.add('a');

ll.remove(0);

System.out.println(ll);

List<Object> subList = ll.subList(1, 3); //1 2


System.out.println(subList);

Iterator<Object> itr = ll.iterator();


while(itr.hasNext()) {
System.out.println(itr.next());
}

for(int i=0; i<ll.size() ; i++) {


System.out.println(ll.get(i));
}

for(Object o : ll) {
System.out.println(o);
}

ll.add(2,"xyz");
System.out.println(ll);

ll.addAll(x);
System.out.println(ll);

ll.addAll(0,x);
System.out.println(ll);

ll.remove("raju");
System.out.println(ll);

Integer k=123;
ll.remove(k);
System.out.println(ll);

ll.remove(0);
System.out.println(ll);

ll.removeAll(x);
System.out.println(ll);

ll.clear();
System.out.println(ll);

///////////////////////////////////////////////////////////////////
///

// System.out.println(al.get(0));
// System.out.println(al.contains("xraju"));
// System.out.println(al.isEmpty());
// System.out.println(al.indexOf(6123));
// System.out.println(al.lastIndexOf(123));
//
// Object[] array = al.toArray();

}
}

TASK: Employee Management System


(ADD READ DELETE UPDATE)
eid, ename, eaddress, esalary, multiple Books Names, multiple contacts
CHOOSE: LINKEDLIST
DATA BINDING: Employee {
id, name, address, salary, List, List
}

Day-57 (18/10/24)

Stack:
 Insertion order: FIRST IN LAST OUT
 Index supported: NO
 Random Access: NO
 Non Synchronized
 Duplicates : Allowed
 Null : Allowed
 USE: FILO / LIFO
package coll2;
import java.util.Stack;
public class Launch {

public static void main(String[] args) {

// Stack stack1 = new Stack();//NON GENERIC


// Stack<Object> stack2 = new Stack<Object>();//GENERIC
// Stack<?> stack3 = new Stack();//WILD CARD GENERIC

Stack<Object> stack = new Stack<Object>();


stack.push("raju");
stack.push("kaju");
stack.push("maju");

System.out.println(stack);

//System.out.println(stack.pop()); //REMOVE

//System.out.println(stack.peek()); //TOP ELEMENT

System.out.println(stack.search("raju"));

System.out.println(stack);
}
}

Queue:
 Insertion order: FIRST IN FIRST OUT
 Index supported: NO
 Random Access: NO
 Non Synchronized
 Duplicates : Allowed
 Null : Allowed
 USE: FIFO/LILO
=>The most common implementation of Queue is LinkedList or ArrayDeque
package coll2;
import java.util.ArrayDeque;
import java.util.Queue;
public class Launch {

public static void main(String[] args) {

Queue<Object> queue = new ArrayDeque<Object>();


queue.add("raju");
queue.add("kaju");
queue.add("maju");

System.out.println(queue);

//System.out.println(queue.poll());
System.out.println(queue.peek());

System.out.println(queue);

}
}

PriorityQueue
 Insertion order: BASED PRIORITY(Lowest=>Remove) : Default Natural
Sorting Ordering : Ascending
 Index supported: NO
 Random Access: NO
 Non Synchronized
 Duplicates : Allowed
 Null : Not Allowed

PriorityQueue
->Complete Binary Tree
MIN HEAP Parent<Child : bydeafult
MAX HEAP Parent>Child

Type1: Complete binary Tree


Why PriorityQueue uses complete binary tree?
Ans: because we can fetch hight priority element very
efficiently (O(1))

package coll2;
import java.util.PriorityQueue;
public class Launch {

public static void main(String[] args) {

PriorityQueue<Integer> pq = new PriorityQueue<Integer>();


pq.add(123);
pq.add(8);
pq.add(1400);
pq.add(400);
pq.add(300);
pq.add(5);
pq.add(556);
pq.add(900);
pq.add(700);

System.out.println(pq);

pq.poll();
//peek clear size

System.out.println(pq);

}
}
PriorityQueue<Integer> pq = new
PriorityQueue<Integer>(Collections.reverseOrder());//MA
X HEAP

PriorityQueue had been designed to be Generic(Data


comparison and sorting)
PriorityQueue Supports only object which is of type
Comparable(compareTo=>Comparison)
package coll2;
import java.util.PriorityQueue;
public class Launch {

public static void main(String[] args) {

PriorityQueue<Object> pq = new PriorityQueue<Object>();

// pq.add(123); //COMPARE ? ==> compareTo();===> Comparable


// pq.add(1243);
// pq.add(1223);
// pq.add(5123);

// pq.add("xdata"); //COMPARE ? ===> compareTo();====>Comparable


// pq.add("qdata");
// pq.add("datta");
// pq.add("drrata");

pq.add(new Employee()); //NO compareTo() so not allowed

System.out.println(pq);
}
}

Deque
 Insertion order: Both side of a queue
 Index supported: NO
 Random Access: NO
 Non Synchronized
 Duplicates : Allowed
 Null : Allowed

package coll2;
import java.util.ArrayDeque;
import java.util.Deque;
public class Launch {

public static void main(String[] args) {

Deque<Object> dq=new ArrayDeque<Object>();


dq.addFirst("raju");
dq.addFirst("kaju");
dq.addLast("xraju");
dq.addLast("xkaju");

System.out.println(dq);

//dq.clear();

dq.pollFirst();
dq.pollLast();

System.out.println(dq);

// dq.removeFirst();
// dq.removeLast();

System.out.println(dq.peekFirst());
System.out.println(dq.peekLast());
}
}

Day-58 (19/10/24)
HashSet:
 Insertion order: Random (HashFunction)
 Index supported: NO
 Random Access: NO
 Non Synchronized
 Duplicates : Not Allowed
 Null : Allowed

->Internally HashSet store data inside the HashTable by


using hash function
->Indexes are calculated by HashSet only with the help of
hashCode (Numeric form of Object)
->When u have unique data but order preservation is not
your concern
package com.mainapp3;
import java.util.HashSet;
public class Launch {

public static void main(String[] args) {

// HashSet hashSet1 = new HashSet(); //NON GENERIC


// HashSet<Object> hashSet2 = new HashSet<Object>(); //GENERIC
// HashSet<?> hashSet3 = new HashSet(); //WILD CARD GENERIC

HashSet<Object> hs = new HashSet<Object>();


hs.add("raju");
hs.add("kaju");
hs.add("maju");

System.out.println(hs);
//
// hs.remove("raju");
//
// System.out.println(hs);

System.out.println(hs.contains( "kaju" ));

int hashCode1 = "Aa".hashCode();


System.out.println(hashCode1);

int hashCode2 = "BB".hashCode();


System.out.println(hashCode2);

//Object

}
}

LinkedHashSet
 Insertion order: Preserved
 Index supported: NO
 Random Access: NO
 Non Synchronized
 Duplicates : Not Allowed
 Null : Allowed

->When u have unique data and u want order


preservation
->Extra operation to main order
TreeSet
 Insertion order: Ascending order
 Index supported: NO
 Random Access: NO
 Non Synchronized
 Duplicates : Not Allowed
 Null : Not Allowed
 Internal: RED BLACK TREE : complexity O(logN)
 Make it Generic while implementing
 ->When u have unique data and u want custom or
ascending order(Default)
package com.mainapp3;
import java.util.TreeSet;
public class Launch {

public static void main(String[] args) {

TreeSet<Object> hs = new TreeSet<Object>();


hs.add(435345);
hs.add(43);
hs.add(555);

System.out.println(hs);

}
}

=============================

Day-59 (20/10/24)
Wilde card Generics
package coll2;
import java.util.ArrayList;
public class Launch {

public static void main(String[] args) {

ArrayList<String> data=new ArrayList<String>();


data.add("raju");
data.add("kaju");
data.add("maju");

ArrayList<?> al=data; //FOR READ ONLY


pass(al);
}

public static void pass(ArrayList<?> al) {


for(Object o : al) {
System.out.println(o);
}
}
}

You can also create u own collection


package coll2;
import java.util.ArrayList;
public class Launch {

public static void main(String[] args) {

ArrayList<String> data=new AnamCollection<String>();


data.add("raju");
data.add("kaju");
data.add("maju");

ArrayList<?> al=data; //FOR READ ONLY


pass(al);
}

public static void pass(ArrayList<?> al) {

al.add(null);

for(Object o : al) {
System.out.println(o);
}
}
}

package coll2;
import java.util.ArrayList;
public class AnamCollection<String> extends ArrayList<String>{

@Override
public void add(int index, String element) {

if(element==null) {
throw new NotNullException("data cannot be null");
}

super.add(index, element);
}

@Override
public boolean add(String e) {

if(e==null) {
throw new NotNullException("data cannot be null");
}

return super.add(e);
}
}

package coll2;
public class NotNullException extends RuntimeException {

public NotNullException(String msg) {


super(msg);
}
}

Map Interface
->Key Value Pair
HashMap
(Key-Value)
 Insertion order: Random
 Index supported: NO
 Random Access: NO
 Non Synchronized
 Duplicates : Value can be duplicate but key must be unique
 Null : Multiple null can be store as a value but only single null is allowed for
a key
 Internal: Hashing, Hashtable TC: O(1)

package coll2;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
public class Launch {

public static void main(String[] args) {

//HashMap hashMap = new HashMap();//NON GENERIC


//HashMap<?,?> hashMap = new HashMap();//WILD CARD GENERIC

HashMap<Integer,String> hashMap = new HashMap<Integer,String>();


//->
hashMap.put(11, "raju"); //Entry Object==> Store
hashMap.put(12, "kaju");
hashMap.put(13, "maju");
hashMap.put(14, "sohan");
hashMap.put(15, "raju");
hashMap.put(15, "raju");
hashMap.put(15, "kaju");
hashMap.put(16, "raju");

hashMap.remove(11);

//Iterator
Set<Entry<Integer, String>> entrySet = hashMap.entrySet();

Iterator<Entry<Integer, String>> iterator = entrySet.iterator();


while(iterator.hasNext()) {
Entry<Integer, String> entry = iterator.next();
System.out.println(entry.getKey()+" "+entry.getValue());
}

System.out.println(hashMap);
}
}

LinkedHashMap
 Insertion order: Preserved(Key)
 Index supported: NO
 Random Access: NO
 Non Synchronized
 Duplicates : Value can be duplicate but key must be unique
 Null : Multiple null can be store as a value but only single null is allowed for
a key
 Internal: Hashing, Hashtable TC: O(1), DoublyLinkedList
 Less efficient than HashMap

package coll2;
import java.util.LinkedHashMap;
public class Launch {

public static void main(String[] args) {

LinkedHashMap<Integer,String> hashMap = new


LinkedHashMap<Integer,String>();
hashMap.put(11, "raju");
hashMap.put(12, "kaju");
hashMap.put(13, "maju");
hashMap.put(14, "sohan");
hashMap.put(16, "raju");
System.out.println(hashMap);
}
}

TreeMap
 Insertion order: Ascending(Key)/CUSTOM
 Index supported: NO
 Random Access: NO
 Non Synchronized
 Duplicates : Value can be duplicate but key must be unique
 Null : Multiple null can be store as a value but only single null is allowed for
a key
 Internal: RedBlackTree : TC:O(logN)

package coll2;
import java.util.TreeMap;
public class Launch {

public static void main(String[] args) {

TreeMap<Integer,String> hashMap = new TreeMap<Integer,String>();


hashMap.put(16, "raju");
hashMap.put(11, "raju");
hashMap.put(13, "maju");
hashMap.put(12, "kaju");
hashMap.put(14, "sohan");

System.out.println(hashMap);
}
}

Program:
package coll2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
public class Launch {
public static void main(String[] args) {

//PINCODE====>5 CARS
//Integer====>List<String>

ArrayList<String> area1 = new ArrayList<String>();


area1.add("xyz1");
area1.add("xyz2");
area1.add("xyz3");
area1.add("xyz4");
area1.add("xyz5");

ArrayList<String> area2 = new ArrayList<String>();

area2.add("qxyz1");
area2.add("qxyz2");
area2.add("qxyz3");
area2.add("qxyz4");
area2.add("qxyz5");

ArrayList<String> area3 = new ArrayList<String>();

area3.add("aqxyz1");
area3.add("aqxyz2");
area3.add("aqxyz3");
area3.add("aqxyz4");
area3.add("aqxyz5");

HashMap<Integer,List<String>> hashMap = new


HashMap<Integer,List<String>>();

hashMap.put(123456, area1);
hashMap.put(124456, area2);
hashMap.put(123666, area3);

for( Entry<Integer, List<String>> e : hashMap.entrySet())


{
System.out.println("PINCODE: "+e.getKey());
List<String> value = e.getValue();
for(String name :value) {
System.out.println(name);
}
}

System.out.println(hashMap);
}
}

Day-60 (23/10/24)
Comparable (java.lang) [compareTo()]
->It is an interface
->It is used to compare objects to maintain natural
sorting order
->Same class
CompareTo Method (int)
 Positive : Current=>right
 Negative : Current=>left
 Zero : Correct => Based on order in which u are inserting
package coll2;
import java.util.TreeSet;
public class Launch {

public static void main(String[] args) {

Employee e1 = new Employee(11, 18, "araju");


Employee e2 = new Employee(12, 19, "braju");
Employee e3 = new Employee(13, 20, "craju");
Employee e4 = new Employee(14, 21, "draju");

TreeSet<Employee> treeSet=new TreeSet<Employee>();

treeSet.add(e2); // [e2]->start
treeSet.add(e1); // [e2 e1]
treeSet.add(e3); // [e3 e2 e1]
treeSet.add(e4); // [e4 e3 e2 e1]

System.out.println(treeSet);

}
}

package coll2;

public class Employee implements Comparable<Employee> {

private int id;


private int age;
private String name;

@Override
public int compareTo(Employee o) {
System.out.println(o);
return o.id - this.id; //12-11=>POS
//12-13=>Neg
//12-14=>Neg , 13-14=>Neg
}

public Employee(int id, int age, String name) {


super();
this.id = id;
this.age = age;
this.name = name;
}

public int getId() {


return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Employee [id=" + id + ", age=" + age + ", name=" + name + "]";
}

Comparable (java.util) [compare()]


->It is an interface
->It is used to compare objects to maintain custom sorting order
->Diff class
package coll2;
import java.util.TreeSet;
public class Launch {

public static void main(String[] args) {

Employee e1 = new Employee(11, 18, "araju");


Employee e2 = new Employee(12, 19, "braju");
Employee e3 = new Employee(13, 20, "craju");
Employee e4 = new Employee(4, 21, "draju");

TreeSet<Employee> treeSet=new TreeSet<Employee>(new OrderBasedOnName());


treeSet.add(e2); // [e2]->start
treeSet.add(e1); // [e1 e2]
treeSet.add(e3); // [e3 e2 e1]
treeSet.add(e4); // [e4 e3 e2 e1]

System.out.println(treeSet);

//TreeSet<Employee> Based On Name


//TreeSet<Employee> Based On Age

}
}
package coll2;

public class Employee implements Comparable<Employee> {

private int id;


private int age;
private String name;

@Override
public int compareTo(Employee o) {
System.out.println("*****");
return this.id - o.id;

public Employee(int id, int age, String name) {


super();
this.id = id;
this.age = age;
this.name = name;
}

public int getId() {


return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Employee [id=" + id + ", age=" + age + ", name=" + name + "]";
}

package coll2;
import java.util.Comparator;

public class OrderBasedOnName implements Comparator<Employee> {

@Override
public int compare(Employee e1, Employee e2) {

return e2.getName().compareTo(e1.getName());

//braju ------compareTo---- araju


//98 97
//98-91 =>Pos

Collections
->it contains lot of static method for searching sorting
manipulation

Example: Predefined Comparator:


package coll2;
import java.util.Collections;
import java.util.TreeSet;
public class Launch {

public static void main(String[] args) {

Employee e1 = new Employee(11, 18, "araju");


Employee e2 = new Employee(12, 19, "braju");
Employee e3 = new Employee(13, 20, "craju");
Employee e4 = new Employee(4, 21, "draju");

TreeSet<Employee> treeSet=new
TreeSet<Employee>(Collections.reverseOrder());

treeSet.add(e2);
treeSet.add(e1);
treeSet.add(e3);
treeSet.add(e4);

System.out.println(treeSet);

}
}

Sorting:
package coll2;
import java.util.ArrayList;
import java.util.Collections;
public class Launch {

public static void main(String[] args) {

Employee e1 = new Employee(11, 18, "araju");


Employee e2 = new Employee(12, 19, "braju");
Employee e3 = new Employee(13, 20, "craju");
Employee e4 = new Employee(4, 21, "draju");

ArrayList<Employee> al=new ArrayList<Employee>();

al.add(e2);
al.add(e1);
al.add(e3);
al.add(e4);

Collections.sort(al);

System.out.println(al);

}
}

Other methods:
package coll2;
import java.util.ArrayList;
import java.util.Collections;
public class Launch {

public static void main(String[] args) {

ArrayList<Integer> arrayList = new ArrayList<Integer>();


arrayList.add(123);
arrayList.add(455);
arrayList.add(1);
arrayList.add(444);
arrayList.add(1);
arrayList.add(3);
arrayList.add(1);
System.out.println(arrayList);

//Collections.reverse(arrayList);
//Collections.shuffle(arrayList);

// Integer max = Collections.max(arrayList);


// System.out.println(max);
//
// Integer min = Collections.min(arrayList);
// System.out.println(min);

// int binarySearch = Collections.binarySearch(arrayList, 444);


// System.out.println(binarySearch);
//

int frequency = Collections.frequency(arrayList, 1);


System.out.println(frequency);
System.out.println(arrayList);

}
}

Day-61 (24/10/24)
File Input Output (IO) : java.io
 Variable : Temp (RAM)
 Array : Temp (RAM)
 Collection : Temp (RAM)

File IO is used to achieve Data Persistency (Permanent Storage)


->We can create a file, write, read, delete, folder create….many more

How to create a file


package com.mainapp;
import java.io.File;
import java.io.IOException;
public class Launch {

public static void main(String[] args) throws IOException {


for(int i=1 ; i<=100000 ; i++) {

File file = new File("C:\\Users\\codehunt\\Desktop\\


fileio\\abc"+i+".txt");
boolean newFile = file.createNewFile();
if(newFile)
System.out.println("File Created");
else
System.out.println("Failed to Create");

}
}
}

How to delete a file


package com.mainapp;
import java.io.File;
import java.io.IOException;
public class Launch {

public static void main(String[] args) throws IOException {

File file = new File("C:\\Users\\codehunt\\Desktop\\


fileio2\\pqrs.txt");
boolean newFile = file.delete();
if(newFile)
System.out.println("File Deleted");
else
System.out.println("Failed to Delete");

}
}

How to write a file


package com.mainapp;
import java.io.FileOutputStream;
import java.io.IOException;
public class Launch {

public static void main(String[] args) throws IOException {

String s="123";
byte[] b = s.getBytes();

FileOutputStream fos = new FileOutputStream("C:\\Users\\


codehunt\\Desktop\\fileio2\\abc.txt");
fos.write(b);

System.out.println("Data sent successfully");

}
}

How to read a file:


package com.mainapp;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class Launch {

public static void main(String[] args) throws IOException {

FileInputStream fis = new FileInputStream("C:\\Users\\codehunt\\Desktop\\


fileio2\\abc.txt");
while(true) {

int i = fis.read();
if(i==-1) {
System.out.println();
break;
}
System.out.print((char)i);

fis.close();

//Delete
System.out.println(new File("C:\\Users\\codehunt\\Desktop\\fileio2\\
abc.txt").delete());

}
}

TASK:
Day-62 (25/10/24)
->File1: this is my car->Read(this is my car) : Manipulate(this is xyz car)-
>File1(Store)
->File(“this is my car”) : FileWriting: first it will create a file and if file is
already available then it will delete all its content and then write(File
Override)

package com.mainapp;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Launch {

public static void main(String[] args) throws Exception {


FileInputStream fis = new FileInputStream("C:\\Users\\codehunt\\Desktop\\
f1\\abc.txt");
String data="";
String vowels="";

int temp=0;
while(true) {

temp=fis.read();
if(temp==-1)break;
data=data+(char)temp;

String[] split = data.split(" ");


for(int i=0 ; i<split.length ; i++) {

if(split[i].startsWith("a") || split[i].startsWith("e") ||
split[i].startsWith("i")||
split[i].startsWith("o") || split[i].startsWith("u"))
{

vowels=vowels+split[i]+" ";

}
}

FileOutputStream fos = new FileOutputStream("C:\\Users\\codehunt\\


Desktop\\f2\\pqrs.txt");
fos.write(vowels.getBytes());

System.out.println("DATA SENT SUCCESSFULLY");

fis.close();
fos.close();

}
}

Append:
package com.mainapp;
import java.io.FileOutputStream;
public class Launch {

public static void main(String[] args) throws Exception {

FileOutputStream fos = new FileOutputStream("C:\\Users\\


codehunt\\Desktop\\f2\\pqrs.txt",true);
fos.write(" kaju".getBytes());
fos.close();
}
}

Without Path: (Project Location)


package com.mainapp;
import java.io.FileOutputStream;
public class Launch {

public static void main(String[] args) throws Exception {

FileOutputStream fos = new FileOutputStream("pqrs.txt");


fos.write(" kaju".getBytes());
fos.close();

}
}

How to create a folder :


package com.mainapp;
import java.io.File;
import java.util.Scanner;
public class Launch {

public static void main(String[] args) throws Exception {

// String foldername=new Scanner(System.in).next();


//
// File file = new File("C:\\Users\\codehunt\\Desktop\\
f2\\"+foldername);
// boolean mkdir = file.mkdir();
// System.out.println(mkdir);

String foldername=new Scanner(System.in).next();

String path="C:\\Users\\codehunt\\Desktop\\
f2"+File.separator+foldername;

File file = new File(path);


boolean mkdir = file.mkdir();
System.out.println(mkdir);

}
}
BufferedInputStream and BufferedOutputStream

package com.mainapp;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
public class Launch {

public static void main(String[] args) throws Exception {

String path="C:\\Users\\codehunt\\Desktop\\
f2"+File.separator+"pqrs.txt";

FileInputStream fis = new FileInputStream(path);


BufferedInputStream bis = new BufferedInputStream(fis);
int temp=0;
while(true) {

temp=bis.read();
if(temp==-1)break;
System.out.print((char)temp);
}

bis.close();fis.close();
}
}

Program : BufferedOutputStream
package com.mainapp;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
public class Launch {

public static void main(String[] args) throws Exception {

String path="C:\\Users\\codehunt\\Desktop\\
f2"+File.separator+"pqrs.txt";

FileOutputStream fos = new FileOutputStream(path);


BufferedOutputStream bos = new BufferedOutputStream(fos);

bos.write("mouse".getBytes());

bos.close();
fos.close();

}
}

Day-63 (25/10/24)
Serialization and Deserialization
-> Serialization: Process of converting an Object to a byte stream
-> Deserialization : Then reconstruct the object from that byte stream
package com.mainapp;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Launch {

public static void main(String[] args) throws Exception {

//Serialization

Demo demo1 = new Demo(11, "raju", "mi", 1000); //Serialization(Market)

FileOutputStream fos = new FileOutputStream("pqrs.txt"); //Byte Oriented

ObjectOutputStream oos = new ObjectOutputStream(fos);


oos.writeObject(demo1);

Demo demo = new Demo(12, "kaju", "csk", 2000); //Serialization(Market)


oos.writeObject(demo);

System.out.println("DONE");

//Deserialization

FileInputStream fis = new FileInputStream("pqrs.txt");


ObjectInputStream ois = new ObjectInputStream(fis);

Demo d1 = (Demo) ois.readObject();


System.out.println(d1.toString());

Demo d2 = (Demo) ois.readObject();


System.out.println(d2.toString());
ois.close();
fis.close();

}
}

File Copy Paste / Cut Paste


package com.mainapp;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Launch {

public static void main(String[] args) throws Exception {

String source="C:\\Users\\codehunt\\Desktop\\f1\\abc.mp4";
FileInputStream fis=new FileInputStream(source);
byte[] b = fis.readAllBytes();

String destination="C:\\Users\\codehunt\\Desktop\\f2\\abc.mp4";
FileOutputStream fos = new FileOutputStream(destination);
fos.write(b);

fis.close();
fos.close();

new File(source).delete();
}
}

You might also like