-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnew22.txt
813 lines (605 loc) · 21.4 KB
/
new22.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
Unsigned right shift: -1>>>2 = 1073741823
Binary value of -1 is: 11111111111111111111111111111111
shift bits 2 positions to right and add 0's to the left: 001111111111111111111111111111
Result is: 1073741823
The short circuit AND is a minimal evaluation operator i.e. the right side is not evaluated when left side result of expression is false, the final result becomes false.
The short circuit OR is a minimal evaluation operator i.e. the right side is not evaluated when left side result of expression is true, the final result becomes true.
byte -> short -> int -> long -> float -> double
char -> int
-------------------------------------------------> Implicit Typecasting
<---------------------------------------------Explicit Typecasting
do -while loop
import java.util.Scanner;
class Account {
public static void main(String[] args) {
double balance = 0, minbal = 500, depositAmt = 0;
Scanner sc = new Scanner(System.in);
do {
System.out.println("Enter the amount to be deposit");
depositAmt = sc.nextInt();
} while(depositAmt < minbal);
balance = depositAmt;
System.out.println("Your deposit was successful");
}
}
while loop
import java.util.Scanner;
class Account {
public static void main(String[] args) {
double balance = 0, minbal = 500, depositAmt = 0;
Scanner sc = new Scanner(System.in);
while(depositAmt < minbal) {
System.out.println("Enter the amount to be deposit");
depositAmt = sc.nextInt();
}
balance = depositAmt;
System.out.println("Your deposit was successful");
}
}
Multi Dimensional Array
// Multi-dimensional arrays are arrays of arrays. The two dimensional
array can be termed as a physical table with rows and columns.
int marks[][] = new int [2][3]; // Declares a 2-D array with 2 rows and 3 columns
Bank bank[][] = new Bank[2][3];
int marks[][] = new int[2][]; // While instantiating a 2-D array, specifying the size of the 2nd dimension is not mandatory.
Bank bank[][] = new Bank[2][];
marks[0] = new int[2]; // First row of the multidimensional array will have 2 columns.
bank[0] = new Bank[2];
------------------------------------------------
For Each Loop
for(int i: arr) { // The iteration in the loop happens automatically. The value is assigned to
//variable i from the array in every iteration of the loop.
balance += deposit; // Loop will repeat the statements in its body till the last element is reached in the array.
balance -= withdrawal;
interest = balance * rateOfInterest;
balance += interest;
System.out.println("The interest for the month " + i + " is " + interest);
}
}
----------------------------------------------------
Enum Example
enum Designation{
CEO(2),GeneralManager(4),RegionalManager(20),BranchManager(30);
private int noofEmployees;
Designation(int noofEmployees)
{
this.noofEmployees=noofEmployees;
}
public int getNoofEmployees(){
return noofEmployees;
}
}
class Bank{
public void reportees(Designation designation){
System.out.println(designation.getNoofEmployees());
}
public static void main(String[] args){
Bank bank=new Bank();
bank.reportees(Designation.CEO);
}
}
Enum going over all the values of Enum
enum DAY{
SUNDAY(1),MONDAY(2),TUESDAY(3),WEDNESDAY(4),THURSDAY(5),FRIDAY(6),SATURDAY(7);
private int value;
private Day(int value){
this.value=value;
}
public int getValue(){
return this.value;
}
}
public class UserInterface{
public static void main(string[] args){
/printing all constants of an enum
for(Day day:Day.values())
System.out.println("Day:"+day.name()+" Value:"+day.getValue());
}
}
final can be used in 3 scenarios
Before a variable
A final variable's value once initialized can't be changed, i.e. it is a constant private final int Tenure = 20;
Before a method
A final method cannot be overridden in a subclass
public final void calculateEMI(){...}
Before a class
A final class cannot be sub classed.(i.e. you cannot extend the class)
public final class Loan{...}
Static Check
class Account{
static int minbalance; //class variable
static{
minbalance = 500; // static block
}
public static int getMinimumBalance(){
return minbalance; //can't use instance variable in static method
//and block
}
public static void main (String[] args) {
System.out.println("The value.." + getMinimumBalance());
}
}
-----------------------------------
Variable Arguments
public int reward(double...fixedDeposit){ //Variable argument
double sum=0;
int rewardPoint=0;
for(double deposit:fixedDeposit){
sum=sum+deposit;
}
-----------------
SET
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
class DuplicateUsers {
public static void main(String[] args) {
List<User> userList = new ArrayList<User>();
userList.add(new User("Max", "fgc123", "[email protected]"));
userList.add(new User("Mike", "hdgsh@", "[email protected]"));
userList.add(new User("Mojo", "asdf45", "[email protected]"));
userList.add(new User("Michael", "oiort543", "[email protected]"));
userList.add(new User("John", "ucantseeme", "[email protected]"));
userList.add(new User("Moby", "fgc123", "[email protected]"));
Set<User> userSet = new LinkedHashSet<>();
userSet.addAll(userList);
for(User user : userSet)
System.out.println(user);
}
}
class User {
String username;
String password;
String email;
public User(String username, String password, String email) {
super();
this.username = username;
this.password = password;
this.email = email;
}
@Override
public String toString() {
return this.username + " : " + this.email;
}
}
---------------
Maps
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
class MapExample {
public static void main(String[] args) {
Map<String, String> map=new HashMap<>();
map.put("P1", "Lemon Cake");
map.put("P2", "Ratatouille");
map.put("P3", "Bertie Bott's Beans");
//Key cannot be duplicated, the value will be overriden
map.put("P3", "BlueBerry Cake");
//Checking if map contains the specific key
if(map.containsKey("P1")){
System.out.println("P1 found");
}
else
System.out.println("P1 not found");
//Checking if map contains the specific value
if(map.containsValue("Ratatouille"))
System.out.println("Ratatouille is found");
else
System.out.println("Ratatouille not found");
//Checking the size of the map
System.out.println("Map size:"+map.size());
//Retrieving the value of a map using key
System.out.println("The value of P3 is "+map.get("P3"));
//Retrieving all the keys of a map
Set<String> keySet = map.keySet();
//Display the entries in the map
System.out.println("ItemId ItemName");
System.out.println("=========================");
for(String key : keySet){
System.out.println(key+" "+map.get(key));
}
System.out.println("=========================");
//Another way of displaying the entries in the map
System.out.println("ItemId ItemName");
System.out.println("=========================");
Set<Entry<String, String>> entrySet = map.entrySet();
for(Entry<String, String> entry : entrySet){
System.out.println(entry.getKey()+" "+entry.getValue());
}
System.out.println("=========================");
//Removing one item from the map using its key
map.remove("P3");
//Displaying only the values from the map
System.out.println("ItemName in the map are");
System.out.println("=========================");
Collection<String> values = map.values();
for(String val : values){
System.out.println(val);
}
System.out.println("=========================");
//Removing all the items from the map
map.clear();
//Checking the map is empty or not
if(map.isEmpty()){
System.out.println("No items found");
}
}
}
--------------------------------
Collections
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class CollectionsDemo {
public static void main(String[] args) {
List<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(5);
list1.add(10);
list1.add(50);
list1.add(15);
list1.add(20);
list1.add(1);
Collections.sort(list1); //sorting the collection
System.out.println(list1);
Collections.reverse(list1); //reversing the collection
System.out.println(list1);
Integer max = Collections.max(list1); //finding the maximum in the collection
System.out.println(max);
Integer min = Collections.min(list1); //finding minimum in a collection
System.out.println(min);
Integer freq = Collections.frequency(list1, 1); //finding the frequency of an element in a collection
System.out.println(freq);
Collections.swap(list1, 1, 3); //swapping two elements in a collection
System.out.println(list1);
Collections.shuffle(list1); //shuffling the elements in a collection
System.out.println(list1);
}
}
---------------------------
List
import java.util.ArrayList;
import java.util.List;
class ListExample {
public static void main(String[] args) {
List<String> orders = new ArrayList<String>();
orders.add("Tortilla");
orders.add("Sandwich");
orders.add("Fried rice");
orders.add("Pasta");
orders.add("Burger");
orders.add("Pizza");
orders.add("Pasta");
orders.add("Burger");
// Check whether orders contain any item
if (orders.isEmpty()) {
System.out.println("No orders available!!");
}
// Display the number of orders in the list
System.out.println("No Of Orders: " + orders.size());
List<String> newOrders = new ArrayList<String>();
newOrders.add("Tortilla");
newOrders.add("Cutlet");
newOrders.add("Fried Egg");
// Adding this newOrders list into the existing orders
orders.addAll(newOrders);
// Removing "Burger" item from the orders
orders.remove("Burger");
// Removing first item from the orders
orders.remove(0);
// Display all orders
System.out.println("The items available in the order are: ");
System.out.println("========================================");
for (String order : orders) {
System.out.println(order);
}
System.out.println("========================================");
// Checking whether Pasta is ordered or not
if (orders.contains("Pasta")) {
System.out.println("Pasta is ordered already!!!");
} else {
System.out.println("No Pasta ordered!!");
}
// Converting list to array
Object[] ordersArray = orders.toArray();
// Deleting all the items from the orders
orders.clear();
System.out.println(orders.isEmpty());
}
}
-------------------------------
ABSTRACT
abstract class Branch{
abstract public boolean validatePhotoProof(String proof);
abstract public boolean validateAddressProof(String proof);
public void openAccount(String photoProof,String addressProof,int amount){
if(amount>=1000){
if(validateAddressProof(addressProof) && validatePhotoProof(photoProof)){
System.out.println("Account opened");
}
else{
System.out.println("cannot open account");
}
}
else{
System.out.println("cannot open account");
}
}
}
class MumbaiBranch extends Branch{
public boolean validatePhotoProof(String proof){
if(proof.equalsIgnoreCase("pan card")){
return true;
}
return false;
}
public boolean validateAddressProof(String proof){
if(proof.equalsIgnoreCase("ration card")){
return true;
}
return false;
}
}
class Execute{
public static void main(String[] args){
Branch mumbaiBranch=new MumbaiBranch();
mumbaiBranch.openAccount("pan card","ration card",2000);
}
}
----------------------------------------------
INTERFACE
interface IBankNew{
boolean applyforCreditCard(Customer customer);
}
interface IBank extends IBankNew{
int CAUTION_MONEY = 2000;
String createAccount(Customer customer);
double issueVehicleLoan(String vehicleType, Customer customer);
double issueHouseLoan(Customer customer);
double issueGoldLoan(Customer customer);
}
class Customer {
private String name;
private String customerId;
public String getName() {
return name;
}
public void setName(String name) {
this.name=name;
}
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId= customerId;
}
}
class MumbaiBranch implements IBank {
public String createAccount(Customer customer){
return "Acc12345";
}
public double issueVehicleLoan(String vehicleType,Customer customer){
if(vehicleType.equals("bike")) {
return 100000;
}
else {
return 500000;
}
}
public double issueHouseLoan(Customer customer){
return 200000;
}
public double issueGoldLoan(Customer customer){
return 500000;
}
public boolean applyforCreditCard(Customer customer){
return true;
}
}
class Execute{
public static void main(String[] args){
IBank bank=new MumbaiBranch();
Customer customer = new Customer();
customer.setCustomerId("cust1001");
customer.setName("Ajay");
String accountNumber = bank.createAccount(customer);
System.out.println("Account number is..." +accountNumber);
double gloan = bank.issueGoldLoan(customer);
System.out.println("Gold loan amount is..." +gloan);
double hloan = bank.issueHouseLoan(customer);
System.out.println("House loan amount is..." +hloan);
double vloan = bank.issueVehicleLoan("bike", customer);
System.out.println("Vehicle loan amount is..." +vloan);
System.out.println("Caution money is..." +IBank.CAUTION_MONEY);
IBankNew bank1 = new MumbaiBranch();
boolean credit = bank1.applyforCreditCard(customer);
System.out.println("Credit card request.." + credit);
}
}
========================================
INNER CLASS
class Manager { // Outer Class
private class Grade { // Inner Class
private char grade;
private char calculateGrade(String employeeid, int point) {
if (isEmployeeExists(employeeid)) {
if (point < 100 && point >= 90) {
grade = 'A';
} else if (point < 90 && point >= 80) {
grade = 'B';
} else {
grade = 'C';
}
}
return grade;
}
// Check if the employee id exists or not
private boolean isEmployeeExists(String employeeId) {
// check from database or file system
return true;
}
}
public char CheckEmployeeID(String employeeId, int point) {
Grade grade = new Grade();
return grade.calculateGrade(employeeId,point);
}
}
class Execute {
public static void main (String[] args) {
Manager manager = new Manager();
String employeeId = "I1001";
char gradePoint = manager.CheckEmployeeID(employeeId, 80);
System.out.println("The grade for " + employeeId + " is " + gradePoint);
}
}
==================================
STRING BUFFER
class StringBufferDemo{
public static void main(String[] args){
String firstName="Sachin";
String lastName="Tendulkar";
String fullName=firstName+lastName;
//'+'operator concatenates the string but creates a new object in the heap memory as sting is immutable
System.out.println(fullName);
StringBuffer sb=new StringBuffer(firstName);
String fName=sb.append(lastName).toString();//toString method converts StringBuffer to String
//StringBuffer is mutable, it appends to a single object
System.out.println(fName);
}
}
========================================
STRING BUILDER
// Java code to illustrate StringBuilder
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
// create a StringBuilder object
// usind StringBuilder() constructor
StringBuilder str
= new StringBuilder();
str.append("GFG");
// print string
System.out.println("String = "
+ str.toString());
// create a StringBuilder object
// usind StringBuilder(CharSequence) constructor
StringBuilder str1
= new StringBuilder("AAAABBBCCCC");
// print string
System.out.println("String1 = "
+ str1.toString());
// create a StringBuilder object
// usind StringBuilder(capacity) constructor
StringBuilder str2
= new StringBuilder(10);
// print string
System.out.println("String2 capacity = "
+ str2.capacity());
// create a StringBuilder object
// usind StringBuilder(String) constructor
StringBuilder str3
= new StringBuilder(str1);
// print string
System.out.println("String3 = "
+ str3.toString());
}
}
============================================
fLOAT FORMATTING
String strDouble = String.format("%.2f", 2.00023);
System.out.println(strDouble); // print 2.00
DecimalFormat df = new DecimalFormat("#.##");
String formatted = df.format(2.00023);
System.out.println(formatted); //prints 2
===============================================
java se : core java products
java ee : distrubuted products based on se
java se:
Development tools
compiler (javac)
java application launcher(java)
Java runtime Environment
java standard package
Runtime libraries
Step 1: Open command prompt
Step 2: Copy the path of your JDK folder
Step 3: Use the command to set path set JAVA_HOME=**paste your jdk path**
Step 4: Verify it by using the command: echo %JAVA_HOME%
Step 5: Use the command: set PATH=%JAVA_HOME%\bin
Step 6: Verify it by using the command: echo %PATH%
Source -> javac -> ByteCode(.class) -> jvm [Class Loader, ByteCode Verifier, [Interpreter, JIT compiler,] Runtime]
Primitive[Boolean ,Numeric]
Boolean[boolean]
Numeric[Character,Integral]
Character[char]
Integral[Integer, Floating point]
Integer[byte,short,int,long,flaot,double]
Floating point[float,double]
Non premitive => stores the memory address
premitive => stores the value
int 2^31
flaot 2^63 -> 63-1
Scanner sc = new Scanner(System.in);
Map< String,Integer> hm = new HashMap< String,Integer>();
hm.put("a", new Integer(100));
hm.put("b", new Integer(200));
hm.put("c", new Integer(300));
hm.put("d", new Integer(400));
// Returns Set view
Set< Map.Entry< String,Integer> > st = hm.entrySet();
for (Map.Entry< String,Integer> me:st)
{
System.out.print(me.getKey()+":");
System.out.println(me.getValue());
}
capitalCities.remove("England");
capitalCities.keySet()
capitalCities.values()
int[] array = list.stream().mapToInt(i->i).toArray();
int pos =arr.indexOf(3);
https://justpaste.it/edit/32324002/6497cbaa10dcc7f9
https://jpst.it/1XjCy
https://justpaste.it/3f9j0
enum Designation{
CEO(2),GeneralManager(4),RegionalManager(20),BranchManager(30);
private int noofEmployees;
Designation(int noofEmployees)
{
this.noofEmployees=noofEmployees;
}
public int getNoofEmployees(){
return noofEmployees;
}
}
class Bank{
public void reportees(Designation designation){
System.out.println(designation.getNoofEmployees());
}
public static void main(String[] args){
Bank bank=new Bank();
bank.reportees(Designation.CEO);
}
}
enum DAY{
SUNDAY(1),MONDAY(2),TUESDAY(3),WEDNESDAY(4),THURSDAY(5),FRIDAY(6),SATURDAY(7);
private int value;
private Day(int value){
this.value=value;
}
public int getValue(){
return this.value;
}
}
public class UserInterface{
public static void main(string[] args){
/printing all constants of an enum
for(Day day:Day.values())
System.out.println("Day:"+day.name()+" Value:"+day.getValue());
}
}