Shelkerupali2.files.wordpress.com



Declaration, Instantiation and Initialization of Java ArrayWe can declare, instantiate and initialize the java array together by:int?a[]={33,3,4,5};//declaration,?instantiation?and?initialization??Let's see the simple example to print this array.class?Testarray1{??public?static?void?main(String?args[]){??int?a[]={33,3,4,5};//declaration,?instantiation?and?initialization??//printing?array??for(int?i=0;i<a.length;i++)//length?is?the?property?of?array??System.out.println(a[i]);??}}??Output:33 3 4 5 Example of Multidimensional java arrayLet's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.class?Testarray3{??public?static?void?main(String?args[]){???//declaring?and?initializing?2D?array??int?arr[][]={{1,2,3},{2,4,5},{4,4,5}};??//printing?2D?array??for(int?i=0;i<3;i++){???for(int?j=0;j<3;j++){?????System.out.print(arr[i][j]+"?");???}???System.out.println();??}????}}??Output:1 2 3 2 4 5 4 4 5Java StringIn java, string is basically an object that represents sequence of char values. An array of characters works same as java string. For example:char[]?ch={'j','a','v','a','t','p','o','i','n','t'};??String?s=new?String(ch);??is same as:String?s="javatpoint";??Java String class provides a lot of methods to perform operations on string such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.What is String in javaGenerally, string is a sequence of characters. But in java, string is an object that represents a sequence of characters. The java.lang.String class is used to create string object.How to create String object?There are two ways to create String object: By string literalBy new keyword1) String LiteralJava String literal is created by using double quotes. For Example:String?s="welcome";??Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new string instance is created and placed in the pool. For example: String?s1="Welcome";??String?s2="Welcome";//will?not?create?new?instance??2) By new keywordString?s=new?String("Welcome");//creates?two?objects?and?one?reference?variable??In such case, JVM will create a new string object in normal(non pool) heap memory and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap(non pool). Java String Examplepublic?class?StringExample{??public?static?void?main(String?args[]){??String?s1="java";//creating?string?by?java?string?literal??char?ch[]={'s','t','r','i','n','g','s'};??String?s2=new?String(ch);//converting?char?array?to?string??String?s3=new?String("example");//creating?java?string?by?new?keyword??System.out.println(s1);??System.out.println(s2);??System.out.println(s3);??}}??javastringsexample1) StringBuffer append() methodThe append() method concatenates the given argument with this string.class?StringBufferExample{??public?static?void?main(String?args[]){??StringBuffer?sb=new?StringBuffer("Hello?");??sb.append("Java");//now?original?string?is?changed??System.out.println(sb);//prints?Hello?Java??}??}??2) StringBuffer insert() methodThe insert() method inserts the given string with this string at the given position.class?StringBufferExample2{??public?static?void?main(String?args[]){??StringBuffer?sb=new?StringBuffer("Hello?");??sb.insert(1,"Java");//now?original?string?is?changed??System.out.println(sb);//prints?HJavaello??}??}??3) StringBuffer replace() methodThe replace() method replaces the given string from the specified beginIndex and endIndex.class?StringBufferExample3{??public?static?void?main(String?args[]){??StringBuffer?sb=new?StringBuffer("Hello");??sb.replace(1,3,"Java");??System.out.println(sb);//prints?HJavalo??}??}??4) StringBuffer delete() methodThe delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex.class?StringBufferExample4{??public?static?void?main(String?args[]){??StringBuffer?sb=new?StringBuffer("Hello");??sb.delete(1,3);??System.out.println(sb);//prints?Hlo??}??}?5) StringBuffer reverse() methodThe reverse() method of StringBuilder class reverses the current string.class?StringBufferExample5{??public?static?void?main(String?args[]){??StringBuffer?sb=new?StringBuffer("Hello");??sb.reverse();??System.out.println(sb);//prints?olleH??}??}??6) StringBuffer capacity() methodThe capacity() method of StringBuffer class returns the current capacity of the buffer. The default capacity of the buffer is 16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34. class?StringBufferExample6{??public?static?void?main(String?args[]){??StringBuffer?sb=new?StringBuffer();??System.out.println(sb.capacity());//default?16??sb.append("Hello");??System.out.println(sb.capacity());//now?16??sb.append("java?is?my?favourite?language");??System.out.println(sb.capacity());//now?(16*2)+2=34?i.e?(oldcapacity*2)+2??}??}??7) StringBuffer ensureCapacity() methodThe ensureCapacity() method of StringBuffer class ensures that the given capacity is the minimum to the current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34. class?StringBufferExample7{??public?static?void?main(String?args[]){??StringBuffer?sb=new?StringBuffer();??System.out.println(sb.capacity());//default?16??sb.append("Hello");??System.out.println(sb.capacity());//now?16??sb.append("java?is?my?favourite?language");??System.out.println(sb.capacity());//now?(16*2)+2=34?i.e?(oldcapacity*2)+2??sb.ensureCapacity(10);//now?no?change??System.out.println(sb.capacity());//now?34??sb.ensureCapacity(50);//now?(34*2)+2??System.out.println(sb.capacity());//now?70??}??}??Wrapper class in JavaWrapper class in java?provides the mechanism?to convert primitive into object and object into primitive.The eight classes of?java.lang?package are known as wrapper classes in java. The list of eight wrapper classes are given below:Primitive TypeWrapper classbooleanBooleancharCharacterbyteByteshortShortintIntegerlongLongfloatFloatdoubleDoubleWrapper class Example: Primitive to Wrapperpublic?class?WrapperExample1{??public?static?void?main(String?args[]){??//Converting?int?into?Integer??int?a=20;??Integer?i=Integer.valueOf(a);//converting?int?into?Integer??Integer?j=a;//autoboxing,?now?compiler?will?write?Integer.valueOf(a)?internally????System.out.println(a+"?"+i+"?"+j);??}}??Output:20 20 20Wrapper class Example: Wrapper to Primitivepublic?class?WrapperExample2{????public?static?void?main(String?args[]){????//Converting?Integer?to?int????Integer?a=new?Integer(3);????int?i=a.intValue();//converting?Integer?to?int??int?j=a;//unboxing,?now?compiler?will?write?a.intValue()?internally????????System.out.println(a+"?"+i+"?"+j);????}}????Output:3 3 3Java EnumEnum in java?is a data type that contains fixed set of constants.It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc.Points to remember for Java Enumenum improves type safetyenum can be easily used in switchenum can be traversedenum can have fields, constructors and methodsenum may implement many interfaces but cannot extend any class because it internally extends Enum classSimple example of java enumclass?EnumExample1{??public?enum?Season?{?WINTER,?SPRING,?SUMMER,?FALL?}????public?static?void?main(String[]?args)?{??for?(Season?s?:?Season.values())??System.out.println(s);????}}??Output:WINTER SPRING SUMMER FALLDefining Java enumThe enum can be defined within or outside the class because it is similar to a class.Java enum example: defined outside classenum?Season?{?WINTER,?SPRING,?SUMMER,?FALL?}??class?EnumExample2{??public?static?void?main(String[]?args)?{??Season?s=Season.WINTER;??System.out.println(s);??}}???Output:WINTERInheritanceInheritance in java?is a mechanism in which one object acquires all the properties and behaviors of parent object.?Syntax of Java Inheritanceclass?Subclass-name?extends?Superclass-name??{?????//methods?and?fields??}??The?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.Java Inheritance Exampleclass?Employee{???float?salary=40000;??}??class?Programmer?extends?Employee{???int?bonus=10000;???public?static?void?main(String?args[]){?????Programmer?p=new?Programmer();?????System.out.println("Programmer?salary?is:"+p.salary);?????System.out.println("Bonus?of?Programmer?is:"+p.bonus);??}??}??Programmer salary is:40000.0 Bonus of programmer is:10000Types of inheritance in javaOn the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.Single Inheritance ExampleFile: TestInheritance.javaclass?Animal{??void?eat(){System.out.println("eating...");}??}??class?Dog?extends?Animal{??void?bark(){System.out.println("barking...");}??}??class?TestInheritance{??public?static?void?main(String?args[]){??Dog?d=new?Dog();??d.bark();??d.eat();??}}??Output:barking...eating...Multilevel Inheritance ExampleFile: TestInheritance2.javaclass?Animal{??void?eat(){System.out.println("eating...");}??}??class?Dog?extends?Animal{??void?bark(){System.out.println("barking...");}??}??class?BabyDog?extends?Dog{??void?weep(){System.out.println("weeping...");}??}??class?TestInheritance2{??public?static?void?main(String?args[]){??BabyDog?d=new?BabyDog();??d.weep();??d.bark();??d.eat();??}}??Output:weeping...barking...eating...Hierarchical Inheritance ExampleFile: TestInheritance3.javaclass?Animal{??void?eat(){System.out.println("eating...");}??}??class?Dog?extends?Animal{??void?bark(){System.out.println("barking...");}??}??class?Cat?extends?Animal{??void?meow(){System.out.println("meowing...");}??}??class?TestInheritance3{??public?static?void?main(String?args[]){??Cat?c=new?Cat();??c.meow();??c.eat();??//c.bark();//C.T.Error??}}??Output:meowing...eating...Q) Why multiple inheritance is not supported in java?To reduce the complexity and simplify the language, multiple inheritance is not supported in java.Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class.Since 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 now.class?A{??void?msg(){System.out.println("Hello");}??}??class?B{??void?msg(){System.out.println("Welcome");}??}??class?C?extends?A,B{//suppose?if?it?were??????Public?Static?void?main(String?args[]){?????C?obj=new?C();?????obj.msg();//Now?which?msg()?method?would?be?invoked???}??}??Compile Time ErrorMethod Overloading in JavaIf a class has multiple methods having same name but different in parameters, it is known as?Method Overloading.1) Method Overloading: changing no. of argumentsIn this example, we have created two methods, first add() method performs addition of two numbers and second add method performs addition of three numbers.In this example, we are creating static methods so that we don't need to create instance for calling methods.class?Adder{??static?int?add(int?a,int?b){return?a+b;}??static?int?add(int?a,int?b,int?c){return?a+b+c;}??}??class?TestOverloading1{??public?static?void?main(String[]?args){??System.out.println(Adder.add(11,11));??System.out.println(Adder.add(11,11,11));??}}??Output:2224.92) Method Overloading: changing data type of argumentsIn 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.class?Adder{??static?int?add(int?a,?int?b){return?a+b;}??static?double?add(double?a,?double?b){return?a+b;}??}??class?TestOverloading2{??public?static?void?main(String[]?args){??System.out.println(Adder.add(11,11));??System.out.println(Adder.add(12.3,12.6));??}}??Output:2233Method Overriding in JavaIf subclass (child class) has the same method as declared in the parent class, it is known as?method overriding in java.Usage of Java Method OverridingMethod overriding is used to provide specific implementation of a method that is already provided by its super class.Method overriding is used for runtime polymorphismRules for Java Method Overridingmethod must have same name as in the parent classmethod must have same parameter as in the parent class.must be IS-A relationship (inheritance).Example of method overridingclass?Vehicle{??void?run(){System.out.println("Vehicle?is?running");}??}??class?Bike2?extends?Vehicle{??void?run(){System.out.println("Bike?is?running?safely");}????public?static?void?main(String?args[]){??Bike2?obj?=?new?Bike2();??obj.run();??}??Output:Bike is running safelyReal example of Java Method OverridingConsider a scenario, Bank is a class that provides functionality to get rate of interest. But, rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate of interest.class?Bank{??int?getRateOfInterest(){return?0;}??}????class?SBI?extends?Bank{??int?getRateOfInterest(){return?8;}??}????class?ICICI?extends?Bank{??int?getRateOfInterest(){return?7;}??}??class?AXIS?extends?Bank{??int?getRateOfInterest(){return?9;}??}????class?Test2{??public?static?void?main(String?args[]){??SBI?s=new?SBI();??ICICI?i=new?ICICI();??AXIS?a=new?AXIS();??System.out.println("SBI?Rate?of?Interest:?"+s.getRateOfInterest());??System.out.println("ICICI?Rate?of?Interest:?"+i.getRateOfInterest());??System.out.println("AXIS?Rate?of?Interest:?"+a.getRateOfInterest());??}??}??Output:SBI Rate of Interest: 8ICICI Rate of Interest: 7AXIS Rate of Interest: 9Runtime Polymorphism Or (Dynamic Method Dispatch?)in JavaRuntime polymorphism?or?Dynamic Method Dispatch?is a process in which a call to an overridden method is resolved at runtime rather than compile-time.Example of Java Runtime PolymorphismIn this example, we are creating two classes Bike and Splendar. Splendar class extends Bike class and overrides its run() method. Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.class?Bike{????void?run(){System.out.println("running");}??}??class?Splender?extends?Bike{????void?run(){System.out.println("running?safely?with?60km");}??????public?static?void?main(String?args[]){??????Bike?b?=?new?Splender();//upcasting??????b.run();????}??}??Output:running safely with 60km.Java Runtime Polymorphism Example: Shapeclass?Shape{??void?draw(){System.out.println("drawing...");}??}??class?Rectangle?extends?Shape{??void?draw(){System.out.println("drawing?rectangle...");}??}??class?Circle?extends?Shape{??void?draw(){System.out.println("drawing?circle...");}??}??class?Triangle?extends?Shape{??void?draw(){System.out.println("drawing?triangle...");}??}??class?TestPolymorphism2{??public?static?void?main(String?args[]){??Shape?s;??s=new?Rectangle();??s.draw();??s=new?Circle();??s.draw();??s=new?Triangle();??s.draw();??}??}??Output:drawing rectangle...drawing circle...drawing triangle...Java Runtime Polymorphism Example: Animalclass?Animal{??void?eat(){System.out.println("eating...");}??}??class?Dog?extends?Animal{??void?eat(){System.out.println("eating?bread...");}??}??class?Cat?extends?Animal{??void?eat(){System.out.println("eating?rat...");}??}??class?Lion?extends?Animal{??void?eat(){System.out.println("eating?meat...");}??}??class?TestPolymorphism3{??public?static?void?main(String[]?args){??Animal?a;??a=new?Dog();??a.eat();??a=new?Cat();??a.eat();??a=new?Lion();??a.eat();??}}??Output:eating bread...eating rat...eating meat...Java final variableIf you make any variable as final, you cannot change the value of final variable(It will be constant).class?Bike9{???final?int?speedlimit=90;//final?variable???void?run(){????speedlimit=400;???}???public?static?void?main(String?args[]){???Bike9?obj=new??Bike9();???obj.run();???}??}//end?of?class??Output:Compile Time ErrorJava final methodIf you make any method as final, you cannot override it.Example of final methodclass?Bike{????final?void?run(){System.out.println("running");}??}???????class?Honda?extends?Bike{?????void?run(){System.out.println("running?safely?with?100kmph");}??????????public?static?void?main(String?args[]){?????Honda?honda=?new?Honda();?????honda.run();?????}??}??Output:Compile Time ErrorJava final classIf you make any class as final, you cannot extend it.Example of final classfinal?class?Bike{}????class?Honda1?extends?Bike{????void?run(){System.out.println("running?safely?with?100kmph");}????????public?static?void?main(String?args[]){????Honda1?honda=?new?Honda1();????honda.run();????}??}??Output:Compile Time Errorsuper keyword in javaThe?super?keyword in java is a reference variable which is used to refer immediate parent class object.Usage of java super Keywordsuper can be used to refer immediate parent class instance variable.super can be used to invoke immediate parent class method.super() can be used to invoke immediate parent class constructor.1) super is used to refer immediate parent class instance variable.We can use super keyword to access the data member or field of parent class. It is used if parent class and child class have same fields.class?Animal{??String?color="white";??}??class?Dog?extends?Animal{??String?color="black";??void?printColor(){??System.out.println(color);//prints?color?of?Dog?class??System.out.println(super.color);//prints?color?of?Animal?class??}??}??class?TestSuper1{??public?static?void?main(String?args[]){??Dog?d=new?Dog();??d.printColor();??}}??Output:blackwhiteAbstract class in JavaA class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and non-abstract methods (method with body).Before learning java abstract class, let's understand the abstraction in java first.Abstraction in JavaAbstraction?is a process of hiding the implementation details and showing only functionality to the user.Ways to achieve AbstractionThere are two ways to achieve abstraction in javaAbstract class (0 to 100%)Interface (100%)Abstract class in JavaA class that is declared as abstract is known as?abstract class. It needs to be extended and its method implemented. It cannot be instantiated.Example abstract classabstract?class?A{}??Abstract methodA method that is declared as abstract and does not have implementation is known as abstract method.Example abstract methodabstract?void?printStatus();//no?body?and?abstract??Example of abstract class that has abstract methodIn this example, Bike the abstract class that contains only one abstract method run. It implementation is provided by the Honda class.abstract?class?Bike{????abstract?void?run();??}??class?Honda4?extends?Bike{??void?run(){System.out.println("running?safely..");}??public?static?void?main(String?args[]){???Bike?obj?=?new?Honda4();???obj.run();??}??}??running safely..Another example of abstract class in javaFile: TestBank.javaabstract?class?Bank{????abstract?int?getRateOfInterest();????}????class?SBI?extends?Bank{????int?getRateOfInterest(){return?7;}????}????class?PNB?extends?Bank{????int?getRateOfInterest(){return?8;}????}????????class?TestBank{????public?static?void?main(String?args[]){????Bank?b;??b=new?SBI();??System.out.println("Rate?of?Interest?is:?"+b.getRateOfInterest()+"?%");????b=new?PNB();??System.out.println("Rate?of?Interest?is:?"+b.getRateOfInterest()+"?%");????}}????Rate of Interest is: 7 %Rate of Interest is: 8 %Java static keywordThe?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 instance of the class.The static can be:variable (also known as class variable)method (also known as class method)blocknested class1) Java static variableIf you declare any variable as static, it is known static variable.The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees, college name of students etc.The static variable gets memory only once in class area at the time of class loading.Advantage of static variableIt makes your program?memory efficient?(i.e it saves memory).Understanding problem without static variableclass?Student{???????int?rollno;???????String?name;???????String?college="ITS";??}??Example of static variableclass?Student8{?????int?rollno;?????String?name;?????static?String?college?="ITS";??????????Student8(int?r,String?n){?????rollno?=?r;?????name?=?n;?????}???void?display?(){System.out.println(rollno+"?"+name+"?"+college);}?????public?static?void?main(String?args[]){???Student8?s1?=?new?Student8(111,"Karan");???Student8?s2?=?new?Student8(222,"Aryan");??????s1.display();???s2.display();???}??}??Output:111 Karan ITS 222 Aryan ITS2) Java static methodIf you apply static keyword with any method, it is known as static method.A static method belongs to the class rather than object of a class.A static method can be invoked without the need for creating an instance of a class.static method can access static data member and can change the value of it.Example of static methodclass?Student9{???????int?rollno;???????String?name;???????static?String?college?=?"ITS";??????????????static?void?change(){???????college?=?"BBDIT";???????}?????????Student9(int?r,?String?n){???????rollno?=?r;???????name?=?n;???????}?????????void?display?(){System.out.println(rollno+"?"+name+"?"+college);}????????public?static?void?main(String?args[]){??????Student9.change();????????Student9?s1?=?new?Student9?(111,"Karan");??????Student9?s2?=?new?Student9?(222,"Aryan");??????Student9?s3?=?new?Student9?(333,"Sonoo");????????s1.display();??????s2.display();??????s3.display();??????}??}??Output:111 Karan BBDIT 222 Aryan BBDIT 333 Sonoo BBDITAnother example of static method that performs normal calculation//Program?to?get?cube?of?a?given?number?by?static?method????class?Calculate{????static?int?cube(int?x){????return?x*x*x;????}??????public?static?void?main(String?args[]){????int?result=Calculate.cube(5);????System.out.println(result);????}??}??Output:125Q) why java main method is static?Ans) because object is not required to call static method if it were non-static method, jvm create object first then call main() method that will lead the problem of extra memory allocation.Q) Can we execute a program without main() method?Ans) Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.class?A3{????static{????System.out.println("static?block?is?invoked");????System.exit(0);????}??}??Output:static block is invoked (if not JDK7) ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download