· 6 years ago · Sep 16, 2019, 10:52 AM
1
2Topic 3:
3Java Variables
4
5A variable is a container which holds the value while the java program is executed. A variable is assigned with a datatype.
6Variable is a name of memory location. There are three types of variables in java: local, instance and static.
7There are two types of data types in java: primitive and non-primitive.
8
91. int data=50;//Here data is variable
10
11There are three types of variables in java:
12local variable
13instance variable
14static variable
15Example to understand the types of variables in java
161. Class A{
172. int data=50;//instance variable
183. static int m=100;//static variable
194. void method(){
205. int n=90;//loca variable
216. }
227. }//end of clas
23
24
25Java Variable Example: Add Two Numbers
261. class Simple{
272. public static void main(String[] args){
283. int a=10;
294. int b=10;
305. int c=a+b;
316. System.out.println(c);
327. }}
33
34Output:
3520
36
37
38
39
40Java Variable Example: Widening
411. class Simple{
422. public static void main(String[] args){
433. int a=10;
44
454. float f=a;
465. System.out.println(a);
476. System.out.println(f);
487. }}
49
50
51Output:
5210
5310.0
54
55
56
57
58Java Variable Example: Narrowing (Typecasting)
591. class Simple{
602. public static void main(String[] args){
613. float f=10.5f;
624. //int a=f;//Compile time error
635. int a=(int)f;
646. System.out.println(f);
657. System.out.println(a);
668. }}
67Output:
6810.5
6910
70
71
72
73Java Variable Example: Overflow
741. class Simple{
752. public static void main(String[] args){
763. //Overflow
774. int a=130;
785. byte b=(byte)a;
796. System.out.println(a);
807. System.out.println(b);
818. }}
82Output:
83130
84-126
85
86
87Java Variable Example: Adding Lower Type
881. class Simple{
892. public static void main(String[] args){
903. byte a=10;
914. byte b=10;
925. //byte c=a+b;//Compile Time Error: because a+b=20 will be int
936. byte c=(byte)(a+b);
947. System.out.println(c);
958. }}
96Output:
9720
98
99//**************************************************************************//
100Topic 2:
101Data Types in Java
102Data types specify the different sizes and values that can be stored in the variable. There are two types of data types in Java:
1031. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
1042. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
105
106There are 8 types of primitive data types:
107boolean data type
108byte data type
109char data type
110short data type
111int data type
112long data type
113float data type
114double data type
115
116
117
118Data Type
119Default Value
120Default
121size
122boolean
123false
1241 bit
125char
126'\u0000'
1272 byte
128byte
1290
1301 byte
131short
1320
1332 byte
134int
1350
1364 byte
137long
1380L
1398 byte
140float
1410.0f
1424 byte
143double
1440.0d
1458 byte
146
147Topic 3:
148Unicode System
149 international standard character encoding that is capable of representing most of the world's written languages.
150
151Why java uses Unicode System?
152Before Unicode, there were many language standards:
153ASCII (American Standard Code for Information Interchange) for the United States.
154ISO 8859-1 for Western European Language.
155KOI-8 for Russian.
156GB18030 and BIG-5 for chinese, and so on.
157Problem
158This caused two problems:
1591. A particular code value corresponds to different letters in the various language standards.
1602. The encodings for languages with large character sets have variable length.Some common characters are encoded as single bytes, other require two or more byte.
161
162
163Operators in java
164Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc.
165
166
167
168Java Operator Precedence
169Operator Type
170Category
171Precedence
172Unary
173postfix
174expr++ expr--
175
176prefix
177++expr --expr +expr -expr ~ !
178Arithmetic
179multiplicative
180* / %
181
182additive
183+ -
184Shift
185shift
186<< >> >>>
187Relational
188comparison
189< > <= >= instanceof
190
191equality
192== !=
193Bitwise
194bitwise AND
195&
196
197bitwise exclusive OR
198^
199
200bitwise inclusive OR
201|
202Logical
203logical AND
204&&
205
206logical OR
207||
208Ternary
209ternary
210? :
211Assignment
212assignment
213= += -= *= /= %= &= ^= |= <<= >>= >>>=
214
215
216
217Java Keywords
218
219Java keywords are also known as reserved words. Keywords are particular words which acts as a key to a code. These are predefined words by Java so it cannot be used as a variable or object name.
220
221List of Java Keywords
222 A list of Java keywords or reserved words are given below:
2231. abstract: Java abstract keyword is used to declare abstract class. Abstract class can provide the implementation of interface. It can have abstract and non-abstract methods.
2242. boolean: Java boolean keyword is used to declare a variable as a boolean type. It can hold True and False values only.
2253. break: Java break keyword is used to break loop or switch statement. It breaks the current flow of the program at specified condition.
2264. byte: Java byte keyword is used to declare a variable that can hold an 8-bit data values.
2275. case: Java case keyword is used to with the switch statements to mark blocks of text.
2286. catch: Java catch keyword is used to catch the exceptions generated by try statements. It must be used after the try block only.
2297. char: Java char keyword is used to declare a variable that can hold unsigned 16-bit Unicode characters
2308. class: Java class keyword is used to declare a class.
2319. continue: Java continue keyword is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition.
23210. default: Java default keyword is used to specify the default block of code in a switch statement.
23311. do: Java do keyword is used in control statement to declare a loop. It can iterate a part of the program several times.
23412. double: Java double keyword is used to declare a variable that can hold a 64-bit floating-point numbers.
23513. else: Java else keyword is used to indicate the alternative branches in an if statement.
23614. enum: Java enum keyword is used to define a fixed set of constants. Enum constructors are always private or default.
23715. extends: Java extends keyword is used to indicate that a class is derived from another class or interface.
23816. final: Java final keyword is used to indicate that a variable holds a constant value. It is applied with a variable. It is used to restrict the user.
23917. finally: Java finally keyword indicates a block of code in a try-catch structure. This block is always executed whether exception is handled or not.
24018. float: Java float keyword is used to declare a variable that can hold a 32-bit floating-point number.
24119. for: Java for keyword is used to start a for loop. It is used to execute a set of instructions/functions repeatedly when some conditions become true. If the number of iteration is fixed, it is recommended to use for loop.
24220. if: Java if keyword tests the condition. It executes the if block if condition is true.
24321. implements: Java implements keyword is used to implement an interface.
24422. import: Java import keyword makes classes and interfaces available and accessible to the current source code.
24523. instanceof: Java instanceof keyword is used to test whether the object is an instance of the specified class or implements an interface.
24624. int: Java int keyword is used to declare a variable that can hold a 32-bit signed integer.
24725. interface: Java interface keyword is used to declare an interface. It can have only abstract methods.
24826. long: Java long keyword is used to declare a variable that can hold a 64-bit integer.
24927. native: Java native keyword is used to specify that a method is implemented in native code using JNI (Java Native Interface).
25028. new: Java new keyword is used to create new objects.
25129. null: Java null keyword is used to indicate that a reference does not refer to anything. It removes the garbage value.
25230. package: Java package keyword is used to declare a Java package that includes the classes.
25331. private: Java private keyword is an access modifier. It is used to indicate that a method or variable may be accessed only in the class in which it is declared.
25432. protected: Java protected keyword is an access modifier. It can be accessible within package and outside the package but through inheritance only. It can't be applied on the class.
25533. public: Java public keyword is an access modifier. It is used to indicate that an item is accessible anywhere. It has the widest scope among all other modifiers.
25634. return: Java return keyword is used to return from a method when its execution is complete.
25735. short: Java short keyword is used to declare a variable that can hold a 16-bit integer.
25836. static: Java static keyword is used to indicate that a variable or method is a class method. The static keyword in Java is used for memory management mainly.
25937. strictfp: Java strictfp is used to restrict the floating-point calculations to ensure portability.
26038. super: Java super keyword is a reference variable that is used to refer parent class object. It can be used to invoke immediate parent class method.
26139. switch: The Java switch keyword contains a switch statement that executes code based on test value. The switch statement tests the equality of a variable against multiple values.
26240. synchronized: Java synchronized keyword is used to specify the critical sections or methods in multithreaded code.
26341. this: Java this keyword can be used to refer the current object in a method or constructor.
26442. throw: The Java throw keyword is used to explicitly throw an exception. The throw keyword is mainly used to throw custom exception. It is followed by an instance.
26543. throws: The Java throws keyword is used to declare an exception. Checked exception can be propagated with throws.
26644. transient: Java transient keyword is used in serialization. If you define any data member as transient, it will not be serialized.
26745. try: Java try keyword is used to start a block of code that will be tested for exceptions. The try block must be followed by either catch or finally block.
26846. void: Java void keyword is used to specify that a method does not have a return value.
26947. volatile: Java volatile keyword is used to indicate that a variable may change asynchronously.
27048. while: Java while keyword is used to start a while loop. This loop iterates a part of the program several times. If the number of iteration is not fixed, it is recommended to use while loop.
271
272
273
274//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
275Control Statements
276Java If-else Statement
277
278The Java if statement is used to test the condition. It checks boolean condition: true or false. There are various types of if statement in java.
279if statement
280if-else statement
281if-else-if ladder
282nested if statement
283Java if Statement
284if(condition){
2851. //code to be executed
2862. }
287
288
289//Java Program to demonstate the use of if statement.
290public class IfExample {
2911. public static void main(String[] args) {
2922. int age=20;
2933. if(age>18){
2944. System.out.print("Age is greater than 18");
2955. }
2966. }
2977. }
298Output:
299Age is greater than 18
300
301Java if-else Statement
302
303Syntax:
304f(condition){
305//code if condition is true
306}else{
307//code if condition is false
308}
309
310
311
312public class IfElseExample {
313public static void main(String[] args) {
314 int number=13;
315 if(number%2==0){
316 System.out.println("even number");
317 }else{
318 System.out.println("odd number");
319 }
320}
321}
322
323Output:
324odd number
325
326
327
328
329Leap Year Example:
330
331public class LeapYearExample {
332public static void main(String[] args) {
333 int year=2020;
334 if(((year % 4 ==0) && (year % 100 !=0)) || (year % 400==0)){
335 System.out.println("LEAP YEAR");
336 }
337 else{
338 System.out.println("COMMON YEAR");
339 }
340}
341}
342
343
344Output:
345LEAP YEAR
346
347
348Using Ternary Operator
349We can also use ternary operator (? :) to perform the task of if...else statement. It is a shorthand way to check the condition. If the condition is true, the result of ? is returned. But, if the condition is false, the result of : is returned.
350Example:
351public class IfElseTernaryExample {
352public static void main(String[] args) {
353 int number=13;
354 //Using ternary operator
355 String output=(number%2==0)?"even number":"odd number";
356 System.out.println(output);
357}
358}
359Output:
360odd number
361
362Java if-else-if ladder Statement
363
364Syntax:
365
366if(condition1){
367//code to be executed if condition1 is true
368}else if(condition2){
369//code to be executed if condition2 is true
370}
371else if(condition3){
372//code to be executed if condition3 is true
373}
374...
375else{
376//code to be executed if all the conditions are false
377}
378
379Example:
380
381//Java Program to demonstrate the use of If else-if ladder.
382//It is a program of grading system for fail, D grade, C grade, B grade, A grade and A+.
383public class IfElseIfExample {
384public static void main(String[] args) {
385 int marks=65;
386
387 if(marks<50){
388 System.out.println("fail");
389 }
390 else if(marks>=50 && marks<60){
391 System.out.println("D grade");
392 }
393 else if(marks>=60 && marks<70){
394 System.out.println("C grade");
395 }
396 else if(marks>=70 && marks<80){
397 System.out.println("B grade");
398 }
399 else if(marks>=80 && marks<90){
400 System.out.println("A grade");
401 }else if(marks>=90 && marks<100){
402 System.out.println("A+ grade");
403 }else{
404 System.out.println("Invalid!");
405 }
406}
407}
408Output:
409C grade
410
411
412Program to check POSITIVE, NEGATIVE or ZERO:
413
414public class PositiveNegativeExample {
415public static void main(String[] args) {
416 int number=-13;
417 if(number>0){
418 System.out.println("POSITIVE");
419 }else if(number<0){
420 System.out.println("NEGATIVE");
421 }else{
422 System.out.println("ZERO");
423 }
424}
425}
426
427Output:
428NEGATIVE
429
430
431Java Nested if statement
432
433Syntax:
434
435if(condition){
436 //code to be executed
437 if(condition){
438 //code to be executed
439 }
440}
441Example 1
442//Java Program to demonstrate the use of Nested If Statement.
443public class JavaNestedIfExample {
444public static void main(String[] args) {
445 //Creating two variables for age and weight
446 int age=20;
447 int weight=80;
448 //applying condition on age and weight
449 if(age>=18){
450 if(weight>50){
451 System.out.println("You are eligible to donate blood");
452 }
453 }
454}}
455
456
457Output:
458
459You are eligible to donate blood
460
461Example 2:
462
463//Java Program to demonstrate the use of Nested If Statement.
464public class JavaNestedIfExample2 {
465public static void main(String[] args) {
466 //Creating two variables for age and weight
467 int age=25;
468 int weight=48;
469 //applying condition on age and weight
470 if(age>=18){
471 if(weight>50){
472 System.out.println("You are eligible to donate blood");
473 } else{
474 System.out.println("You are not eligible to donate blood");
475 }
476 } else{
477 System.out.println("Age must be greater than 18");
478 }
479} }
480Test it Now
481Output:
482
483You are not eligible to donate blood
484
485
486Java Switch Statement
487
488The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement. The switch statement works with byte, short, int, long, enum types, String and some wrapper types like Byte, Short, Int, and Long. Since Java 7, you can use strings in the switch statement.
489In other words, the switch statement tests the equality of a variable against multiple values.
490
491Syntax:
492
493switch(expression){
494case value1:
495 //code to be executed;
496 break; //optional
497case value2:
498 //code to be executed;
499 break; //optional
500......
501default:
502 code to be executed if all cases are not matched;
503}
504
505Example:
506
507public class SwitchExample {
508public static void main(String[] args) {
509 //Declaring a variable for switch expression
510 int number=20;
511 //Switch expression
512 switch(number){
513 //Case statements
514 case 10: System.out.println("10");
515 break;
516 case 20: System.out.println("20");
517 break;
518 case 30: System.out.println("30");
519 break;
520 //Default case statement
521 default:System.out.println("Not in 10, 20 or 30");
522 }
523}
524}
525Test it Now
526Output:
527
52820
529
530Finding Month Example:
531
532//Java Program to demonstrate the example of Switch statement
533//where we are printing month name for the given number
534public class SwitchMonthExample {
535public static void main(String[] args) {
536 //Specifying month number
537 int month=7;
538 String monthString="";
539 //Switch statement
540 switch(month){
541 //case statements within the switch block
542 case 1: monthString="1 - January";
543 break;
544 case 2: monthString="2 - February";
545 break;
546 case 3: monthString="3 - March";
547 break;
548 case 4: monthString="4 - April";
549 break;
550 case 5: monthString="5 - May";
551 break;
552 case 6: monthString="6 - June";
553 break;
554 case 7: monthString="7 - July";
555 break;
556 case 8: monthString="8 - August";
557 break;
558 case 9: monthString="9 - September";
559 break;
560 case 10: monthString="10 - October";
561 break;
562 case 11: monthString="11 - November";
563 break;
564 case 12: monthString="12 - December";
565 break;
566 default:System.out.println("Invalid Month!");
567 }
568 //Printing month of the given number
569 System.out.println(monthString);
570}
571}
572Test it Now
573Output:
574
5757 – July
576
577Program to check Vowel or Consonant:
578
579If the character is A, E, I, O, or U, it is vowel otherwise consonant. It is not case-sensitive.
580
581public class SwitchVowelExample {
582public static void main(String[] args) {
583 char ch='O';
584 switch(ch)
585 {
586 case 'a':
587 System.out.println("Vowel");
588 break;
589 case 'e':
590 System.out.println("Vowel");
591 break;
592 case 'i':
593 System.out.println("Vowel");
594 break;
595 case 'o':
596 System.out.println("Vowel");
597 break;
598 case 'u':
599 System.out.println("Vowel");
600 break;
601 case 'A':
602 System.out.println("Vowel");
603 break;
604 case 'E':
605 System.out.println("Vowel");
606 break;
607 case 'I':
608 System.out.println("Vowel");
609 break;
610 case 'O':
611 System.out.println("Vowel");
612 break;
613 case 'U':
614 System.out.println("Vowel");
615 break;
616 default:
617 System.out.println("Consonant");
618 }
619}
620}
621Output:
622
62320
624
625
626Java Switch Statement is fall-through
627The Java switch statement is fall-through. It means it executes all statements after the first match if a break statement is not present.
628
629Example:
630
631//Java Switch Example where we are omitting the
632//break statement
633public class SwitchExample2 {
634public static void main(String[] args) {
635 int number=20;
636 //switch expression with int value
637 switch(number){
638 //switch cases without break statements
639 case 10: System.out.println("10");
640 case 20: System.out.println("20");
641 case 30: System.out.println("30");
642 default:System.out.println("Not in 10, 20 or 30");
643 }
644}
645}
646
647
648
649
650
651Java Nested Switch Statement
652We can use switch statement inside other switch statement in Java. It is known as nested switch statement.
653
654Example:
655
656//Java Program to demonstrate the use of Java Nested Switch
657public class NestedSwitchExample {
658 public static void main(String args[])
659 {
660 //C - CSE, E - ECE, M - Mechanical
661 char branch = 'C';
662 int collegeYear = 4;
663 switch( collegeYear )
664 {
665 case 1:
666 System.out.println("English, Maths, Science");
667 break;
668 case 2:
669 switch( branch )
670 {
671 case 'C':
672 System.out.println("Operating System, Java, Data Structure");
673 break;
674 case 'E':
675 System.out.println("Micro processors, Logic switching theory");
676 break;
677 case 'M':
678 System.out.println("Drawing, Manufacturing Machines");
679 break;
680 }
681 break;
682 case 3:
683 switch( branch )
684 {
685 case 'C':
686 System.out.println("Computer Organization, MultiMedia");
687 break;
688 case 'E':
689 System.out.println("Fundamentals of Logic Design, Microelectronics");
690 break;
691 case 'M':
692 System.out.println("Internal Combustion Engines, Mechanical Vibration");
693 break;
694 }
695 break;
696 case 4:
697 switch( branch )
698 {
699 case 'C':
700 System.out.println("Data Communication and Networks, MultiMedia");
701 break;
702 case 'E':
703 System.out.println("Embedded System, Image Processing");
704 break;
705 case 'M':
706 System.out.println("Production Technology, Thermal Engineering");
707 break;
708 }
709 break;
710 }
711 }
712}
713Test it Now
714Output:
715
716Data Communication and Networks, MultiMedi
717
718Java Enum in Switch Statement
719Java allows us to use enum in switch statement.
720
721Example:
722
723//Java Program to demonstrate the use of Enum
724//in switch statement
725public class JavaSwitchEnumExample {
726 public enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat }
727 public static void main(String args[])
728 {
729 Day[] DayNow = Day.values();
730 for (Day Now : DayNow)
731 {
732 switch (Now)
733 {
734 case Sun:
735 System.out.println("Sunday");
736 break;
737 case Mon:
738 System.out.println("Monday");
739 break;
740 case Tue:
741 System.out.println("Tuesday");
742 break;
743 case Wed:
744 System.out.println("Wednesday");
745 break;
746 case Thu:
747 System.out.println("Thursday");
748 break;
749 case Fri:
750 System.out.println("Friday");
751 break;
752 case Sat:
753 System.out.println("Saturday");
754 break;
755 }
756 }
757 }
758}
759Test it Now
760Output:
761
762Sunday
763Monday
764Twesday
765Wednesday
766Thursday
767Friday
768Saturday
769
770
771Java Wrapper in Switch Statement
772Java allows us to use four wrapper classes: Byte, Short, Integer and Long in switch statement.
773
774Example:
775
776//Java Program to demonstrate the use of Wrapper class
777//in switch statement
778public class WrapperInSwitchCaseExample {
779 public static void main(String args[])
780 {
781 Integer age = 18;
782 switch (age)
783 {
784 case (16):
785 System.out.println("You are under 18.");
786 break;
787 case (18):
788 System.out.println("You are eligible for vote.");
789 break;
790 case (65):
791 System.out.println("You are senior citizen.");
792 break;
793 default:
794 System.out.println("Please give the valid age.");
795 break;
796 }
797 }
798}
799Test it Now
800Output:
801
802You are eligible for vote.
803
804
805
806////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
807Loops in Java
808In programming languages, loops are used to execute a set of instructions/functions repeatedly when some conditions become true. There are three types of loops in java.
809for loop
810while loop
811do-while loop
812Java For Loop vs While Loop vs Do While Loop
813Comparison
814for loop
815while loop
816do while loop
817Introduction
818The Java for loop is a control flow statement that iterates a part of the programs multiple times.
819The Java while loop is a control flow statement that executes a part of the programs repeatedly on the basis of given boolean condition.
820The Java do while loop is a control flow statement that executes a part of the programs at least once and the further execution depends upon the given boolean condition.
821When to use
822If the number of iteration is fixed, it is recommended to use for loop.
823If the number of iteration is not fixed, it is recommended to use while loop.
824If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use the do-while loop.
825Syntax
826for(init;condition;incr/decr){
827// code to be executed
828}
829while(condition){
830//code to be executed
831}
832do{
833//code to be executed
834}while(condition);
835Example
836//for loop
837for(int i=1;i<=10;i++){
838System.out.println(i);
839}
840//while loop
841int i=1;
842while(i<=10){
843System.out.println(i);
844i++;
845}
846//do-while loop
847int i=1;
848do{
849System.out.println(i);
850i++;
851}while(i<=10);
852Syntax for infinitive loop
853for(;;){
854//code to be executed
855}
856while(true){
857//code to be executed
858}
859do{
860//code to be executed
861}while(true);
862
863
864Java For Loop
865The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop.
866There are three types of for loops in java.
867Simple For Loop
868For-each or Enhanced For Loop
869Labeled For Loop
870Java Simple For Loop
871
872Syntax:
873
874for(initialization;condition;incr/decr){
875//statement or code to be executed
876}
877Example:
878
879//Java Program to demonstrate the example of for loop
880//which prints table of 1
881public class ForExample {
882public static void main(String[] args) {
883 //Code of Java for loop
884 for(int i=1;i<=10;i++){
885 System.out.println(i);
886 }
887}
888}
889
890Output:
891
8921
8932
8943
8954
8965
8976
8987
8998
9009
90110
902Java Nested For Loop
903
904If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes completely whenever outer loop executes.
905
906Example:
907
908public class NestedForExample {
909public static void main(String[] args) {
910//loop of i
911for(int i=1;i<=3;i++){
912//loop of j
913for(int j=1;j<=3;j++){
914 System.out.println(i+" "+j);
915}//end of i
916}//end of j
917}
918}
919Output:
9201 1
9211 2
9221 3
9232 1
9242 2
9252 3
9263 1
9273 2
9283 3
929
930Java for-each Loop
931
932Syntax:
933
934for(Type var:array){
935//code to be executed
936}
937Example:
938
939//Java For-each loop example which prints the
940//elements of the array
941public class ForEachExample {
942public static void main(String[] args) {
943 //Declaring an array
944 int arr[]={12,23,44,56,78};
945 //Printing array using for-each loop
946 for(int i:arr){
947 System.out.println(i);
948 }
949}
950}
951
952Output:
953
95412
95523
95644
95756
95878
959
960Java Labeled For Loop
961
962We can have a name of each Java for loop. To do so, we use label before the for loop. It is useful if we have nested for loop so that we can break/continue specific for loop.
963Usually, break and continue keywords breaks/continues the innermost for loop only.
964
965Syntax:
966
967labelname:
968for(initialization;condition;incr/decr){
969//code to be executed
970}
971Example:
972
973//A Java program to demonstrate the use of labeled for loop
974public class LabeledForExample {
975public static void main(String[] args) {
976 //Using Label for outer and for loop
977 aa:
978 for(int i=1;i<=3;i++){
979 bb:
980 for(int j=1;j<=3;j++){
981 if(i==2&&j==2){
982 break aa;
983 }
984 System.out.println(i+" "+j);
985 }
986 }
987}
988}
989
990Java Infinitive For Loop
991
992f you use two semicolons ;; in the for loop, it will be infinitive for loop.
993
994Syntax:
995
996for(;;){
997//code to be executed
998}
999Example:
1000
1001//Java program to demonstrate the use of infinite for loop
1002//which prints an statement
1003public class ForExample {
1004public static void main(String[] args) {
1005 //Using no condition in for loop
1006 for(;;){
1007 System.out.println("infinitive loop");
1008 }
1009}
1010}
1011Output:
1012
1013infinitive loop
1014infinitive loop
1015infinitive loop
1016infinitive loop
1017infinitive loop
1018ctrl+c
1019
1020Java While Loop
1021The Java while loop is used to iterate a part of the program several times. If the number of iteration is not fixed, it is recommended to use while loop.
1022Syntax:
1023while(condition){
1024//code to be executed
1025}
1026
1027Example:
1028
1029public class WhileExample {
1030public static void main(String[] args) {
1031 int i=1;
1032 while(i<=10){
1033 System.out.println(i);
1034 i++;
1035 }
1036}
1037}
1038Output:
1039
10401
10412
10423
10434
10445
10456
10467
10478
10489
104910
1050
1051Java do-while Loop
1052The Java do-while loop is used to iterate a part of the program several times. If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use do-while loop.
1053The Java do-while loop is executed at least once because condition is checked after loop body.
1054Syntax:
1055
1056do{
1057//code to be executed
1058}while(condition);
1059
1060Example:
1061
1062public class DoWhileExample {
1063public static void main(String[] args) {
1064 int i=1;
1065 do{
1066 System.out.println(i);
1067 i++;
1068 }while(i<=10);
1069}
1070}
1071Test it Now
1072Output:
1073
10741
10752
10763
10774
10785
10796
10807
10818
10829
108310
1084
1085Java Break Statement
1086When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.
1087The Java break is used to break loop or switch statement. It breaks the current flow of the program at specified condition. In case of inner loop, it breaks only inner loop.
1088We can use Java break statement in all types of loops such as for loop, while loop and do-while loop.
1089Syntax:
1090
1091jump-statement;
1092break;
1093Java Break Statement with Loop
1094Example:
1095
1096//Java Program to demonstrate the use of break statement
1097//inside the for loop.
1098public class BreakExample {
1099public static void main(String[] args) {
1100 //using for loop
1101 for(int i=1;i<=10;i++){
1102 if(i==5){
1103 //breaking the loop
1104 break;
1105 }
1106 System.out.println(i);
1107 }
1108}
1109}
1110Output:
1111
11121
11132
11143
11154
1116
1117Java Continue Statement
1118The continue statement is used in loop control structure when you need to jump to the next iteration of the loop immediately. It can be used with for loop or while loop.
1119The Java continue statement is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition. In case of an inner loop, it continues the inner loop only.
1120We can use Java continue statement in all types of loops such as for loop, while loop and do-while loop.
1121
1122Syntax:
1123
1124jump-statement;
1125continue;
1126Java Continue Statement Example
1127Example:
1128
1129//Java Program to demonstrate the use of continue statement
1130//inside the for loop.
1131public class ContinueExample {
1132public static void main(String[] args) {
1133 //for loop
1134 for(int i=1;i<=10;i++){
1135 if(i==5){
1136 //using continue statement
1137 continue;//it will skip the rest statement
1138 }
1139 System.out.println(i);
1140 }
1141}
1142}
1143Test it Now
1144Output:
1145
11461
11472
11483
11494
11506
11517
11528
11539
115410
1155
1156Java Comments
1157The java comments are statements that are not executed by the compiler and interpreter. The comments can be used to provide information or explanation about the variable, method, class or any statement. It can also be used to hide program code for specific time.
1158Types of Java Comments
1159There are 3 types of comments in java.
11601. Single Line Comment
11612. Multi Line Comment
11623. Documentation Comment
1163
11641) Java Single Line Comment
1165The single line comment is used to comment only one line.
1166Syntax:
1167//This is single line comment
1168Example:
1169
1170public class CommentExample1 {
1171public static void main(String[] args) {
1172 int i=10;//Here, i is a variable
1173 System.out.println(i);
1174}
1175}
1176Output:
117710
1178
11792) Java Multi Line Comment
1180The multi line comment is used to comment multiple lines of code.
1181Syntax:
1182/*
1183This
1184is
1185multi line
1186comment
1187*/
1188Example:
1189
1190public class CommentExample2 {
1191public static void main(String[] args) {
1192/* Let's declare and
1193 print variable in java. */
1194 int i=10;
1195 System.out.println(i);
1196}
1197}
1198Output:
119910
12003) Java Documentation Comment
1201The documentation comment is used to create documentation API. To create documentation API, you need to use javadoc tool.
1202Syntax:
1203/**
1204This
1205is
1206documentation
1207comment
1208*/
1209Example:
1210
1211/** The Calculator class provides methods to get addition and subtraction of given 2 numbers.*/
1212public class Calculator {
1213/** The add() method returns addition of given numbers.*/
1214public static int add(int a, int b){return a+b;}
1215/** The sub() method returns subtraction of given numbers.*/
1216public static int sub(int a, int b){return a-b;}
1217}
1218
1219/////////////////////////////////////////////////////////////////
1220Java Object Class
1221
1222Java OOPs Concepts
1223
1224In this page, we will learn about the basics of OOPs. Object-Oriented Programming is a paradigm that provides many concepts, such as inheritance, data binding, polymorphism, etc.
1225
1226The main aim of object-oriented programming is to implement real-world entities, for example, object, classes, abstraction, inheritance, polymorphism, etc.
1227OOPs (Object-Oriented Programming System)
1228Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies software development and maintenance by providing some concepts:
1229Object
1230Class
1231Inheritance
1232Polymorphism
1233Abstraction
1234Encapsulation
1235Apart from these concepts, there are some other terms which are used in Object-Oriented design:
1236Coupling
1237Cohesion
1238Association
1239Aggregation
1240Composition
1241Object
1242Any entity that has state and behavior is known as an object. For example, a chair, pen, table, keyboard, bike, etc. It can be physical or logical.
1243Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors like wagging the tail, barking, eating, etc.
1244Class
1245Collection of objects is called class. It is a logical entity.
1246A class can also be defined as a blueprint from which you can create an individual object. Class doesn't consume any space.
1247
1248Class
1249Collection of objects is called class. It is a logical entity.
1250A class can also be defined as a blueprint from which you can create an individual object. Class doesn't consume any space.
1251Inheritance
1252When one object acquires all the properties and behaviors of a parent object, it is known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
1253Polymorphism
1254If one task is performed in different ways, it is known as polymorphism. For example: to convince the customer differently, to draw something, for example, shape, triangle, rectangle, etc.
1255In Java, we use method overloading and method overriding to achieve polymorphism.
1256Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc.
1257Abstraction
1258Hiding internal details and showing functionality is known as abstraction. For example phone call, we don't know the internal processing.
1259In Java, we use abstract class and interface to achieve abstraction.
1260Encapsulation
1261Binding (or wrapping) code and data together into a single unit are known as encapsulation. For example, a capsule, it is wrapped with different medicines.
1262A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.
1263Coupling
1264Coupling refers to the knowledge or information or dependency of another class. It arises when classes are aware of each other. If a class has the details information of another class, there is strong coupling. In Java, we use private, protected, and public modifiers to display the visibility level of a class, method, and field. You can use interfaces for the weaker coupling because there is no concrete implementation.
1265Cohesion
1266Cohesion refers to the level of a component which performs a single well-defined task. A single well-defined task is done by a highly cohesive method. The weakly cohesive method will split the task into separate parts. The java.io package is a highly cohesive package because it has I/O related classes and interface. However, the java.util package is a weakly cohesive package because it has unrelated classes and interfaces.
1267Association
1268Association represents the relationship between the objects. Here, one object can be associated with one object or many objects. There can be four types of association between the objects:
1269One to One
1270One to Many
1271Many to One, and
1272Many to Many
1273Let's understand the relationship with real-time examples. For example, One country can have one prime minister (one to one), and a prime minister can have many ministers (one to many). Also, many MP's can have one prime minister (many to one), and many ministers can have many departments (many to many).
1274Association can be undirectional or bidirectional.
1275Aggregation
1276Aggregation is a way to achieve Association. Aggregation represents the relationship where one object contains other objects as a part of its state. It represents the weak relationship between objects. It is also termed as a has-a relationship in Java. Like, inheritance represents the is-a relationship. It is another way to reuse objects.
1277Composition
1278The composition is also a way to achieve Association. The composition represents the relationship where one object contains other objects as a part of its state. There is a strong relationship between the containing object and the dependent object. It is the state where containing objects do not have an independent existence. If you delete the parent object, all the child objects will be deleted automatically.
1279
1280What is the difference between an object-oriented programming language and object-based programming language?
1281Object-based programming language follows all the features of OOPs except Inheritance. JavaScript and VBScript are examples of object-based programming languages.
1282
1283
1284Java Naming conventions
1285Java naming convention is a rule to follow as you decide what to name your identifiers such as class, package, variable, constant, method, etc.
1286But, it is not forced to follow. So, it is known as convention not rule. These conventions are suggested by several Java communities such as Sun Microsystems and Netscape.
1287All the classes, interfaces, packages, methods and fields of Java programming language are given according to the Java naming convention. If you fail to follow these conventions, it may generate confusion or erroneous code.
1288
1289
1290Advantage of naming conventions in java
1291By using standard Java naming conventions, you make your code easier to read for yourself and other programmers. Readability of Java program is very important. It indicates that less time is spent to figure out what the code does.
1292The following are the key rules that must be followed by every identifier:
1293The name must not contain any white spaces.
1294The name should not start with special characters like & (ampersand), $ (dollar), _ (underscore).
1295Let's see some other rules that should be followed by identifiers.
1296Class
1297It should start with the uppercase letter.
1298It should be a noun such as Color, Button, System, Thread, etc.
1299Use appropriate words, instead of acronyms.
1300Example: -
1301public class Employee
1302{
1303//code snippet
1304}
1305Interface
1306It should start with the uppercase letter.
1307It should be an adjective such as Runnable, Remote, ActionListener.
1308Use appropriate words, instead of acronyms.
1309Example: -
1310interface Printable
1311{
1312//code snippet
1313}
1314Method
1315It should start with lowercase letter.
1316It should be a verb such as main(), print(), println().
1317If the name contains multiple words, start it with a lowercase letter followed by an uppercase letter such as actionPerformed().
1318Example:-
1319 class Employee
1320{
1321//method
1322void draw()
1323{
1324//code snippet
1325}
1326}
1327Variable
1328It should start with a lowercase letter such as id, name.
1329It should not start with the special characters like & (ampersand), $ (dollar), _ (underscore).
1330If the name contains multiple words, start it with the lowercase letter followed by an uppercase letter such as firstName, lastName.
1331Avoid using one-character variables such as x, y, z.
1332Example :-
1333 class Employee
1334{
1335//variable
1336int id;
1337//code snippet
1338}
1339Package
1340It should be a lowercase letter such as java, lang.
1341If the name contains multiple words, it should be separated by dots (.) such as java.util, java.lang.
1342Example :-
1343
1344package com.javatpoint; //package
1345class Employee
1346{
1347//code snippet
1348}
1349Constant
1350It should be in uppercase letters such as RED, YELLOW.
1351If the name contains multiple words, it should be separated by an underscore(_) such as MAX_PRIORITY.
1352It may contain digits but not as the first letter.
1353Example :-
1354 class Employee
1355{
1356//constant
1357 static final int MIN_AGE = 18;
1358//code snippet
1359}
1360CamelCase in java naming conventions
1361Java follows camel-case syntax for naming the class, interface, method, and variable.
1362If the name is combined with two words, the second word will start with uppercase letter always such as actionPerformed(), firstName, ActionEvent, ActionListener, etc.
1363
1364#Objects and Classes in Java
1365In this page, we will learn about Java objects and classes. In object-oriented programming technique, we design a program using objects and classes.
1366An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical entity only.
1367
1368What is an object in Java
1369
1370An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car, etc. It can be physical or logical (tangible and intangible). The example of an intangible object is the banking system.
1371An object has three characteristics:
1372State: represents the data (value) of an object.
1373Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.
1374Identity: An object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. However, it is used internally by the JVM to identify each object uniquely.
1375
1376For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used to write, so writing is its behavior.
1377An object is an instance of a class. A class is a template or blueprint from which objects are created. So, an object is the instance(result) of a class.
1378Object Definitions:
1379An object is a real-world entity.
1380An object is a runtime entity.
1381The object is an entity which has state and behavior.
1382The object is an instance of a class.
1383
1384What is a class in Java
1385A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It is a logical entity. It can't be physical.
1386A class in Java can contain:
1387Fields
1388Methods
1389Constructors
1390Blocks
1391Nested class and interface
1392
1393Syntax to declare a class:
1394class <class_name>{
1395 field;
1396 method;
1397}
1398
1399Instance variable in Java
1400A variable which is created inside the class but outside the method is known as an instance variable. Instance variable doesn't get memory at compile time. It gets memory at runtime when an object or instance is created. That is why it is known as an instance variable.
1401
1402Method in Java
1403In Java, a method is like a function which is used to expose the behavior of an object.
1404Advantage of Method
1405Code Reusability
1406Code Optimization
1407
1408new keyword in Java
1409The new keyword is used to allocate memory at runtime. All objects get memory in Heap memory area.
1410
1411Object and Class Example: main within the class
1412In this example, we have created a Student class which has two data members id and name. We are creating the object of the Student class by new keyword and printing the object's value.
1413Here, we are creating a main() method inside the class.
1414File: Student.java
1415//Java Program to illustrate how to define a class and fields
1416//Defining a Student class.
1417class Student{
1418 //defining fields
1419 int id;//field or data member or instance variable
1420 String name;
1421 //creating main method inside the Student class
1422 public static void main(String args[]){
1423 //Creating an object or instance
1424 Student s1=new Student();//creating an object of Student
1425 //Printing values of the object
1426 System.out.println(s1.id);//accessing member through reference variable
1427 System.out.println(s1.name);
1428 }
1429}
1430
1431Output:
14320
1433null
1434Object and Class Example: main outside the class
1435In real time development, we create classes and use it from another class. It is a better approach than previous one. Let's see a simple example, where we are having main() method in another class.
1436We can have multiple classes in different Java files or single Java file. If you define multiple classes in a single Java source file, it is a good idea to save the file name with the class name which has main() method.
1437File: TestStudent1.java
1438//Java Program to demonstrate having the main method in
1439//another class
1440//Creating Student class.
1441class Student{
1442 int id;
1443 String name;
1444}
1445//Creating another class TestStudent1 which contains the main method
1446class TestStudent1{
1447 public static void main(String args[]){
1448 Student s1=new Student();
1449 System.out.println(s1.id);
1450 System.out.println(s1.name);
1451 }
1452}
1453
1454Output:
14550
1456null
14573 Ways to initialize object
1458There are 3 ways to initialize object in Java.
14591. By reference variable
14602. By method
14613. By constructor
14621) Object and Class Example: Initialization through reference
1463Initializing an object means storing data into the object. Let's see a simple example where we are going to initialize the object through a reference variable.
1464File: TestStudent2.java
1465class Student{
1466 int id;
1467 String name;
1468}
1469class TestStudent2{
1470 public static void main(String args[]){
1471 Student s1=new Student();
1472 s1.id=101;
1473 s1.name="Sonoo";
1474 System.out.println(s1.id+" "+s1.name);//printing members with a white space
1475 }
1476}
1477
1478Output:
1479101 Sonoo
1480We can also create multiple objects and store information in it through reference variable.
1481File: TestStudent3.java
1482class Student{
1483 int id;
1484 String name;
1485}
1486class TestStudent3{
1487 public static void main(String args[]){
1488 //Creating objects
1489 Student s1=new Student();
1490 Student s2=new Student();
1491 //Initializing objects
1492 s1.id=101;
1493 s1.name="Sonoo";
1494 s2.id=102;
1495 s2.name="Amit";
1496 //Printing data
1497 System.out.println(s1.id+" "+s1.name);
1498 System.out.println(s2.id+" "+s2.name);
1499 }
1500}
1501
1502Output:
1503101 Sonoo
1504102 Amit
15052) Object and Class Example: Initialization through method
1506In this example, we are creating the two objects of Student class and initializing the value to these objects by invoking the insertRecord method. Here, we are displaying the state (data) of the objects by invoking the displayInformation() method.
1507File: TestStudent4.java
1508class Student{
1509 int rollno;
1510 String name;
1511 void insertRecord(int r, String n){
1512 rollno=r;
1513 name=n;
1514 }
1515 void displayInformation(){System.out.println(rollno+" "+name);}
1516}
1517class TestStudent4{
1518 public static void main(String args[]){
1519 Student s1=new Student();
1520 Student s2=new Student();
1521 s1.insertRecord(111,"Karan");
1522 s2.insertRecord(222,"Aryan");
1523 s1.displayInformation();
1524 s2.displayInformation();
1525 }
1526}
1527
1528Output:
1529111 Karan
1530222 Aryan
1531
1532As you can see in the above figure, object gets the memory in heap memory area. The reference variable refers to the object allocated in the heap memory area. Here, s1 and s2 both are reference variables that refer to the objects allocated in memory.
1533
15343) Object and Class Example: Initialization through a constructor
1535We will learn about constructors in Java later.
1536
1537Object and Class Example: Employee
1538Let's see an example where we are maintaining records of employees.
1539File: TestEmployee.java
1540class Employee{
1541 int id;
1542 String name;
1543 float salary;
1544 void insert(int i, String n, float s) {
1545 id=i;
1546 name=n;
1547 salary=s;
1548 }
1549 void display(){System.out.println(id+" "+name+" "+salary);}
1550}
1551public class TestEmployee {
1552public static void main(String[] args) {
1553 Employee e1=new Employee();
1554 Employee e2=new Employee();
1555 Employee e3=new Employee();
1556 e1.insert(101,"ajeet",45000);
1557 e2.insert(102,"irfan",25000);
1558 e3.insert(103,"nakul",55000);
1559 e1.display();
1560 e2.display();
1561 e3.display();
1562}
1563}
1564
1565Output:
1566101 ajeet 45000.0
1567102 irfan 25000.0
1568103 nakul 55000.0
1569Object and Class Example: Rectangle
1570There is given another example that maintains the records of Rectangle class.
1571File: TestRectangle1.java
1572class Rectangle{
1573 int length;
1574 int width;
1575 void insert(int l, int w){
1576 length=l;
1577 width=w;
1578 }
1579 void calculateArea(){System.out.println(length*width);}
1580}
1581class TestRectangle1{
1582 public static void main(String args[]){
1583 Rectangle r1=new Rectangle();
1584 Rectangle r2=new Rectangle();
1585 r1.insert(11,5);
1586 r2.insert(3,15);
1587 r1.calculateArea();
1588 r2.calculateArea();
1589}
1590}
1591
1592Output:
159355
159445
1595What are the different ways to create an object in Java?
1596There are many ways to create an object in java. They are:
1597By new keyword
1598By newInstance() method
1599By clone() method
1600By deserialization
1601By factory method etc.
1602We will learn these ways to create object later.
1603
1604Anonymous object
1605Anonymous simply means nameless. An object which has no reference is known as an anonymous object. It can be used at the time of object creation only.
1606If you have to use an object only once, an anonymous object is a good approach. For example:
1607new Calculation();//anonymous object
1608Calling method through a reference:
1609Calculation c=new Calculation();
1610c.fact(5);
1611Calling method through an anonymous object
1612new Calculation().fact(5);
1613Let's see the full example of an anonymous object in Java.
1614class Calculation{
1615 void fact(int n){
1616 int fact=1;
1617 for(int i=1;i<=n;i++){
1618 fact=fact*i;
1619 }
1620 System.out.println("factorial is "+fact);
1621}
1622public static void main(String args[]){
1623 new Calculation().fact(5);//calling method with anonymous object
1624}
1625}
1626Output:
1627Factorial is 120
1628Creating multiple objects by one type only
1629We can create multiple objects by one type only as we do in case of primitives.
1630Initialization of primitive variables:
1631int a=10, b=20;
1632Initialization of refernce variables:
1633Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects
1634Let's see the example:
1635//Java Program to illustrate the use of Rectangle class which
1636//has length and width data members
1637class Rectangle{
1638 int length;
1639 int width;
1640 void insert(int l,int w){
1641 length=l;
1642 width=w;
1643 }
1644 void calculateArea(){System.out.println(length*width);}
1645}
1646class TestRectangle2{
1647 public static void main(String args[]){
1648 Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
1649 r1.insert(11,5);
1650 r2.insert(3,15);
1651 r1.calculateArea();
1652 r2.calculateArea();
1653}
1654}
1655
1656Output:
165755
165845
1659Real World Example: Account
1660File: TestAccount.java
1661//Java Program to demonstrate the working of a banking-system
1662//where we deposit and withdraw amount from our account.
1663//Creating an Account class which has deposit() and withdraw() methods
1664class Account{
1665int acc_no;
1666String name;
1667float amount;
1668//Method to initialize object
1669void insert(int a,String n,float amt){
1670acc_no=a;
1671name=n;
1672amount=amt;
1673}
1674//deposit method
1675void deposit(float amt){
1676amount=amount+amt;
1677System.out.println(amt+" deposited");
1678}
1679//withdraw method
1680void withdraw(float amt){
1681if(amount<amt){
1682System.out.println("Insufficient Balance");
1683}else{
1684amount=amount-amt;
1685System.out.println(amt+" withdrawn");
1686}
1687}
1688//method to check the balance of the account
1689void checkBalance(){System.out.println("Balance is: "+amount);}
1690//method to display the values of an object
1691void display(){System.out.println(acc_no+" "+name+" "+amount);}
1692}
1693//Creating a test class to deposit and withdraw amount
1694class TestAccount{
1695public static void main(String[] args){
1696Account a1=new Account();
1697a1.insert(832345,"Ankit",1000);
1698a1.display();
1699a1.checkBalance();
1700a1.deposit(40000);
1701a1.checkBalance();
1702a1.withdraw(15000);
1703a1.checkBalance();
1704}}
1705
1706Output:
1707832345 Ankit 1000.0
1708Balance is: 1000.0
170940000.0 deposited
1710Balance is: 41000.0
171115000.0 withdrawn
1712Balance is: 26000.0
1713
1714#Constructors in Java
1715In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory
1716It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default constructor by default.
1717There are two types of constructors in Java: no-arg constructor, and parameterized constructor.
1718Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any.
1719Rules for creating Java constructor
1720There are two rules defined for the constructor.
17211. Constructor name must be the same as its class name
17222. A Constructor must have no explicit return type
17233. A Java constructor cannot be abstract, static, final, and synchronized
1724Types of Java constructors
1725There are two types of constructors in Java:
17261. Default constructor (no-arg constructor)
17272. Parameterized constructor
1728
1729Java Default Constructor
1730A constructor is called "Default Constructor" when it doesn't have any parameter.
1731Syntax of default constructor:
17321. <class_name>(){}
1733Example of default constructor
1734In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation.
1735//Java Program to create and call a default constructor
1736class Bike1{
1737//creating a default constructor
1738Bike1(){System.out.println("Bike is created");}
1739//main method
1740public static void main(String args[]){
1741//calling a default constructor
1742Bike1 b=new Bike1();
1743}
1744}
1745
1746Output:
1747Bike is created
1748 What is the purpose of a default constructor?
1749The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type.
1750
1751Example of default constructor that displays the default values
1752//Let us see another example of default constructor
1753//which displays the default values
1754class Student3{
1755int id;
1756String name;
1757//method to display the value of id and name
1758void display(){System.out.println(id+" "+name);}
1759
1760public static void main(String args[]){
1761//creating objects
1762Student3 s1=new Student3();
1763Student3 s2=new Student3();
1764//displaying values of the object
1765s1.display();
1766s2.display();
1767}
1768}
1769
1770Output:
17710 null
17720 null
1773
1774Java Parameterized Constructor
1775A constructor which has a specific number of parameters is called a parameterized constructor.
1776
1777Example of parameterized constructor
1778In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.
1779//Java Program to demonstrate the use of the parameterized constructor.
1780class Student4{
1781 int id;
1782 String name;
1783 //creating a parameterized constructor
1784 Student4(int i,String n){
1785 id = i;
1786 name = n;
1787 }
1788 //method to display the values
1789 void display(){System.out.println(id+" "+name);}
1790
1791 public static void main(String args[]){
1792 //creating objects and passing values
1793 Student4 s1 = new Student4(111,"Karan");
1794 Student4 s2 = new Student4(222,"Aryan");
1795 //calling method to display the values of object
1796 s1.display();
1797 s2.display();
1798 }
1799}
1800
1801Output:
1802111 Karan
1803222 Aryan
1804
1805
1806Constructor Overloading in Java
1807In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods.
1808Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the number of parameters in the list and their types.
1809Example of Constructor Overloading
1810//Java program to overload constructors
1811class Student5{
1812 int id;
1813 String name;
1814 int age;
1815 //creating two arg constructor
1816 Student5(int i,String n){
1817 id = i;
1818 name = n;
1819 }
1820 //creating three arg constructor
1821 Student5(int i,String n,int a){
1822 id = i;
1823 name = n;
1824 age=a;
1825 }
1826 void display(){System.out.println(id+" "+name+" "+age);}
1827
1828 public static void main(String args[]){
1829 Student5 s1 = new Student5(111,"Karan");
1830 Student5 s2 = new Student5(222,"Aryan",25);
1831 s1.display();
1832 s2.display();
1833 }
1834}
1835Output:
1836111 Karan 0
1837222 Aryan 25
1838
1839Difference between constructor and method in Java
1840There are many differences between constructors and methods. They are given below.
1841Java Constructor
1842Java Method
1843A constructor is used to initialize the state of an object.
1844A method is used to expose the behavior of an object.
1845A constructor must not have a return type.
1846A method must have a return type.
1847The constructor is invoked implicitly.
1848The method is invoked explicitly.
1849The Java compiler provides a default constructor if you don't have any constructor in a class.
1850The method is not provided by the compiler in any case.
1851The constructor name must be same as the class name.
1852The method name may or may not be same as the class name.
1853
1854Java Copy Constructor
1855There is no copy constructor in Java. However, we can copy the values from one object to another like copy constructor in C++.
1856There are many ways to copy the values of one object into another in Java. They are:
1857By constructor
1858By assigning the values of one object into another
1859By clone() method of Object class
1860In this example, we are going to copy the values of one object into another using Java constructor.
1861//Java program to initialize the values from one object to another object.
1862class Student6{
1863 int id;
1864 String name;
1865 //constructor to initialize integer and string
1866 Student6(int i,String n){
1867 id = i;
1868 name = n;
1869 }
1870 //constructor to initialize another object
1871 Student6(Student6 s){
1872 id = s.id;
1873 name =s.name;
1874 }
1875 void display(){System.out.println(id+" "+name);}
1876
1877 public static void main(String args[]){
1878 Student6 s1 = new Student6(111,"Karan");
1879 Student6 s2 = new Student6(s1);
1880 s1.display();
1881 s2.display();
1882 }
1883}
1884
1885Output:
1886111 Karan
1887111 Karan
1888
1889
1890Copying values without constructor
1891We can copy the values of one object into another by assigning the objects values to another object. In this case, there is no need to create the constructor.
1892class Student7{
1893 int id;
1894 String name;
1895 Student7(int i,String n){
1896 id = i;
1897 name = n;
1898 }
1899 Student7(){}
1900 void display(){System.out.println(id+" "+name);}
1901
1902 public static void main(String args[]){
1903 Student7 s1 = new Student7(111,"Karan");
1904 Student7 s2 = new Student7();
1905 s2.id=s1.id;
1906 s2.name=s1.name;
1907 s1.display();
1908 s2.display();
1909 }
1910}
1911
1912Output:
1913111 Karan
1914111 Karan
1915
1916#Java static keyword
1917
1918The static keyword in Java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than an instance of the class.
1919The static can be:
19201. Variable (also known as a class variable)
19212. Method (also known as a class method)
19223. Block
19234. Nested class
1924
1925
19261) Java static variable
1927If you declare any variable as static, it is known as a static variable.
1928The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc.
1929The static variable gets memory only once in the class area at the time of class loading.
1930Advantages of static variable
1931It makes your program memory efficient (i.e., it saves memory).
1932Understanding the problem without static variable
1933class Student{
1934 int rollno;
1935 String name;
1936 String college="ITS";
1937}
1938Suppose there are 500 students in my college, now all instance data members will get memory each time when the object is created. All students have its unique rollno and name, so instance data member is good in such case. Here, "college" refers to the common property of all objects. If we make it static, this field will get the memory only once.
1939Java static property is shared to all objects.
1940Example of static variable
1941//Java Program to demonstrate the use of static variable
1942class Student{
1943 int rollno;//instance variable
1944 String name;
1945 static String college ="ITS";//static variable
1946 //constructor
1947 Student(int r, String n){
1948 rollno = r;
1949 name = n;
1950 }
1951 //method to display the values
1952 void display (){System.out.println(rollno+" "+name+" "+college);}
1953}
1954//Test class to show the values of objects
1955public class TestStaticVariable1{
1956 public static void main(String args[]){
1957 Student s1 = new Student(111,"Karan");
1958 Student s2 = new Student(222,"Aryan");
1959 //we can change the college of all objects by the single line of code
1960 //Student.college="BBDIT";
1961 s1.display();
1962 s2.display();
1963 }
1964}
1965
1966Output:
1967111 Karan ITS
1968222 Aryan ITS
1969
1970
1971Program of the counter without static variable
1972In this example, we have created an instance variable named count which is incremented in the constructor. Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable. If it is incremented, it won't reflect other objects. So each object will have the value 1 in the count variable.
1973//Java Program to demonstrate the use of an instance variable
1974//which get memory each time when we create an object of the class.
1975class Counter{
1976int count=0;//will get memory each time when the instance is created
1977
1978Counter(){
1979count++;//incrementing value
1980System.out.println(count);
1981}
1982
1983public static void main(String args[]){
1984//Creating objects
1985Counter c1=new Counter();
1986Counter c2=new Counter();
1987Counter c3=new Counter();
1988}
1989}
1990
1991Output:
19921
19931
19941
1995
1996Program of counter by static variable
1997As we have mentioned above, static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value.
1998//Java Program to illustrate the use of static variable which
1999//is shared with all objects.
2000class Counter2{
2001static int count=0;//will get memory only once and retain its value
2002
2003Counter2(){
2004count++;//incrementing the value of static variable
2005System.out.println(count);
2006}
2007
2008public static void main(String args[]){
2009//creating objects
2010Counter2 c1=new Counter2();
2011Counter2 c2=new Counter2();
2012Counter2 c3=new Counter2();
2013}
2014}
2015
2016Output:
20171
20182
20193
2020
20212) Java static method
2022If you apply static keyword with any method, it is known as static method.
2023A static method belongs to the class rather than the object of a class.
2024A static method can be invoked without the need for creating an instance of a class.
2025A static method can access static data member and can change the value of it.
2026Example of static method
2027//Java Program to demonstrate the use of a static method.
2028class Student{
2029 int rollno;
2030 String name;
2031 static String college = "ITS";
2032 //static method to change the value of static variable
2033 static void change(){
2034 college = "BBDIT";
2035 }
2036 //constructor to initialize the variable
2037 Student(int r, String n){
2038 rollno = r;
2039 name = n;
2040 }
2041 //method to display values
2042 void display(){System.out.println(rollno+" "+name+" "+college);}
2043}
2044//Test class to create and display the values of object
2045public class TestStaticMethod{
2046 public static void main(String args[]){
2047 Student.change();//calling change method
2048 //creating objects
2049 Student s1 = new Student(111,"Karan");
2050 Student s2 = new Student(222,"Aryan");
2051 Student s3 = new Student(333,"Sonoo");
2052 //calling display method
2053 s1.display();
2054 s2.display();
2055 s3.display();
2056 }
2057}
2058
2059Output:111 Karan BBDIT
2060 222 Aryan BBDIT
2061 333 Sonoo BBDIT
2062
2063Another example of a static method that performs a normal calculation
2064//Java Program to get the cube of a given number using the static method
2065
2066class Calculate{
2067 static int cube(int x){
2068 return x*x*x;
2069 }
2070
2071 public static void main(String args[]){
2072 int result=Calculate.cube(5);
2073 System.out.println(result);
2074 }
2075}
2076
2077Output:125
2078Restrictions for the static method
2079There are two main restrictions for the static method. They are:
20801. The static method can not use non static data member or call non-static method directly.
20812. this and super cannot be used in static context.
2082class A{
2083 int a=40;//non static
2084
2085 public static void main(String args[]){
2086 System.out.println(a);
2087 }
2088}
2089
2090Output:Compile Time Error
2091
2092Q) Why is the Java main method static?
2093Ans) It is because the object is not required to call a static method. If it were a non-static method, JVM creates an object first then call main() method that will lead the problem of extra memory allocation.
2094
20953) Java static block
2096Is used to initialize the static data member.
2097It is executed before the main method at the time of classloading.
2098Example of static block
2099class A2{
2100 static{System.out.println("static block is invoked");}
2101 public static void main(String args[]){
2102 System.out.println("Hello main");
2103 }
2104}
2105
2106Output:static block is invoked
2107 Hello main
2108
2109Q) Can we execute a program without main() method?
2110Ans) No, one of the ways was the static block, but it was possible till JDK 1.6. Since JDK 1.7, it is not possible to execute a java class without the main method.
2111class A3{
2112 static{
2113 System.out.println("static block is invoked");
2114 System.exit(0);
2115 }
2116}
2117
2118Output:
2119static block is invoked
2120
2121#this keyword in java
2122There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object.
2123
2124Usage of java this keyword
2125Here is given the 6 usage of java this keyword.
21261. this can be used to refer current class instance variable.
21272. this can be used to invoke current class method (implicitly)
21283. this() can be used to invoke current class constructor.
21294. this can be passed as an argument in the method call.
21305. this can be passed as argument in the constructor call.
21316. this can be used to return the current class instance from the method.
2132
2133
2134) this: to refer current class instance variable
2135The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity.
2136Understanding the problem without this keyword
2137Let's understand the problem if we don't use this keyword by the example given below:
2138class Student{
2139int rollno;
2140String name;
2141float fee;
2142Student(int rollno,String nam) this: to refer current class instance variable
2143The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity.
2144
2145Understanding the problem without this keyword
2146Let's understand the problem if we don't use this keyword by the example given below:
2147class Student{
2148int rollno;
2149String name;
2150float fee;
2151Student(int rollno,String name,float fee){
2152rollno=rollno;
2153name=name;
2154fee=fee;
2155}
2156void display(){System.out.println(rollno+" "+name+" "+fee);}
2157}
2158class TestThis1{
2159public static void main(String args[]){
2160Student s1=new Student(111,"ankit",5000f);
2161Student s2=new Student(112,"sumit",6000f);
2162s1.display();
2163s2.display();
2164}}
2165Test it Now
2166Output:
2167
21680 null 0.0
21690 null 0.0
2170In the above example, parameters (formal arguments) and instance variables are same. So, we are using this keyword to distinguish local variable and instance variable.
2171
2172Solution of the above problem by this keyword
2173class Student{
2174int rollno;
2175String name;
2176float fee;
2177Student(int rollno,String name,float fee){
2178this.rollno=rollno;
2179this.name=name;
2180this.fee=fee;
2181}
2182void display(){System.out.println(rollno+" "+name+" "+fee);}
2183}
2184
2185class TestThis2{
2186public static void main(String args[]){
2187Student s1=new Student(111,"ankit",5000f);
2188Student s2=new Student(112,"sumit",6000f);
2189s1.display();
2190s2.display();
2191}}
2192Test it Now
2193Output:
2194
2195111 ankit 5000
2196112 sumit 6000
2197If local variables(formal arguments) and instance variables are different, there is no need to use this keyword like in the following program:
2198
2199Program where this keyword is not required
2200class Student{
2201int rollno;
2202String name;
2203float fee;
2204Student(int r,String n,float f){
2205rollno=r;
2206name=n;
2207fee=f;
2208}
2209void display(){System.out.println(rollno+" "+name+" "+fee);}
2210}
2211
2212class TestThis3{
2213public static void main(String args[]){
2214Student s1=new Student(111,"ankit",5000f);
2215Student s2=new Student(112,"sumit",6000f);
2216s1.display();
2217s2.display();
2218}}
2219Test it Now
2220Output:
2221
2222111 ankit 5000
2223112 sumit 6000
2224It is better approach to use meaningful names for variables. So we use same name for instance variables and parameters in real time, and always use this keyword.
22252) this: to invoke current class method
2226You may invoke the method of the current class by using the this keyword. If you don't use the this keyword, compiler automatically adds this keyword while invoking the method. Let's see the example
2227
2228this keyword
2229class A{
2230void m(){System.out.println("hello m");}
2231void n(){
2232System.out.println("hello n");
2233//m();//same as this.m()
2234this.m();
2235}
2236}
2237class TestThis4{
2238public static void main(String args[]){
2239A a=new A();
2240a.n();
2241}}
2242Test it Now
2243Output:
2244
2245hello n
2246hello m
22473) this() : to invoke current class constructor
2248The this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor. In other words, it is used for constructor chaining.
2249
2250Calling default constructor from parameterized constructor:
2251
2252class A{
2253A(){System.out.println("hello a");}
2254A(int x){
2255this();
2256System.out.println(x);
2257}
2258}
2259class TestThis5{
2260public static void main(String args[]){
2261A a=new A(10);
2262}}
2263Test it Now
2264Output:
2265
2266hello a
226710
2268Calling parameterized constructor from default constructor:
2269
2270class A{
2271A(){
2272this(5);
2273System.out.println("hello a");
2274}
2275A(int x){
2276System.out.println(x);
2277}
2278}
2279class TestThis6{
2280public static void main(String args[]){
2281A a=new A();
2282}}
2283Test it Now
2284Output:
2285
22865
2287hello a
2288Real usage of this() constructor call
2289The this() constructor call should be used to reuse the constructor from the constructor. It maintains the chain between the constructors i.e. it is used for constructor chaining. Let's see the example given below that displays the actual use of this keyword.
2290
2291class Student{
2292int rollno;
2293String name,course;
2294float fee;
2295Student(int rollno,String name,String course){
2296this.rollno=rollno;
2297this.name=name;
2298this.course=course;
2299}
2300Student(int rollno,String name,String course,float fee){
2301this(rollno,name,course);//reusing constructor
2302this.fee=fee;
2303}
2304void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
2305}
2306class TestThis7{
2307public static void main(String args[]){
2308Student s1=new Student(111,"ankit","java");
2309Student s2=new Student(112,"sumit","java",6000f);
2310s1.display();
2311s2.display();
2312}}
2313Test it Now
2314Output:
2315
2316111 ankit java null
2317112 sumit java 6000
2318Rule: Call to this() must be the first statement in constructor.
2319class Student{
2320int rollno;
2321String name,course;
2322float fee;
2323Student(int rollno,String name,String course){
2324this.rollno=rollno;
2325this.name=name;
2326this.course=course;
2327}
2328Student(int rollno,String name,String course,float fee){
2329this.fee=fee;
2330this(rollno,name,course);//C.T.Error
2331}
2332void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
2333}
2334class TestThis8{
2335public static void main(String args[]){
2336Student s1=new Student(111,"ankit","java");
2337Student s2=new Student(112,"sumit","java",6000f);
2338s1.display();
2339s2.display();
2340}}
2341Test it Now
2342Compile Time Error: Call to this must be first statement in constructor
23434) this: to pass as an argument in the method
2344The this keyword can also be passed as an argument in the method. It is mainly used in the event handling. Let's see the example:
2345
2346class S2{
2347 void m(S2 obj){
2348 System.out.println("method is invoked");
2349 }
2350 void p(){
2351 m(this);
2352 }
2353 public static void main(String args[]){
2354 S2 s1 = new S2();
2355 s1.p();
2356 }
2357}
2358Test it Now
2359Output:
2360
2361method is invoked
2362Application of this that can be passed as an argument:
2363In event handling (or) in a situation where we have to provide reference of a class to another one. It is used to reuse one object in many methods.
2364
23655) this: to pass as argument in the constructor call
2366We can pass the this keyword in the constructor also. It is useful if we have to use one object in multiple classes. Let's see the example:
2367
2368class B{
2369 A4 obj;
2370 B(A4 obj){
2371 this.obj=obj;
2372 }
2373 void display(){
2374 System.out.println(obj.data);//using data member of A4 class
2375 }
2376}
2377
2378class A4{
2379 int data=10;
2380 A4(){
2381 B b=new B(this);
2382 b.display();
2383 }
2384 public static void main(String args[]){
2385 A4 a=new A4();
2386 }
2387}
2388Test it Now
2389Output:10
23906) this keyword can be used to return current class instance
2391We can return this keyword as an statement from the method. In such case, return type of the method must be the class type (non-primitive). Let's see the example:
2392
2393Syntax of this that can be returned as a statement
2394return_type method_name(){
2395return this;
2396}
2397Example of this keyword that you return as a statement from the method
2398class A{
2399A getA(){
2400return this;
2401}
2402void msg(){System.out.println("Hello java");}
2403}
2404class Test1{
2405public static void main(String args[]){
2406new A().getA().msg();
2407}
2408}
2409Test it Now
2410Output:
2411
2412Hello java
2413Proving this keyword
2414Let's prove that this keyword refers to the current class instance variable. In this program, we are printing the reference variable and this, output of both variables are same.
2415class A5{
2416void m(){
2417System.out.println(this);//prints same reference ID
2418}
2419public static void main(String args[]){
2420A5 obj=new A5();
2421System.out.println(obj);//prints the reference ID
2422obj.m();
2423}
2424}
2425Test it Now
2426Output:
2427
2428A5@22b3ea59
2429A5@22b3ea59e,float fee){
2430rollno=rollno;
2431name=name;
2432fee=fee;
2433}
2434void display(){System.out.println(rollno+" "+name+" "+fee);}
2435}
2436class TestThis1{
2437public static void main(String args[]){
2438Student s1=new Student(111,"ankit",5000f);
2439Student s2=new Student(112,"sumit",6000f);
2440s1.display();
2441s2.display();
2442}}
2443Test it Now
2444Output:
24450 null 0.0
24460 null 0.0
2447In the above example, parameters (formal arguments) and instance variables are same. So, we are using this keyword to distinguish local variable and instance variable.
2448Solution of the above problem by this keyword
2449class Student{
2450int rollno;
2451String name;
2452float fee;
2453Student(int rollno,String name,float fee){
2454this.rollno=rollno;
2455this.name=name;
2456this.fee=fee;
2457}
2458void display(){System.out.println(rollno+" "+name+" "+fee);}
2459}
2460
2461class TestThis2{
2462public static void main(String args[]){
2463Student s1=new Student(111,"ankit",5000f);
2464Student s2=new Student(112,"sumit",6000f);
2465s1.display();
2466s2.display();
2467}}
2468Test it Now
2469Output:
2470111 ankit 5000
2471112 sumit 6000
2472If local variables(formal arguments) and instance variables are different, there is no need to use this keyword like in the following program:
2473Program where this keyword is not required
2474class Student{
2475int rollno;
2476String name;
2477float fee;
2478Student(int r,String n,float f){
2479rollno=r;
2480name=n;
2481fee=f;
2482}
2483void display(){System.out.println(rollno+" "+name+" "+fee);}
2484}
2485
2486class TestThis3{
2487public static void main(String args[]){
2488Student s1=new Student(111,"ankit",5000f);
2489Student s2=new Student(112,"sumit",6000f);
2490s1.display();
2491s2.display();
2492}}
2493Test it Now
2494Output:
2495111 ankit 5000
2496112 sumit 6000
2497It is better approach to use meaningful names for variables. So we use same name for instance variables and parameters in real time, and always use this keyword.
24982) this: to invoke current class method
2499You may invoke the method of the current class by using the this keyword. If you don't use the this keyword, compiler automatically adds this keyword while invoking the method. Let's see the example
2500
2501class A{
2502void m(){System.out.println("hello m");}
2503void n(){
2504System.out.println("hello n");
2505//m();//same as this.m()
2506this.m();
2507}
2508}
2509class TestThis4{
2510public static void main(String args[]){
2511A a=new A();
2512a.n();
2513}}
2514Test it Now
2515Output:
2516hello n
2517hello m
25183) this() : to invoke current class constructor
2519The this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor. In other words, it is used for constructor chaining.
2520Calling default constructor from parameterized constructor:
2521class A{
2522A(){System.out.println("hello a");}
2523A(int x){
2524this();
2525System.out.println(x);
2526}
2527}
2528class TestThis5{
2529public static void main(String args[]){
2530A a=new A(10);
2531}}
2532Test it Now
2533Output:
2534hello a
253510
2536Calling parameterized constructor from default constructor:
2537class A{
2538A(){
2539this(5);
2540System.out.println("hello a");
2541}
2542A(int x){
2543System.out.println(x);
2544}
2545}
2546class TestThis6{
2547public static void main(String args[]){
2548A a=new A();
2549}}
2550Test it Now
2551Output:
25525
2553hello a
2554Real usage of this() constructor call
2555The this() constructor call should be used to reuse the constructor from the constructor. It maintains the chain between the constructors i.e. it is used for constructor chaining. Let's see the example given below that displays the actual use of this keyword.
2556class Student{
2557int rollno;
2558String name,course;
2559float fee;
2560Student(int rollno,String name,String course){
2561this.rollno=rollno;
2562this.name=name;
2563this.course=course;
2564}
2565Student(int rollno,String name,String course,float fee){
2566this(rollno,name,course);//reusing constructor
2567this.fee=fee;
2568}
2569void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
2570}
2571class TestThis7{
2572public static void main(String args[]){
2573Student s1=new Student(111,"ankit","java");
2574Student s2=new Student(112,"sumit","java",6000f);
2575s1.display();
2576s2.display();
2577}}
2578Test it Now
2579Output:
2580111 ankit java null
2581112 sumit java 6000
2582Rule: Call to this() must be the first statement in constructor.
2583class Student{
2584int rollno;
2585String name,course;
2586float fee;
2587Student(int rollno,String name,String course){
2588this.rollno=rollno;
2589this.name=name;
2590this.course=course;
2591}
2592Student(int rollno,String name,String course,float fee){
2593this.fee=fee;
2594this(rollno,name,course);//C.T.Error
2595}
2596void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
2597}
2598class TestThis8{
2599public static void main(String args[]){
2600Student s1=new Student(111,"ankit","java");
2601Student s2=new Student(112,"sumit","java",6000f);
2602s1.display();
2603s2.display();
2604}}
2605
2606Compile Time Error: Call to this must be first statement in constructor
26074) this: to pass as an argument in the method
2608The this keyword can also be passed as an argument in the method. It is mainly used in the event handling. Let's see the example:
2609class S2{
2610 void m(S2 obj){
2611 System.out.println("method is invoked");
2612 }
2613 void p(){
2614 m(this);
2615 }
2616 public static void main(String args[]){
2617 S2 s1 = new S2();
2618 s1.p();
2619 }
2620}
2621Test it Now
2622Output:
2623method is invoked
2624Application of this that can be passed as an argument:
2625In event handling (or) in a situation where we have to provide reference of a class to another one. It is used to reuse one object in many methods.
2626
26275) this: to pass as argument in the constructor call
2628We can pass the this keyword in the constructor also. It is useful if we have to use one object in multiple classes. Let's see the example:
2629class B{
2630 A4 obj;
2631 B(A4 obj){
2632 this.obj=obj;
2633 }
2634 void display(){
2635 System.out.println(obj.data);//using data member of A4 class
2636 }
2637}
2638
2639class A4{
2640 int data=10;
2641 A4(){
2642 B b=new B(this);
2643 b.display();
2644 }
2645 public static void main(String args[]){
2646 A4 a=new A4();
2647 }
2648}
2649
2650Output:10
2651
26526) this keyword can be used to return current class instance
2653We can return this keyword as an statement from the method. In such case, return type of the method must be the class type (non-primitive). Let's see the example:
2654Syntax of this that can be returned as a statement
2655return_type method_name(){
2656return this;
2657}
2658Example of this keyword that you return as a statement from the method
2659class A{
2660A getA(){
2661return this;
2662}
2663void msg(){System.out.println("Hello java");}
2664}
2665class Test1{
2666public static void main(String args[]){
2667new A().getA().msg();
2668}
2669}
2670Test it Now
2671Output:
2672Hello java
2673Proving this keyword
2674Let's prove that this keyword refers to the current class instance variable. In this program, we are printing the reference variable and this, output of both variables are same.
2675class A5{
2676void m(){
2677System.out.println(this);//prints same reference ID
2678}
2679public static void main(String args[]){
2680A5 obj=new A5();
2681System.out.println(obj);//prints the reference ID
2682obj.m();
2683}
2684}
2685Test it Now
2686Output:
2687A5@22b3ea59
2688A5@22b3ea59
2689
2690#Java Inheritance
2691
2692Inheritance in Java
2693Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system).
2694The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also.
2695Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
2696Why use inheritance in java
2697For Method Overriding (so runtime polymorphism can be achieved).
2698For Code Reusability.
2699Terms used in Inheritance
2700Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created.
2701Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.
2702Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class.
2703Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class.
2704The syntax of Java Inheritance
2705class Subclass-name extends Superclass-name
2706{
2707 //methods and fields
2708}
2709The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality.
2710In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass.
2711
2712Java Inheritance Example
2713
2714As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.
2715class Employee{
2716 float salary=40000;
2717}
2718class Programmer extends Employee{
2719 int bonus=10000;
2720 public static void main(String args[]){
2721 Programmer p=new Programmer();
2722 System.out.println("Programmer salary is:"+p.salary);
2723 System.out.println("Bonus of Programmer is:"+p.bonus);
2724}
2725}
2726
2727 Programmer salary is:40000.0
2728 Bonus of programmer is:10000
2729
2730
2731Types of inheritance in java
2732On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
2733In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.
2734
2735Note: Multiple inheritance is not supported in Java through class.
2736When one class inherits multiple classes, it is known as multiple inheritance. For Example:
2737
2738
2739Single Inheritance Example
2740File: TestInheritance.java
2741class Animal{
2742void eat(){System.out.println("eating...");}
2743}
2744class Dog extends Animal{
2745void bark(){System.out.println("barking...");}
2746}
2747class TestInheritance{
2748public static void main(String args[]){
2749Dog d=new Dog();
2750d.bark();
2751d.eat();
2752}}
2753Output:
2754barking...
2755eating...
2756Multilevel Inheritance Example
2757File: TestInheritance2.java
2758class Animal{
2759void eat(){System.out.println("eating...");}
2760}
2761class Dog extends Animal{
2762void bark(){System.out.println("barking...");}
2763}
2764class BabyDog extends Dog{
2765void weep(){System.out.println("weeping...");}
2766}
2767class TestInheritance2{
2768public static void main(String args[]){
2769BabyDog d=new BabyDog();
2770d.weep();
2771d.bark();
2772d.eat();
2773}}
2774Output:
2775weeping...
2776barking...
2777eating...
2778Hierarchical Inheritance Example
2779File: TestInheritance3.java
2780class Animal{
2781void eat(){System.out.println("eating...");}
2782}
2783class Dog extends Animal{
2784void bark(){System.out.println("barking...");}
2785}
2786class Cat extends Animal{
2787void meow(){System.out.println("meowing...");}
2788}
2789class TestInheritance3{
2790public static void main(String args[]){
2791Cat c=new Cat();
2792c.meow();
2793c.eat();
2794//c.bark();//C.T.Error
2795}}
2796Output:
2797meowing...
2798eating...
2799
2800Q) Why multiple inheritance is not supported in java?
2801To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
2802Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class.
2803Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error.
2804class A{
2805void msg(){System.out.println("Hello");}
2806}
2807class B{
2808void msg(){System.out.println("Welcome");}
2809}
2810class C extends A,B{//suppose if it were
2811
2812 public static void main(String args[]){
2813 C obj=new C();
2814 obj.msg();//Now which msg() method would be invoked?
2815}
2816}
2817RUN IT
2818 Compile Time Error
2819
2820
2821
2822
2823
2824#Aggregation in Java
2825If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship.
2826Consider a situation, Employee object contains many informations such as id, name, emailId etc. It contains one more object named address, which contains its own informations such as city, state, country, zipcode etc. as given below.
2827class Employee{
2828int id;
2829String name;
2830Address address;//Address is a class
2831...
2832}
2833In such case, Employee has an entity reference address, so relationship is Employee HAS-A address.
2834
2835
2836Why use Aggregation?
2837For Code Reusability.
2838
2839Simple Example of Aggregation
2840
2841In this example, we have created the reference of Operation class in the Circle class.
2842class Operation{
2843 int square(int n){
2844 return n*n;
2845 }
2846}
2847
2848class Circle{
2849 Operation op;//aggregation
2850 double pi=3.14;
2851
2852 double area(int radius){
2853 op=new Operation();
2854 int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
2855 return pi*rsquare;
2856 }
2857
2858
2859
2860 public static void main(String args[]){
2861 Circle c=new Circle();
2862 double result=c.area(5);
2863 System.out.println(result);
2864 }
28651. }
2866
2867Output:78.5
2868
2869When use Aggregation?
2870Code reuse is also best achieved by aggregation when there is no is-a relationship.
2871Inheritance should be used only if the relationship is-a is maintained throughout the lifetime of the objects involved; otherwise, aggregation is the best choice.
2872
2873Understanding meaningful example of Aggregation
2874In this example, Employee has an object of Address, address object contains its own informations such as city, state, country etc. In such case relationship is Employee HAS-A address.
2875Address.java
2876public class Address {
2877String city,state,country;
2878
2879public Address(String city, String state, String country) {
2880 this.city = city;
2881 this.state = state;
2882 this.country = country;
2883}
2884
2885}
2886Emp.java
2887public class Emp {
2888int id;
2889String name;
2890Address address;
2891
2892public Emp(int id, String name,Address address) {
2893 this.id = id;
2894 this.name = name;
2895 this.address=address;
2896}
2897
2898void display(){
2899System.out.println(id+" "+name);
2900System.out.println(address.city+" "+address.state+" "+address.country);
2901}
2902
2903public static void main(String[] args) {
2904Address address1=new Address("gzb","UP","india");
2905Address address2=new Address("gno","UP","india");
2906
2907Emp e=new Emp(111,"varun",address1);
2908Emp e2=new Emp(112,"arun",address2);
2909
2910e.display();
2911e2.display();
2912
2913}
2914}
2915
2916Output:111 varun
2917 gzb UP india
2918 112 arun
2919 gno UP india
2920
2921
2922
2923#Java Polymorphism
2924
2925Method Overloading in Java
2926
2927If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.
2928If we have to perform only one operation, having same name of the methods increases the readability of the program.
2929Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs.
2930So, we perform method overloading to figure out the program quickly.
2931
2932Advantage of method overloading
2933Method overloading increases the readability of the program.
2934Different ways to overload the method
2935There are two ways to overload the method in java
29361. By changing number of arguments
29372. By changing the data type
2938
2939Method Overloading: changing no. of arguments
2940In this example, we have created two methods, first add() method performs addition of two numbers and second add method performs addition of three numbers.
2941In this example, we are creating static methods so that we don't need to create instance for calling methods.
2942class Adder{
2943static int add(int a,int b){return a+b;}
2944static int add(int a,int b,int c){return a+b+c;}
2945}
2946class TestOverloading1{
2947public static void main(String[] args){
2948System.out.println(Adder.add(11,11));
2949System.out.println(Adder.add(11,11,11));
2950}}
2951
2952Output:
295322
295433
2955
29562) Method Overloading: changing data type of arguments
2957In this example, we have created two methods that differs in data type. The first add method receives two integer arguments and second add method receives two double arguments.
2958class Adder{
2959static int add(int a, int b){return a+b;}
2960static double add(double a, double b){return a+b;}
2961}
2962class TestOverloading2{
2963public static void main(String[] args){
2964System.out.println(Adder.add(11,11));
2965System.out.println(Adder.add(12.3,12.6));
2966}}
2967
2968Output:
296922
297024.9
2971
2972Q) Why Method Overloading is not possible by changing the return type of method only?
2973In java, method overloading is not possible by changing the return type of the method only because of ambiguity. Let's see how ambiguity may occur:
2974class Adder{
2975static int add(int a,int b){return a+b;}
2976static double add(int a,int b){return a+b;}
2977}
2978class TestOverloading3{
2979public static void main(String[] args){
2980System.out.println(Adder.add(11,11));//ambiguity
2981}}
2982
2983
2984
2985Output:
2986Compile Time Error: method add(int,int) is already defined in class Adder
2987
2988
2989Method Overriding in Java
2990If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java.
2991In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding.
2992Usage of Java Method Overriding
2993Method overriding is used to provide the specific implementation of a method which is already provided by its superclass.
2994Method overriding is used for runtime polymorphism
2995Rules for Java Method Overriding
29961. The method must have the same name as in the parent class
29972. The method must have the same parameter as in the parent class.
29983. There must be an IS-A relationship (inheritance).
2999Understanding the problem without method overriding
3000Let's understand the problem that we may face in the program if we don't use method overriding.
3001//Java Program to demonstrate why we need method overriding
3002//Here, we are calling the method of parent class with child
3003//class object.
3004//Creating a parent class
3005class Vehicle{
3006 void run(){System.out.println("Vehicle is running");}
3007}
3008//Creating a child class
3009class Bike extends Vehicle{
3010 public static void main(String args[]){
3011 //creating an instance of child class
3012 Bike obj = new Bike();
3013 //calling the method with child class instance
3014 obj.run();
3015 }
3016}
3017
3018Output:
3019Vehicle is running
3020
3021
3022
3023
3024A real example of Java Method Overriding
3025Consider a scenario where Bank is a class that provides functionality to get the rate of interest. However, the rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7%, and 9% rate of interest.