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