Java Programming PDF

Summary

This document covers fundamental Java programming concepts, with detailed explanations of looping structures, control structures (like if-else and switch statements), the Java Virtual Machine (JVM), methods, and other relevant elements.

Full Transcript

1) Looping Structure In Java Looping structure is a block of code which can be used to execute repeated statements. Due to looping statements we don’t have to write repeated statements again and again. With this we can remove code complexity. Types of loop:-...

1) Looping Structure In Java Looping structure is a block of code which can be used to execute repeated statements. Due to looping statements we don’t have to write repeated statements again and again. With this we can remove code complexity. Types of loop:- While loop (Entry-controlled loop) 1. To create while loop we use while keyword. 2. Syntax: While(condition) { //Statements } 3. To execute while loop it requires Boolean true value. 4. Relational And Logical Operations are used to make a condition. 5. While loop checks the condition at the beginning, hence it is considered as entry controlled loop. For loop (Entry-controlled loop) To create for loop we can use for keyword. Syntax: for(initialization; condition; increment/decrement) { //logic } 1. Initialization Phase: Can be used to initialized required number of variable. Here declared variable considered as a local variable. In initialization phase we can use unary and assignment operators. This phase executes once at the beginning. 2. Conditional Phase: It requires Boolean true value to execute loop To make a condition we can use relational and logical operator. Executes each time at the beginning. 3. Increment/decrement Phase: We can use unary and assignment operator. Executes each time at the end. Example: for(int i=1; i=50) System.out.println(“second class “); else if (p>=40) System.out.println(“ third class“); else System.out.println(“ failed“); D. nasted if layers of condition can be considered as a nested if condition. Nested if condition can be used to perform minimum comparison. Eg: int a=15; if(a=10) System.out.println(“We are in if condition“); 3) Switch Condition To create switch condition we can use switch case , default and break keyword can be used. Syntax Switch(operand) { Case value1: Statements; Case value2: Statements; Case value3: Statements; Case valueN: Statements; default: statements; } Switch condition require single operand. Switch condition compares operand on the basis of value directly. Hence switch condition considered as a fast control structure. If any case get satisfied the next case get execute implicitly, hence break keyword required. Here default as an else part. Switch condition is mainly used in menu-driven operation. 4) Special Condition It can be created using ternary operator. It is shorthand of if-else condition. Syntax:- datatype variable=(condition)?value1:value2; 5) JVM Java Virtual machine JVM is not available physically JVM is a set of classes and interfaces, which is responsible for executing class file. JVM executes class loader subsystem JVM contains classloadesr subsystem, it is a super class in JVM ClassLoaderSubsystem is a parent class of BootStrapClassLoaderSubsystem ClassLoaderSubsystem is responsible to load and execute class file. 1. BootStrapClassLoaderSubSystem ▪ It is a child class of ClassLoaderSubsystem. ▪ It is a parent class of ExtensionClassLoaderSubsystem. ▪ It is responsible to deploy runtime Environment ▪ To deploy runtime environment it execute rt,jar file 2. ExtensionClassLoaderSubSystem ▪ It is a child class of BootStrapClassLoaderSubsystem. ▪ It is a parent class of ApplicationClassLoaderSubSystem ▪ It is responsible to check class file. 3. ApplicationClassLoaderSubSystem ▪ It is a child class of ExtensionClassLoaderSubsystem ▪ It is responsible to load class file from source folder to JVM ▪ To load class file from source folder to JVM, it uses system variable. ▪ We can set system variable implicitly and explicitly too. ▪ To set explicitly we can use set command. ▪ eg :- set:- path=C:/User/Program files/Java/jdk-17/bin 6) Type of memory 1. Heap area memory. It is considered as a main memory in JVM. It contains special memory like meta-space, stack area memory, method area memory, PC register, String constant pool etc. All this memory also considered as a nursery memory It is also used to store object of a class Non-static variable or method can be considered in heap area memory. It consumes approximately ¼ of ram. 2. Class Area Memory. It is also known as method area memory. It is used to store structure of the class. Here nonstatic element of the class will be stored once in a lifecycle. 3. MetaSpace. It can be used to store static elements of the class. It stores static element of the class during class loading process by using class name. Hence static element of class can be access by using class name directly. Static element can be considered common for all objects. 4. PC register. Stands for program counter. It is a set of instruction regarding memory management. eg:- o java -xmlg MainClass o java -xmxlg MainClass 5. JNI. JNI (Java Native Interface). JNI is responsible to execute external java applications. 7) Class To create a class we can use class keyword. A class can be used to store and process the data. In java, class name should be unique and capitalized. In java, class contain variable, method, constructor and initializer. eg :- o class Demo { //initilizer //constructor //variable //method } 8) Variable In java variable is a temporary container, which can be used to store data. eg :- int a=10; Here int is a datatype and a is variable. In java variable can be considered as a property or member of the class. In java variable name should be identical and Decapitalized eg :- double simpleInterest; double areaOfCircle; double areaOfRectangle; ❖ Types of Variables. 1. Instance Varaible It is also considered as a non static variable. It can be declared within a class or outside the method. Instance variable generate during object creation. Hence we can access instance variable by using object only. Instance variable stored in heap area memory. Instance veriable separate for all objects. 2. Static Variable To create a static variable we use static keyword Static variable can be declare within a class and outside a method. Static variable generate during class loading process. It can be Accessed through class and object. Static variable common for all objects. It also considered as a class variable. It stored in meta space which is nursery memory of java. 3. Local Variable It can be declared within a method or any block. In java all methods or blocks executes in stack area memory, after exit from each block, stack area memory destroy that hence we cannot access any local variable outside their block. Hence local variable has to self initialized before it used. Local variable stored in stack area memory. NOTE:- There is no globle variable in JAVA. 9) Method. In java method is a block of statement which can be used to execute repeated statement at required time. By using method we don’t have to write repeated statement. By using method we can remove code complexity. Syntax:- return_type methodName(para1, para2, para3,,……paraN) { //statement; } In java method name should be identical and decapitalized. eg:- class Demo { void main() //method signature { System.out.println(“m1 method called”); } //method body or implementation static void m2() //method signature { System.out.println(“m2 method called”); } } ❖ Types of methods:- No Argument No return Value. 1. If method does not contain any argument, we should not pass any argument to invoke method. 2. If method does not return any value, return type should be declared using void keyword. With Argument No return value. 1. If method contains any argument, we should pass matching or supportive number of parameters. 2. If method does not return any value, return type should be declared using void keyword. No Argument with return value. 1. If method does not contain any argument, we should not pass any argument to invoke method. 2. If method return any value, value can be returned by using return keyword. 3. Returned value and return type should be matching or supportive. 4. method can return one value at a time. With argument With return value. 1. If method contains any argument, we should pass matching or supportive number of parameters. 2. If method returns any value, value should be return by using return keyword. 3. Return type or retuen value should be matching or supportive. 4. Method can return one value at a time. 10) Method Overloading. In java Method overloading is a concept where one class can contain 2 or more methods with same name but different arguments. o class Demo { void m1() { System.out.println(“no argument m1 method called”); } void m1(int a) { System.out.println(“Integer argument m1 method called”); } } o class MainClass { public static void main(String args[]) { Demo d1=new Demo; d1.m1(); // no argument m1 method called d1.m1(10); //with argument m1 method } } Method overloading is a concept where we can execute method as per their parameter. In method overloading one method can be executed differently on the basis of parameter , hence it is considered as a compile time polymorphism. Method overloading is useful for end-user We cannot prevent method overloading, because it is useful for end user. We cannot overload method on the basis of return type due to method auto promotion Method auto promotion o Byte—short –int—long –float –double—object o char—int –long—float—double—object o child—parent—root—super In java method auto promotion is a concept where if method couldn’t find matching parameter, java compiler auto promote their parameter to support(invoke) supportive method. Due to method auto promotion we don’t have to overload method unnecessarily Due to method auto promotion we cannot overload method on the basis of return type. o class Demo { void add(double a, double b) { System.out.println(“double double method called”); } } o class MainClass{ public static void main(String args[]) { Demo d1=new Demo(); d1.add(10,20); d1.add(‘A’,10); d1.add(14.3,’A’); } } Special Method or Constructor ✓ In java constructor is a special method which contains same name of the class. ✓ Constructor invoked implicitly during object creation. ✓ Hence, constructor cannot be static. ✓ Constructor cannot have return type, because it returns instance of the class by default. ✓ Constructor can be used to initialized instance and static variable. 1) Types of Constructor:- 1. Default Constructor. − Default Constructor do not have any argument, hence it is known as non argument constructor. − Java compiler provides default constructor by default if there is no constructor − Default constructor invoked implicitly by default during object creation − It can be used to initialized instance and static variable with default values. 2. User Defined Constructor − It also contains parameter, hence it is known as parameterized constructor − Java compiler doesn’t provide user-defined constructor, we have to create as per requirement. − User defined constructor can be used to initialized instance and static variable with user defined values. NOTE:- Combination of default and userdefined constructor considered as a constructor Overloading. To prevent new object creation we can declare constructor as a private. Initializers 1) Non Static initializer (Block) − There is no keyword to define non static block. − Non Static block known as instance block. − Syntax:- o { } //no-static block − Non Static block invoked implicitly during object creation before constructor. − Non Static block can be used to initialize instance and static variable with default values only. 2) Static block − To use static block we use static keyword − Syntax:- o static { } //static block − Static block invoked implicitly during class loading before constructor and instance block − Static block can be used to initialized static variable with default values only. 2) Methods of object class: 1) equal() : equal() method can be used to compare 2 objects on the basis of values. 2) toString() : toString() used to convert object into string format. 3) getClass() : getClass() method is used to represent source of object. 4) clone() : clone() method can be used to copy old object to new object. 5) finalize() : filalize() method used by garbadge collector implicitly to destroy unreferenced object from application. 6) wait() : wait() method can be used to put thread object into non-runnable statement until notify() or notifyAll() method invoked. 7) notify() : notify method can be used to free thread object from non- runnable state. 8) notifyAll() : notifyAll can be used to free all thread object from non-runnable state. 3) Object :- − In java object is an instance of the class. − By Using Object , we can access element of a class. ▪ Types Of Object Creation :- 1) by using new keyword:- − Object can be created using new keyword. − here new keyword returns new object. − NOTE: Object should be compared using equal() method not== operator. == is relation operator which compares objects on the basis of memory. equal() method of object class can be used to compare 2 object on the basis of Values. 2) by using reference :- − In java we can create object by reference old object to new one. − This approach can be used to save a memory 3) by using method :- − In java we can create object by using method also. − Java Provides forName() and newInstance() method of class. − forName() method can be used to load a class file. − forName() method throws with classNotFoundException. − newInstance() method throws with InstantationException and IllegalAccessException. − This approach can be used to create object of external class file. 4) by using anonymous way:- − In java anonymous object doesn’t referenced to anyone, hence it is also known as unreferenced object. − In java anonymous object can be used to access single element of a class. − NOTE:- In java, garbage collector is responsible to destroy anonymous object first. 5) by using constructor:- − In java we can create object by using copy constructor also. − Copy constructor is nothing but parameterized constructor, which contains same class type parameter. − By using copy constructor we can copy value of old object to new object. − By using it we can copy complete or partial object 6) by using cloning process:- − In java we can create object by using cloning process also. − In cloning process clone() method of the object class can be used. − Clone() ,method throws with cloneNoteSupportedException, hence to invoke this method, we have to handle exception. − To Perform cloning process, class should be implemented with clonable interface. Note :- Cloning process can be used, if we want to copy complete object. 7) by using singleton pattern :- − In Java we can create object by using singleton pattern also. − Singleton pattern allows you to create single object only. − To prevent new object creation we can declare constructor as private. − Create static method, which will returns static object, and static object is common for all users. NOTE:- Singleton pattern can be used to provide common solution for all, like database connection. 8) by using shollow copy:- − In java shallow copy means 2 object having same memory. − If we make changes in one object, impact can be seen in other object too. − Shallow copy is a faster. − In java shallow copy can be achieve by using reference and singleton pattern. 9) by using deep copy:- − In java deep copy means 2 objects having same values not memory. − If we makes changes in one object, impact cannot be seen in other objects. − Deep copy is slower than shallow copy. − In Deep copy we can achieve by using copy constructor and cloning process. 10) by using Serialization − It is a concept where object converted into bytestream. − Reverse Operation of serialization considered as a deserialization. − Due to serialization we can send data one end to other safely. − To perform serialization, we use serializable interface 11) Array :- In java Array is a concept, where we can store multiple values. Before array, to store multiple values we can use multiple variables also Instead of using multiple variables, we can use array to store multiple values,because array becomes easy to work with multiple values. Array can store multiple values index basis. Array index always starts from 0 and it ends with length-1. By using index we can set and get element from an array if we try to access index of an array, which is not present we will get ArrayIndexOutOfBoundException. To determine size of an array, we can use length property. 12) String : In java String is a class which is located in java.lang package String class can be used to represent group of character String represents group of character by using char[] array. String s1=”India” s1= I n d i a 0 1 2 3 4 String index always stars from 0 and ends with length()-1. 4) How to create string object 1) by using new keyword: eg String s1=new String(“India”); System.out.println(s1); 2) by literal way String s1=”India” System.out.println(s1); 3) by using char[] array char c[] ={‘i’,’n’,’d’,’i’,’a’}; String s1=new String(c); System.out.println(s1); System.out.println(c); 4) by using anonymous way System.out.println(“India”,length()); System.out.println(new String (‘India’).length()); To determine size of string object , we can use length method. To get character from index we can use charAt() method. If we try to access index of a string which is not present we get stringIndexOutOfBoundException. _________________________________________________________________________________ Methods of string String is mutable 13) Mutable class in java:- 1) StringBuffer :- StringBuffer is a class which is located in java.lang package. StringBuffer doesn’t follow StringConstantPool, hence it is considered as mutable class. It doesn’t contain concat() method to perform concatenation. To perform concatenation we can use append() method. It is thread-safe or synchronized implementation. It was introduced in java 1.0 version. eg: o StringBuffer sb= new StringBuffer(“India”); System.out.println(sb); sb.append(“Digital”); System.out.println(sb); // IndiaDigital 2) StringBuilder :- It is a class which is located in java.lang package It does not follow StringConstantPool, hence it is considered as a mutable class. It doesn’t contain concat() method to perform concatenation. To perform concatenation we can use append() method. It is non-synchronized or thread-unsafe implementation. It is faster than StringBuffer. It was introduced in java 1.5 version. eg: o StringBuilder sb=new SStringBuffer(“India”); System.out.println(sb); sb.append(“Digital”); System.out.println(sb); //IndiaDigital 14) Inheritance :- In Java inheritance is a concept where we can reuse our code. In Inheritance a class which provides element to other class considered as a parent class. In inheritance a class which acquires element from other class considered as a child class. To perform inheritance we can use extends keyword. It is also known as IS-A relationship. eg: o class Calculator { double add(double a, double b){return a+b;} double sub(double a, double b){return a-b;} double mul(double a, double b){return a*b;} double div(double a, double b){return a/b;} } o class ScifiCalculator extends Calculator { double square(double a) {return a*a;} double cube(double a){return a*a*a;} double squareRoot(double a){return Math.sqrt(a);} double cubeRoot(double a){return Math.cbrt(a);} } o class MainClass { Public static void main(String[] args) { scifiCalculator c= new scifiCalculator(); System.out.println(c.add(10,20)); System.out.println(c.sub(10,20)); System.out.println(c.square(10)); System.out.println(c.cube(10)); } } By using inheritance we can remove code complexity By using inheritance we don’t have to write redundant code again and again. To prevent inheritance we can declare a class as final ❖ Type of Inheritance :- 1) Simple/Single inheritance − Here one parent class have only one child class. 2) Multiple Inheritance − In multiple inheritance , one parent class can be child class of other class. − A class doesn’t contain child class considered as child class. − NOTE: Parent class of root class considered as a super class. − Eg : Object class. − NOTE : Parent class of root class considered as a super class. 3) Hierarchical inheritance − One parent class can have 2 or more child class. − We cannot access method of Subsidiary class. − eg. parent Parent paint() extends extends paint() paint() BoyChild handsome() GirlChild beautiful() 4) Multiple Inheritance − In java Multiple inheritance is a concept where child class can have 2 or more parent class. − Java allows only one class to be extends hence multiple inheritance not supported. − Java doesn’t support multiple inheritance due to method ambiguous. 5) Hybrid Inheritance − It is combination of multiple and multilevel Inheritance − hybrid inheritance is not supported due to multiple inheritance. 6) Cyclic Inheritance − In this One class can be child and parent of same class. − Cyclic inheritance is not supported due to method ambiguous. 15) Method Overriding − It is a concept where one class contains 2 or more methods with same name and same parameter. − To perform method overriding we require atleast 2 class in IS-A relationship − It is a concept where we can execute method as per object. − Here we can execute one method differently on the basis of object, hence it is considered as a runtime polymorphism. − We cannot override static method. − To prevent method overriding, we can declare a method as a final. − Method overriding is useful for developer. Method Overloading Method Overriding 1) It is a concept where one class 1)It is a concept, where one class contains 2 or more methods with contains 2 or more method with same name but different same name and same parameter. parameter. 2)We can execute method as per 2)Execute as per object. parameter. 3) Can be considered as a 3)Considered as run time compile-time polymorphism. polymorphism. 4)We can perform method 4)To perform method overriding it overloading in one class. requires atleast 2 class in IS-A relationship 5)We can overload static method 5)We cannot override static method 6) We cannot prevent method 6) To prevent method overriding overloading we can use final keyword 7) It is useful for end-user 7) It is useful for developers. 16) Upcasting − Object of child class reference to object. − It is also called widenning or generalization. − Upcasting is permissible. − Method considered of object and properties considered of referenced. − eg: Demo1 d1= new Demo3(); System.out.println(d1.a); System.out.println(d1.b); d1.m1(); 17) Downcasting − In java downcasting is concept where object of parent class referenced to child class. − also known as narrowing or degeneralization − If we try to perform downcasting explicitly we will get ClassCastException − eg: Demo2 d1=new Demo1(); 18) This − This is a keyword which represent current class − This keyword can be used with variable, constructor or object. − This keyword with variable can be used to differentiate between local and non- local variable − eg: this.a − by using this keyword we can represent current object. − eg : this. − by using this keyword we can invoke user-defined constructor from parameterized constructor and vice-versa. − eg: this(); − NOTE : This keyword with constructor should be at first statement. 19) Super − In java super is keyword which is used to represent parent class or its element. − Super keyword can be used with variable, method and constructor. − By using super with variable we can differentiate between child and parent class variable. − eg: super.a; − By using super with method we can differentiate between child and parent class method. − eg: super.display(); − By using super with constructor we can invoke user defined constructor of parent class. − eg: super(); − NOTE: Super keyword with constructor should be at first statement in constructor ,super and this keyword cannot be used simultaneously. 20) This VS Super This Super 1. In java this keyword can be used to 1. In java super keyword can be used to represent current class or its element represent parent class or its element 2. This Keyword can be used with 2. Super Keyword can be used with variable, object and constructor method, variable and constructor 3. This keyword does not give any error 3. Super keyword gives error if the mentioned element not found. 4. This keyword with variable can be 4. Super keyword with variable can be used to differentiate between local used to differentiate between child and non-local variable and parent variable 5. This keyword cannot be used with 5. Super keyword with method can be method used to differentiate between child and parent method 6. This keyword with constructor can be 6. Super keyword with constructor can used to invoked user-defined be used to invoke user-defined constructor from default constructor constructor from child class. & vice-versa 21) Package − In java package is a folder or sub-directory which can be used to store classes and interfaces. − By using folder, we can organise application. − If application is well organized, we can easily access required classes and interfaces. − To create package we can use package keyword. − In java package should be in smallcase − to compile package classes, we can use following command − eg: javac -d.FileName.java − To use other package classes we can use package keyword with qualified name of class. − Here qualified name means package+classname − eg: a.b.c.d.e.Demo 22) Access Specifier − In java access specifier is a concept, where we can set scope or visibility to class or its elements − Type of access specifier : 1) Private − To use it , we use private keyword. − Private access specifier can be used with method and variable. − It scope up to within a class. 2) Default − There is no keyword to define default access specifiers. − It is set default by default − It can be used by class, variable and method − It scope up to within a package. 3) Protected − To use protected access specifier we can use protected keyword. − It can be used with method and variable. − It scope upto within a package and outside the package only through child class. 4) Public − we can use public keyword to use public access specifier. − It can be used with method, variable and class. − It scope throughout the package. 23) Encapsulation − In java encapsulation is a concept , where we can hide our data. − It is also called as data binding. − It is known as Wrapping of class. − It is also known as 100% concrete class − To hide data we can declare all properties as private. − To set private data we can use setter method − To get private data we can use getter method − By using setter and getter method, we can set and get individual private properties of class. − To set all private properties directly, we can use constructor. − To display all private properties we can override toString() method of object class. − Encapsulation can be used to send data one end to other, hence it is considered as a model class. 24) Abstraction − In java abstraction is a concept where we can hide our method. − To achieve abstraction, we can use abstract class. What is abstract class ? ✓ In java abstract class means incomplete class. ✓ Here abstract means incomplete things. ✓ If class contain any abstract method class should be declared with abstract keyword. ✓ In java abstract method does not contain body or implementation. ✓ Abstract method also known as incomplete or un-implemented method. ✓ We cannot create object of abstract class. ✓ In java abstract class can be considered as a 0 to 100 implemented. ✓ NOTE: To prevent object creation we can declare class as an abstract. ✓ Abstract class can contain constructor and initializer to initialize properties of a class. ✓ To use abstract class we can use extends keyword ✓ We have to override abstract method into child class or child class become abstract implicitly. 25) Interface − To create an interface, we can use interface keyword. − In java interface name should be capitalized and unique. − eg: interface Demo { } − Interface contain all methods are abstract and public by default. − Hence abstract keyword doesn’t required to use. − Interface considered as a 0 implemented class. − Interface doesn’t contain constructor or initializer, because it is 0 implemented class. − We cannot create object of an interface, because it is abstract by default. − Interface contains all variable are public static and final by default. − To use interface we can use implements keyword. − We have to override abstract method into child class or child class becomes abstract implicitly. − eg: one interface can extends other interface too ❖ Application Of Interface- 1. Interface act as a blueprint or skeleton of an application. It gives only structure of application. 2. By using interface we can achieve multiple inheritance. 3. By using interface we can achieve loosely couple code Interface Abstract Class To create an interface we can use To create an abstract class we can interface keyword. use abstract keyword. Interface contain all method are Abstract class contain abstract and abstract abstract by default non-abstract method. Interface doesn’t contain Abstract class can contain construct constructor or initializer or initializers. Interface considered as a 0 Abstract class considered as a 0 to implemented class 100 implemented class Interface contain all variable are We can create public, final and static public,final and static by default variable in abstract class. We can not change access specifier We can use access specifier as per in interface,because interface and requirement method are public by default We cannot use abstract class in we can use interface in abstract interface class To use interface we can use To use abstract class we can use implements keyword extends keywords Interface can be used to Abstract class can be used to − to perform multiple achieve abstraction. inheritance − As a skeleton or blueprint of application − to achieve loosely couple code − to achieve powerful abstraction ❖ Helper class:- Helper class contains function that helps in assisting the program. This class intent to give quick implementation of functions such that program do not have to implement again and again. ❖ Polymorphism:- − In java polymorphism is a concept where we can execute code differently. − By using polymorphism we can execute code as per requirements. ❖ Types Of Polymorphism:- 1. Compile Time Polymorphism − Compile Time polymorphism is also known as early binding and static binding. − It can be achieved using method overloading. − In this we can execute method as per parameter − It is useful for end user. − We cannot prevent compile time polymorphism. 2. Runtime Polymorphism − It is known as late binding or dynamic binding. − It can be achieved by using method overloading − In this we can execute method as per object − It is useful for developer. − To prevent runtime polymorphism we can use final keyword.

Use Quizgecko on...
Browser
Browser