Core Java
Core Java
Day-1 (9/7/24)
What is Java?
Java is a platform and a programming language
What is Programming Language?
b.Assembly Language(1949)
->First useful programming language which consist human readable
commands ( MNEMONICS )
->Easier than Machine Language
->Machine Friendly
->Still Complex language
Day-3 (12/7/24)
History of Java
Before Java C and C++ was very famous
Problem: Both are Platform Dependent Programming Languages
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
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
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
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
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
Day-10 (26/7/24)
double v6=1983.67679212343456561;
System.out.println(v6);
char v7='M';
boolean v8=true;
}
}
Day-11 (29/7/24)
package firstpro;
import java.util.Scanner;
public class Launch {
float v5=scan.nextFloat();
double v6=scan.nextDouble();
char v7=scan.next().charAt(0);
boolean v8=scan.nextBoolean();
}
}
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) {
}
}
}
}
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
*
*/
/*
* USER : pin
* 1234->pune
* 3456->banglore
* 9898->bhopal
* Not exist
*/
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");
// }
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();
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
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)
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)
// 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
// 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
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 {
int result=myClass.m3();
System.out.println("MAIN:="+result);
result=myClass.m4(10, 20);
System.out.println("MAIN:="+result);
}
}
package firstpro;
public class MyClass {
//Parameter No Return
// int a=10,b=20;
// return a+b;
return 10;
}
//Parameter Return
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
package com.methods;
public class Recursion {
// 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 x=100;
byte b=(byte)x;
System.out.println(b);
float f=14.77f;
byte b1=(byte) f;
System.out.println(b1);
int k=100;
char c=(char)k;
System.out.println(c);
}
}
Day-20 (12/8/24)
Before Java
Java History
Java Features
Java Arch
Data types
Control statement
Method
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
Blueprint: CAR
->BMW--------------->LONDON
->MAHINDRA------->MUMBAI
->TATA--------------->AHMADABAD
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
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
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 {
// 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
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
423 43 54 43
53 64 24 65
64 646 35 75
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 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
Output:
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:
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
package databind;
public class Launch {
public static void main(String[] args) {
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.
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]
========================================================
==========
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
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
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)
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 ( ~ )
Day-35 (6/9/24)
Inheritance
Types of Inheritance
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");
}
}
Day-38 (11/9/24)
STATIC KEYWORD
->it is used for memory management (save memory)
->variable, method, block, nested class
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%)
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 {
package thiskey;
public class Gpay extends PaymentGateway {
@Override
public void checkBal() {
}
@Override
public void sendMoney() {
}
}
package thiskey;
public class Paytm extends PaymentGateway{
@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) {
}
}
package thiskey;
public abstract class PaymentGateway {
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 {
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
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 {
}
}
package com.mainapp;
import java.util.Scanner;
public class Calculator {
} 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
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
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 {
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() {
if(name.equalsIgnoreCase("raju")) {
five();
}
else if(name.equalsIgnoreCase("kaju")) {
seven();
}
else {
eleven();
}
}
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 {
t1.start();
t2.start();
}
}
package com.mainapp;
@Override
public void run() {
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;
@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();
}
}
}
}
t1.start();
t2.start();
t3.start();
}
}
package com.mainapp;
public class Table implements Runnable {
@Override
public void run() {
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 {
// 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);
package com.mainapp;
public class Database1 extends Thread {
@Override
public void run() {
package com.mainapp;
public class Database2 extends Thread {
@Override
public void run() {
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 {
card1.setName("CARD1");
card2.setName("CARD2");
card1.start();
card2.start();
card1.join();
card2.join();
account.get();
}
}
package com.mainapp;
public class Card extends Thread {
//CARD1 CARD2
@Override
public void run() {
for(int i=1;i<=100000;i++) {
account.deduct(2,name );
}
}
}
package com.mainapp;
public class Account extends Thread {
this.bal=this.bal-bal;
System.out.println("DEBIT SUCCESSFULLY"+cardName);
Day-52 (5/10/24)
SYNCHRONIZED BLOCK : custom scope
package com.mainapp;
public class Launch {
card1.setName("CARD1");
card2.setName("CARD2");
card1.start();
card2.start();
card1.join();
card2.join();
account.get();
}
}
package com.mainapp;
public class Card extends Thread {
//CARD1 CARD2
@Override
public void run() {
for(int i=1;i<=100000;i++) {
account.change();
}
}
}
package com.mainapp;
public class Account extends Thread {
xyz=xyz.append("a"); //CARD1
synchronized (this) {
//CRITICAL CODE
change++;
}
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 {
resource1.setName("raju");
resource2.setName("kaju");
resource1.start();
resource2.start();
}
}
package com.mainapp;
@Override
public void run() {
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();
}
}
}
}
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();
}
}
}
}
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
u1.setName("raju");
u2.setName("kaju");
u1.start();
u2.start();
}
}
package com.mainapp2;
public class User extends Thread {
@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 {
while(messageSent==true) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
messageSent=true;
notify();
}
while(messageSent==false) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
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) {
u1.setName("raju");
u2.setName("kaju");
u3.setName("maju");
u1.start();
u2.start();
u3.start();
}
}
package com.mainapp2;
@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 {
//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();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
messageSent=true;
notifyAll();
}
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();
}
}
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
//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);
}
}
//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 {
//NON GENERIC
ArrayList al=new ArrayList();
al.add("raju");
al.add(123); //Autoboxing
al.add(false);
al.add('a');
System.out.println(al);
System.out.println(al2);
System.out.println(al3);
}
}
package com.mainapp;
import java.util.ArrayList;
public class Launch {
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 {
System.out.println(al);
// 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
System.out.println(ll);
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 {
ll.remove(0);
System.out.println(ll);
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();
}
}
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 {
System.out.println(stack);
//System.out.println(stack.pop()); //REMOVE
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 {
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
package coll2;
import java.util.PriorityQueue;
public class Launch {
System.out.println(pq);
pq.poll();
//peek clear size
System.out.println(pq);
}
}
PriorityQueue<Integer> pq = new
PriorityQueue<Integer>(Collections.reverseOrder());//MA
X HEAP
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 {
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
System.out.println(hs);
//
// hs.remove("raju");
//
// System.out.println(hs);
//Object
}
}
LinkedHashSet
Insertion order: Preserved
Index supported: NO
Random Access: NO
Non Synchronized
Duplicates : Not Allowed
Null : Allowed
System.out.println(hs);
}
}
=============================
Day-59 (20/10/24)
Wilde card Generics
package coll2;
import java.util.ArrayList;
public class Launch {
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 {
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 {
hashMap.remove(11);
//Iterator
Set<Entry<Integer, String>> entrySet = hashMap.entrySet();
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 {
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 {
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>
area2.add("qxyz1");
area2.add("qxyz2");
area2.add("qxyz3");
area2.add("qxyz4");
area2.add("qxyz5");
area3.add("aqxyz1");
area3.add("aqxyz2");
area3.add("aqxyz3");
area3.add("aqxyz4");
area3.add("aqxyz5");
hashMap.put(123456, area1);
hashMap.put(124456, area2);
hashMap.put(123666, area3);
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 {
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;
@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
}
System.out.println(treeSet);
}
}
package coll2;
@Override
public int compareTo(Employee o) {
System.out.println("*****");
return this.id - o.id;
package coll2;
import java.util.Comparator;
@Override
public int compare(Employee e1, Employee e2) {
return e2.getName().compareTo(e1.getName());
Collections
->it contains lot of static method for searching sorting
manipulation
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 {
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 {
//Collections.reverse(arrayList);
//Collections.shuffle(arrayList);
}
}
Day-61 (24/10/24)
File Input Output (IO) : java.io
Variable : Temp (RAM)
Array : Temp (RAM)
Collection : Temp (RAM)
}
}
}
}
}
String s="123";
byte[] b = s.getBytes();
}
}
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 {
int temp=0;
while(true) {
temp=fis.read();
if(temp==-1)break;
data=data+(char)temp;
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]+" ";
}
}
fis.close();
fos.close();
}
}
Append:
package com.mainapp;
import java.io.FileOutputStream;
public class Launch {
}
}
String path="C:\\Users\\codehunt\\Desktop\\
f2"+File.separator+foldername;
}
}
BufferedInputStream and BufferedOutputStream
package com.mainapp;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
public class Launch {
String path="C:\\Users\\codehunt\\Desktop\\
f2"+File.separator+"pqrs.txt";
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 {
String path="C:\\Users\\codehunt\\Desktop\\
f2"+File.separator+"pqrs.txt";
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 {
//Serialization
System.out.println("DONE");
//Deserialization
}
}
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();
}
}