1 | JDK | Java Development Kit | JDK = Compiler + JVM + JRE > Java Virtual Machine, Java Runtime Environment. | Compiler compiles source code to Byte code, JVM execute Byte code and convert it to Binary code. JVM responsible for running Java application. JRE is a collection of tools that run Java application. | Jdk is owned by Oracle, Stable version is 8, can use 11. | Open Jdk is like corretto 1.8, some Third Party organization like amazon who derived their Jdk from Oracle version and further support and maintained it. For Example : JDK Corretto 1.8 is useful to run uiautomatorviewer | Core Java vs Java Standard Edition > Core Java is the standard edition from which other editions are derived, So both are same. | Install Jdk | ||
2 | Computer Architecture Languages | High Level Language | Human Understandable | Is more english like language | ||||||
Low Level Language | M/c Understandable | Is a language in binary numbers | ||||||||
3 | Java Files | .java file in which High level code written | compiled by compiler to .class file which have byte code | class loader is Java internal API which upload .class file to JVM (Java virtual Machine), JVM on the target machine will convert this byte code to machine understandable binary code and executes it. | JVM then pass on instructions to Interpreter for Mac, Windows or Linux which then show result on output console. Interpreter is from OS side | |||||
.class file created in same folder if created by terminal or .class file created in bin folder if created by eclipse | ||||||||||
In Eclipse, .class file can be seen by Navigator view under Window Menu which is deprecadted now | ||||||||||
4 | Maven | online repository for dependencies | Download jar files automatically in Project | Download and unzip it in any folder. Stable version 3.6.3 | ||||||
5 | Environment Variables | System Variables are available to all Users. It is at OS Level | are in the form of KEY and VALUE pair. | “Path =” This key already defined in OS (in-built variable) and value given against this key is understood by OS > executables or batch files values given against this key | Such as here for Java, path is to given upto bin folder where all executables files are present | JAVA & JAVA_HOME are two different variables | ||||
3rd Party varaibles are available to all Users. It is at OS Level | 3rd Party variables are set to make connections between system softwares & applications | Third Party Variabales are like “JAVA_HOME “. These variables name are standard and can be used by third party applications or other applications installed in the OS | Such as here for JAVA_HOME, path is to given upto jdk folder where all files are present | Set MAVEN_HOME too by path upto Maven Folder/bin on Hard Disk | ||||||
User varaibles are avaible specifically for that user who is logged in | ||||||||||
6 | Integrated Development Environment (IDE) | Code Editor Which integrates with JDK + Maven + Others | Eclipse > | Download from packages and unzip it: Eclipse IDE for Java Developers | ||||||
Set Jdk path in Eclipse > | Eclipse > Window > Preferences > Java > Installed JRE > Add > Std JVM > Select jdk folder from SSD > finish | |||||||||
Java library > contains all jar files of JRE framework | rt.jar > | Its contains all compiled class files for the Core java and bootstrap classes which required during runtime. These classes comprise of Java platform Core API | ||||||||
Java perspective (Right icon with J letter) & Open Perspective icons at top right corner of Eclipse | This means nature of Eclipse to be to associate with projects | Default is Java perspective | ||||||||
Console view in eclipse is like terminal in Mac OS | Shows us the output while executing Program | |||||||||
Add/Choose specific Jdk for Specific project > | Project Folder > R.click > Properties > Java build Path > Libraries Tab > JRE Library > Add Library > Select Jdk > Apply and close | |||||||||
Shorcuts > | To type main method in Java class is : main (ctrl+space) | Ctrl + S > saves and compiles the file | ||||||||
CODING :- | ||||||||||
7 | Logic | Logic is the working principle on which software built (What, Why & How). It is also called Business Logic. | It is contained in the set of instructions written by programmer. | |||||||
8 | Object | Simply its entity having knowledge of something of specific point of time which may or may not update according to set conditions | More Clarity: Its copy of class at given point of time | Object can be Value, Variable, Data Structure, Method, Table or combination of these. It also defines the Instance of class in class based OOPS | ||||||
9 | Object Oriented Programming Structure (OOPS) | Object called to get or set the value | Is the type of computer programming where programmer is using the idea of object for defines the data type of data structure and also defines the type of fx’s that can applied to data structure. Simply means which data to get or set by the use of object | |||||||
10 | Keyword | Reserved words whose meaning already defined to compiler | ||||||||
11 | Template | It is a file which is pre-formated in some way and serves as a starting point for new document | ||||||||
12 | Instance | Is also called State | Concrete Occurance of Object | |||||||
13 | Inheritance | Is a mechanism where which one object/class acquires all the properties and behaviors of a parent object/class | Can access the member of inherited class into inheritance class | |||||||
14 | Name Space | Means Group, Collection of classes, It may be nested | ||||||||
15 | Data Structure | It is the data organization, management & storage format, that enables efficeint access and modifcation. | It Is the collection of data values and relationship amoung them | |||||||
16 | String | It is sequence of characters stores in character array and marks in double quotation marks ” “ | ||||||||
17 | Array | Character array is collection of variables of char data type and stores in consecutive memory addresses | ||||||||
18 | Concadinate | Joining two texts together in one cell from two different cells | ||||||||
19 | Pointers | Is a variable that store address of memory location | ||||||||
20 | Create a Java Project | New – Java Project | src folder | package | class | main method | run as Java application | |||
21 | Create a Maven Project | New – Maven Project | src/main/java & src/test/java folder | package | class | main method & pom.xml file or Convert to TestNg execution approach which creates testng.xml | run as Junit / TestNg Test | |||
22 | Class | Class is defining idea in OOPS | It is template definition of methods & variables or it can be a particular kind of object. It is also collection of similar data types. | Used for re-usability, Also Called Business Object | public class name { } | |||||
Instance Properties > | Block | { } | Execute before to Methods and runs every time as the objects created | { } constructor(); method(); Methods run after constructor and Constructor run after Instance block | static block Loads first along with the class and execute once only even if many objects created during execution. It runs before to instance block | |||||
These are the properties of the class and declared directly within class and have scope everywhere in the class but are always used with object. | Variable | It is the entity that changed, It use to store & retrieve data from memory location | Just inside the Class Curly Brackets & Declare (Just create) or Initailize (provide first value) there. | public class name { int A = 100; } | ; called statement terminator | |||||
Method | Defines the behaviour of object, it is the action that object can able to perform. Methods required an object of its class to be created before it can be called. | Inside class curly Brackets | public void methodOne() {}; | |||||||
A method is a block of code which only runs when it is called. Methods are used to perform certain actions, and they are also known as functions. | Method start with return type either primitive, non-primitive or void | name() { } with or w/o arguments | public static void main(String args[]) { } :- main method in Java :- | |||||||
>> same name methods can be use but number of arguments or sequence of arguments must be different | void is also the return type as it will return nothing | If Return type is of Primitive data types then method returns value and If Return type is of non-Primitive data types then method returns object | main method is entry point in java and excution of java program starts from this method, all other methods called in this method | |||||||
Local Properties > | If any above property used inside Method it is called Local Property to that Method | They have scope from their point of initialization to the end of block in a class. i.e. end of method | Local variables have no default value and they must be initialized (or have some value) before being used otherwise there is compile-time error. | |||||||
Static Properties > | Any property used at Instance Level can be static, static not use with local property | If we use Keyword Static then its means we call method without creating object | Static property Called with class name or directly But normal property always called with object | non static method/property can be called from static method with the help of object And static method can called static property directly. | from inside static method, non static method can be called in same class with the object of class like object.nonStaticMethod(); AND static method can call static method directly or with class name. | |||||
Static means no duplicacy, only one instance of thing which once updated then always keep its updated value | static block at instance level executes onece only but normal block at instance level execute all time when ever class constructor run | Static method can call static variable or static method directly, static method can call non static constructor as static keyword Not Applicable to constructor | non static method called static method with the class name like ClassName.static Method | |||||||
23 | Naming Convention (Camel Case) | Variable Name => | start with small letter + Camel Case > | startName = 1; | ||||||
Method Name => | start with small letter + Camel Case > | startName() { }; | ||||||||
Class Name => | start with first Capital letter + Camel Case > | StartName { } | ||||||||
Project Name => | start with first Capital letter + Camel Case > | StartName | ||||||||
final Variable Name => | all Capital Leters + can use _ > | final START_NAME = 1; | ||||||||
Packages Name => | Domain_Name.Application_Name.Module_Name > | com.neimanmarcus.kids > | Package can be of 2 types, like inbuilt package & user defined package > | 1) One class called into other class in same package then not need to import and need to import if called from other package | import com.package.*; > This call all classes under this package | |||||
Interface Name => | start with small letter + Camel Case > | startName(); | 2) class can be called also as package_Name.class_Name object = new package_Name.Class_Name(); This is called fully qualified class name | |||||||
24 | Data Types | Capacity: byte = 8 Bits = 1Byte => | Range of Values: Signed: -128 to 127 OR Unsigned: 0-255 | <<— Primitive Data types –> | These are basic data types and their value directly stored in memory like Byte, short, int etc and from these other data types can be derived > | like String is derived data type | ||||
short = 16 Bits = 2Bytes => | -32768 to 32767 | Primitive int variable has default value of 0. | ||||||||
int = 32 Bits = 4Bytes => | [ -2147483648 (2^31) to 2147483647 (2^31-1) ] | Primitive boolean data type has default value “false”. | ||||||||
long = 64 bits = 8bytes => | -9223372036854775808(-2^63) to 9223372036854775807(2^63 -1) | Primitive char variable has default value – nothing. | ||||||||
float = 32 Bits = 4Bytes => | [ -3.40E+38 (3.4 * 10 raise to power 38) to 3.40E+38 ] | it is mandatory to write f or F with float value like float abc = 54.66f; | ||||||||
double = 64 bits = 8Bytes => | [ -1.7e+308 (1.7 * 10 raise to power 308) to 1.7e+308 ] | no need to write f or F with double value like double abc = 54.66465747; | ||||||||
char = 8 Bits = 1Byte => | take any characters out of these from 0-127 => ‘a’-‘z’ or ‘A’-‘Z’ ‘&’, ‘@’, ‘0’-‘9’ AND Other symbols | |||||||||
boolean = 1 bit => | true or false = 0 or 1 | |||||||||
bit = 0 or 1 | Signed means it contains negative & positive values AND unsigned means it start from zero | Non – Primitive Data type —>> | is a class and can be access by object | String is non-primitive data type and it is the class defined in Java and its take set of characters/integers or symbols written under double quotes | String store as object | |||||
User defined classes are also as Non – primitive data types and have non – primitive variables which are accessible thru object | Addition obj; > Addition here class name and obj is its object name, Can have multiple data types in it | Array List eee; > Can have rows only, Can have rows & colums, Can have Key : Value pair, Is of one data type | ||||||||
Non-Primitive instance variable has default value null. | Null is a Object in Java with no size and no dimensions | |||||||||
Local variables have no default value and they must be initialized before being used otherwise there is compile- time error. | ||||||||||
Reference Variables –>> | Refers to memory location which stores data Like Null Object and thus value assigned to null object after execution of code | |||||||||
25 | Type casting for Data | Are of two types :- implicit (means happened automatically) & explicit (means need to do intentionaly) | implicit is also called widening like byte to short > int > long > float > double | this convertion happened automatically like short + byte = int by default in java or int + double = double | ||||||
explicit is also called narrowing like double to float > long > int > short > byte | this need to do intennationally by type cast like int = (int) (long + double) | |||||||||
26 | Access Modifiers | public | private | protected | if no modifier given => it is also called default modifier but no keyword to write there | These can be applied to class, variable, method, block & Constructor | ||||
scope/available thru out in same class | available thru out in same class | available thru out in same class | available thru out in same class | |||||||
available to other class in same package | not available to other class in same package | available to other class in same package | available to other class in same package | |||||||
available to other class in different package | not available to other class in different package | available to other class only if this first class is sub class of Called class which means “extends” as Parent – Child relation. Variable from Parent class called with object of current class which created wih new keyword | not available to other class in different package even if “extends” | |||||||
Not available in other project | Not available in other project | Not available in other project | Not available in other project | |||||||
protected methods and variables work with keyword “this” as (current class) object and not with “new” object of extends class ? | ||||||||||
27 | Creation of Object | Object is something which occupies memory, has size and dimensions | When object created, whatever is with class at that time, comes to that object > Simple Means copy of class created which have all the Instance properties | Object can be initialised by Puppy1 pup1; or Puppy1 pup1 = null; Here Puppy1 is the class | also use to create object => packageName.constructor(); | |||||
Box obj = new Box(); :- | Box > | Is the class name > | Its load the class in JVM and also load the static variables and static methods and final variables, final methods | static variables and static methods can be access without object of classs & with the class name | ||||||
obj > | is the object name > | Object is used to access instance variables and instance methods | ||||||||
new > | is the keyword > | New memory allocated and After this keyword, instance variables and instance methods loads in JVM | new keyword also execute instance object created in that class with new keyword and execute constructor which associated with it | |||||||
Box() > | is the constructor of class > | after this, object creation completed | ||||||||
28 | Class Constructor | 1) | Constructors are not Properties of class but variable and methods are. | Constructor is like method with class name and have no return type | ||||||
2) | are used to create object | |||||||||
3) | Puppy = Puppy(); | Left side Puppy is class name and right side is that class constructor | ||||||||
4) | have no return type | |||||||||
5) | constructor can be multiple and can be overloaded inside class | Overloading means : Same name with in same class but arguments or sequence of arguments can be differ | ||||||||
6) | If argument pass on to constructor then it is called Parameterized constructor | If no argument pass then it is called default constructor | default constructor can only be created automatically in class if no any parameterized constructor present so far | If to use default and parametrised constrcutor, then both need to present in class | ||||||
7) | Constructor can be used to initialize instance variable without calling method> | int x ; > Puppy(100); | One class constructor called from other class without extending the first class | |||||||
29 | “this” Keyword | “this” : it is a object and called as calling object and defined as current class – current object | It called implicitly, means automatically. If any instance object or varaible is called (at class level)) then this keyword add automatically. | If same name varaible or object is present in current method and to call instance object then this keyword to use like :- | this.name = name :- | By this statement, local variable assigned to instance variable by using keyword this | ||||
It is not used where static keyword is in use | instance object called when this keyword used or when same name object is not present in current method then “this” keyword fixed automaticlaly but it is in hidden state | class example { float dd = 50.54; void abc() { float dd = 100.11; System.out.println(this.dd); System.out.println(dd);} | ||||||||
local object called with in current method only without keyword this | This print 50.54 as instance variable called with keyword “this” and 2nd ans id 100.11 | instance object called when this keyword used or when same name object is not present in current method then “this” keyword fixed automaticlaly but it is in hidden state | local object called with in current method only without keyword ‘this’ | |||||||
30 | “final” keyword | This keyword is used where to provide value for variable which would not be change at any stage | It can be use before class, method or variable | If final used then value must be given for that variable. | ||||||
final means constant value | final variable cant be change | final method cant be override | final class cant be extend and cannot extend other classes | |||||||
31 | Null Pointer Exception | It is caused when Object refrence is null and trying to access its properties > | class Addition1 { int x = 100; Addition1 add = null; System.out.println(add.x);} | If the object is null even then its know about all the static properties of class of which that object is. So it can show result for static properties | ||||||
null have no size, no dimension, no memory but points to memory location | Printing of x here gives null pointer exception as object “add” have null reference however x was defined. x when merged with any object then it should not be null to avoid NPE. | |||||||||
32 | Escape Sequence | System.out.println(x + ” \” ” + name) > | here \ called as Escape Sequence which means just ignore itself & ignore next character as a code and take it as a String Object – one of member in String value | 10 ” Kamal | these only charters to use after back slash : \b, \t, \n, \f, \r, \”, \’, \\ | |||||
System.out.println(x + ” \” amit \” ” + name) > | 10 ” amit ” Kamal | |||||||||
System.out.println(x + ” \\” amit \” ” + name) > | 10 \” amit ” Kamal | |||||||||
“\n abc “ | Print abc in new line | “\r abc “ | Print abc in next row | |||||||
” \t abc | Print abc after one tab space | |||||||||
” \b abc | Print abc with one back space | |||||||||
33 | Prement Increment | x = 5 > plus plus x (++x) > | This means 1+x = 6 & the value of x this time update as 6 as increment predone to original x | int ab = ++x; System.out.println(ab); System.out.println(x); | ||||||
Post Increment | x = 5 > x plus plus (x++) > | This means x+1 = 6 but the value of x this time remains as 5 as increment done after running this code | int y = 5; int z = y++; System.out.println(z); System.out.println(y); | //this statement increases the value of y by 1 //but will use its current value this time //and next time when you will use y, you will get its incremented value. | ||||||
34 | two == or .equals Operator | two == check the memory location or compare memory location | .equals compare content or value | .equals operator is not applicable to Primitiave Data type | ||||||
abc == xyz variables should have same value then returns boolean true but both objects should made by String Literal Method | abc.eqauls(xyz); should have same value then returns boolean true whether the objects made by String Literal or String Object Method by ‘new’ Keyword | Equality can be check for same data type | ||||||||
Called Object equality | Called Content Equality | |||||||||
35 | 4 Pillars of JAVA | # Polymorphism > | Same name but arguments are differents or sequence is diff. called overloading | Same name and same argument but in other class called overriding | ||||||
# Encapsulation > | variables are private and assigned values by public setter or getter methods | |||||||||
# Inheritance > | aquiring properties of parent class with extends Keyword | Upcasting & Class Casting is also related to it | ||||||||
# Abstraction > | Body for method provide in child class | |||||||||
36 | Polymorphism | Poly means many and morph means forms => means many forms | Polymorphism is of 2 types :- Overloading and Overriding | Overloading means : Same name with in same class > | in this case method name should be same but its number of arguments or sequence of arguments should be different | gives compile time error if something wrong | ||||
Overriding means : Same name with in other class > | ditto same but called with class name | gives Runtime time error if something wrong | ||||||||
37 | Encapsulation | Variables are taken as private and those are assigned values by public getter and setter methods | also called data hiding class | If class have not main method inside it is called entity class and also called POJO class which means Plain Old Java Object. | Encapsulation class is example of entity class and it is used in Page Object Model framework | |||||
Generation of getter setter methods => | private string name; | R.Click on Variable Name > Source > Generate getter & setter > select which one -> after method -> sort by -> generate | ||||||||
38 | Inheritance | this is about to acquired properties of other class by using keyword “extends” | Parent can be class or interface to child class or interface | extends or implements / extends & implements | Is a mechanism where which one object/class acquires all the properties and behaviors of a parent object/class | |||||
all classes inherited from java.lang.object – directly or indirectly | ||||||||||
every class extends object class which called automatically or implicitly if not mentioned otherwise | If Object class already present in same package then extends this local class first | system.out.println(super.name); > super here used to call name variable from Parent class | ||||||||
39 | Overriding (in Polymorphism) | @override | Override is kind of warring and method can be used with or w/o this keyword | >> Static Methods cannot be override | ||||||
public void sleep(){ } | If same method is available in parent class with same arguments or with same sequence of argurments then it is called overriding | It just an indication for developer | >> private method not be inheritted | |||||||
super(); | Calling Parent class constructor | >> final method cannot be override | ||||||||
this(); | Calling child class constructor | |||||||||
super(10, 10) or super(); | at a time, one constructor of parent class called in Child class and that should be metioned to before all inside child class constructor | super(); this is also called default constructor & It called implicitly | ||||||||
class constructor is called in class only, not inside the method | super(); this(); cannot be come together as who so ever written first, same called and consider in execution | |||||||||
40 | Recursive Invocation | If one constructor called and points again to calling constructor which goes on loop then this situation is called Recursive Invocation | On the fly Object OR Anonymus Object :- | If the object created without name like new Animal().run(); then is called as “On the fly OR Anonymus” Object | ||||||
41 | Upcasting | Animal a1 = new Dog(); | Here Animal is the Parent class & Dog & Bird are Child classes | a1 have state of instance variable & instance method of Parent class and method state of child class and execute method of child class during runtime | During upcasting approach, Methods execute from Child class but the variables are called from Parent class i.e. instance variables | In other words, Object have knowledge of all the properties of Parent class and only methods of child class | UPCASTING is from Parent to Child, not from child to parent while creating object, Child obj = new Parent() is wrong | |||
Animal a2 = new Bird(); | Reference of Parent class and Object here created of Child class | Parent class called here as Reference class and child class called as object class | Same name method need to be present in Parent class and in child class then child class method execute implicitly otherwise class casting need to use | |||||||
If Animal extends to Bird, Bird extends to Dog then obj.Method() executes method from the first child class like dog, if not availble there then execute from next child class like bird and final from parent class if not available in any child class | If Animal extends to Bird, Bird extends to Dog then obj.Constructor() executes constructor from top most parent class, then next parent class and then finally execute from Child / current class constructor | DMD (Dynamic Method Dispatch) or run time Polymorphism :- | During run time, it is decided to execute method of Child class if upcasting approach used. Run from upper child class even if method is not available in lowest child class | If the methiod is static and present in child and parent class both then @override annotation is not applicable and method run from parent class only during runtime | ||||||
42 | Class Casting | ((Dog)a1).runFast(); | Here run Fast method is not available in parent class i.e. Animal so Child class casting is need to provide to confirm executon of method in child class i.e. dog. This is called Class casting | When method not present in parent class and have in child class and to execute from child class, class casting is required | ||||||
43 | instanceof Operator | returns boolean value like true or false > | boolean flag = a1 instanceof Animal; | This retuns true as a1 is object of Dog class which is the child class of Animal class (Parent Class) | instanceof here means contains…… | |||||
44 | Interface | all methods are abstract inside interface. abstract keyword is optional | Body to Method is must given inside child class who implements it. Body here means logic/statements which to execute when that interface/method called | used for declaration not to define. we can implement multiple inteface in single class with keyword “implements”. if interface public then its member are public also. We can inherit interface within interface with kewords “extends”. | public class abc implements Football, Basketball { } | public interface Football extends Basketball { } | Football and Basketball both here are interfaces | |||
public interface Football { public void startRun(); } | OR public interface Football { public abstract void startRun(); } | Interface have 100% abstract methods and body / logic is to provide in class or can implement customised logic in class | Interface have no constructors | private & protected modifiers are not allowed in interface | ||||||
variables can be provide inside interface but those are “public static final” | In jdk version 8 or called as 1.8 > By using default keyword, body can be given inside interface to abstract method which can be available to all child classes without implementing it in class > | default void print() { statements; } > Called with > | ClassObjectName.print(); | |||||||
Also the public static void method can also be use in interface in jdk 1.8 > | public static void print() { statements; } > Called with > | interfaceName.print(); | ||||||||
45 | Abstract Methods | If only signature given for method without Body then it is called Abstract Method > | abstract void setName(String name); | abstract methods are not be final | ||||||
By default all abstract methods are public | abstract public void multiplication(); | |||||||||
abstract methods are meant to Overriden in child class | public abstract void division(); | |||||||||
46 | Abstract Class | The class which can have abstract methods or solid Methods or both [Solid methods means normal method who have body] | Keyword: abstract class abc { } or public abstract class abc { } | It is concept of Logic hiding > | Abstract classes have a rule that if the class contains even a single abstract method, it is mandatory to declare class abstract but if the class is abstract, it may or may not have abstract methods. | |||||
No Object can be created for abstract class | MyFirstAbstractClass1 obj = new ClassSolid(); By upcasting approach, constructors from top most parent class run first, then from Junior class and lastly from child class | we can not use abstract with final keyword and also you can’t use abstract with static keyword. | ||||||||
47 | Random Class | Returns int from 0 to 1 upto 12 decimal points > | 0.012345679 | |||||||
This Method in Math class > | Math.random(); | |||||||||
48 | String Class | String V1 = “Ram”; | Called String Literal | created new object, if updated then also new object created | Two objects created by String Literal have same value then points to same memory location | |||||
String V2 = new String(“Sham”); | Called String Object | always created new object, if updated then also new object created | ||||||||
In string class, whenever new value store, new object created in JVM memory every time > | If, V1 = V1.concat(“123”); => Ram123 => New object created in memory, not updated the earlier stored V1 memory > | This is the reason, String class called immutable | ||||||||
49 | String Interning Property | String abc = “abc”; | These two objects, created by String literal, have same value, points to same memory location in string pool and is called String interning | |||||||
String xyz = “abc”; | ||||||||||
String ddd = new String(“abc”); | This always create new Object in the memory location. | |||||||||
Object abc & ddd are different and have different memory location> | abc = ddd.intern(); > | This merge the memory location of both variables having same content | Not working in code? | |||||||
50 | index of | println(abc.indexOf(“c”); > | returns int, first occurence of c > 2 | (abc.indexOf(“Gon”)); > give index of starting character | ||||||
println(abc.lastIndexOf(“c”); > | returns int, returns last occurence of c > 3 | |||||||||
println(abc.indexOf(“z”); > | returns int, if no value present then retuns negative value > -1 | |||||||||
51 | charAt() | println(abc.charAt(2)); > | returns character at that index > c | Index start from 0 | ||||||
length() | abc.length(); | Returns int as Total count. abc is the variable | count start from 1 | |||||||
52 | compareTo | int x = abc4.compareTo(abc3); > | retunrs int in positive and negative value | It is not applicable to primitive type | ||||||
If abc4 > abc3 => | retuns + integer | |||||||||
If abc4 < abc3 => | retuns – integer | |||||||||
If abc4 = abc3 => | retuns 0 | |||||||||
53 | Garbage Collection | Delete unused objects from memory. | abc = “Raghu”; | |||||||
We can tel JVM for the unused object but its upto JVM when to delete it | abc = null; > | this tell jvm that it can delete object Ragu now and this called garbage collection | ||||||||
Garabage collection never be final, its depends on JVM to execute it or not | abc = “Sham”; | |||||||||
54 | String Buffer Class | Its mutable class | StringBuffer sb = new StringBuffer(“abc”); | sb.append(“john”) > john ad up to abc in same memory location > abcJohn | sb.toString(); print object value to string | |||||
(Similar have String Builder Class) | New value update at same memory location of same object | StringBuffer sb = new StringBuffer(); | sb.replace(0, 6, “123”); > | Startig from 0, at 6th index, replace 123 > abcjoh123 | ||||||
All values update at same location if two objects of same name, both the objects created by ‘new’ keyword | sb.replace(0, sb.length(), ” “); > | Startig from 0, at entire lenght, replace empty String > ans is nothing | ||||||||
55 | Loops | for > | for(initialize; Check Condition; Increment/Decrement;) { statement; } | for(int i=1; i<=5; i++;) { prinln(i) } | For every iteration of outside for loop, the nested for loop initializes itself(starts from beginning) | |||||
while > | initialize; while(check condition) { statement; Increment / Decrement;} | int i=1; while(i<=5) { prinln(i); i++; } | ||||||||
do – while > | initialize; do{ statement; Increment / Decrement;} while(check condition); | int i=1; do{ prinln(i); i++; } while(i<=5); | ||||||||
enhanced for loop > | for(Collection_type New_Obj_Name : That_Collection_Object_ from which data to get) { statement; } | for(collection_of_String ob1_name: ArrayOb2) { } | ||||||||
56 | if – else Conditions | if() { } | if only one statement is to provide for condition then curly brackets not required | |||||||
else if () { } | ||||||||||
else { } | ||||||||||
57 | Operators & && | || | & | AND operator checks both the conditions in if condition | Binary Operator | if(i=1 & i.length()=5) > returns NPE as i is null and 2nd condition gives NPE | |||||
&& | AND AND operator do not check 2nd condition in if condition if the first condition returns false | Logical operator and also called Short circuit operator | if(i=1 && i.length()=5) > returns nothing as first condition fails | |||||||
| | OR operator checks both the conditions in if condition | Binary Operator | When NPE comes, Code does not execute ahead. | |||||||
|| | OR OR operator do not check 2nd condition in if condition if the first condition returns true | Logical Operator | ||||||||
58 | Ternary Operator | int result = val.equals(“ram”) ? 55:100; | If val is equal to ram then return 55 or otherwise 100 | |||||||
59 | break; & continue; | break – exit from loop > | After this keyword, code written ahead does not excute for current loop also terminate the loop counter as well | continue – Skip one iteration / iterations as per the condition given and execute loop > | After this keyword, code written ahead does not excute for current loop but start next loop | |||||
60 | Arrays | Size must need to provide | int[] arr1 = new int[5]; | print(arr2.toString()); returns array values. OR Arrays.toString(arr2); -> returns arrays values | Important Method :- Arrays.asList() :- convert Array to List | String capitalArray[] = {“Oslo”, “Stockholm”, “Washington”, “Copenhagen”, “Seoul”, “Rome”, “Madrid”}; String countryArray[] = {“Italy”, “Norway”, “South Korea”, “United States”, “Spain”, “Denmark”, “Sweden”}; | ||||
arrays can be of Primitive and non primitive type | int[] arr2= {1, 2, 3, 4, 5}; //Array initialize | print(arr2); returns junk value. or called hash code value | This method takes the array which is required to be converted into a List. | List<String> countryList = Arrays.asList(countryArray); | ||||||
array have homogenous data – same type data | int [] arr2 = null; //Array initialize | arr2.length; – returns size. | return a fixed-size list backed by the specified array. | |||||||
It has AIOBE – Array Index Out of Bound Exception | arr2 [0] = 1; //adding element to array at this index | arr2[1].length; – returns value at that index. ?? | The returned list is serializable and implements RandomAccess. | |||||||
Arrays are collections of objects with the same type of a defined size. We access elements in an array using an index object, and can initialize arrays both with and without elements. | arr2 [1] = 2; | StringObject.length(); – returns count. | This method acts as a bridge between array-based and collection-based APIs, in combination with Collection.toArray() | |||||||
elements to array can be provide at the time of initialize, otherwise if it declare only then elements add with index values one by one | int [] arr3; //Array declare | String val = “ravi; kani; sham”; String[] arr3 = val.split(“;”); ? | ||||||||
If array size given then it is still possible to add element in that but that cant be execute/print and give error out of bound | int [] arr6 ; // NO! Initializers can only be used in declarations // arr6 = { 1, 2, 3, 4, 10, 11, 12 } ; | < Gives error as values can be given only when declare | ||||||||
61 | Arrays vs Collection | Arrays | Collection | |||||||
Arrays are fixed in size | Expands and Collapse automatically | |||||||||
Store same data type | Hold multiple data type | |||||||||
Store primitve and objects | Stores only object | |||||||||
62 | String to Integer thru parseInt | System.out.println(Integer.parseInt(args[0]) + Integer.parseInt(args[1])); | args here can be like > | args = argumentsForMain(); | String args[] = {“1”, “2”}; | |||||
This convert String to Integer and perform mathematical operation | public static String[] argumentsForMain() { String arr4[] = {“1”, “0”}; return arr4; } | String number1 = “40”; String number2 = “50”; | System.out.println(Integer.parseInt(number1) + Integer.parseInt(number2)); | |||||||
63 | Wrapper Classes | Eight in number | Stores object of primitive data type by accepting primitive value | Number num = new Long(999999); | Integer obj2 = new Integer(5); double ll = obj2.doubleValue(); This is method in Integer class and returns value in double | AutoBoxing :- | If primitive data type value input then it automatically converts to wrapper class called autoboxing | |||
Byte, Short, Integer, Long, Float, Double, Character, Boolean | Numerical classes extends from abstract Number class | Integer num2 = new Integer(789); | same meaning as Integer num5 = new Integer.valueOf(789); It does not accept string value | UnBoxing :- | If result to get in primitive data type then it automatically convert wrapper class object to primitive data type called unboxing | |||||
Short num3 = new Short((short)100); //?? | int xx =Integer.parseInt(“12”); //takes in string & returns integer value | |||||||||
Integer num4 = new Integer(“abc”); // If string convert in integer value then it shows that otherwise gives Number Format Exception | ||||||||||
64 | Collection Framework | have interface & classes in package java.util; | store objects and not store primitrive data type | |||||||
Iterable Interface | It has iterator() method | which returns object of Iterator Interface & Use to read collection | top in hierarchy, all the collection interfaces like List, Set, Map automatically implements iterable interface | |||||||
Iterator Interface | have following methods :- | ArrayList al = {1, 2, 3, 4,5 }; | ||||||||
hasNext() | returns boolean, to check if there is element in collection | iterator itr = al.iterator(); | iterator methods returns object of iterator interface from collection | |||||||
next() | returns object of collection | while(itr.hasNext()) | ||||||||
remove() | returns void, remove element from collection | {System.out(itr.next()); } | ||||||||
Collection Interface | Collection coll = new ArrayList(); Collection Print all values but Array print Junk Value and Collection have methods > | .add(“abc”) | returns boolean >> [add element] to collection | |||||||
.remove(“abc”) | returns boolean >> [remove element] from collection | |||||||||
.contains(“abc”) | returns boolean >> used to search an element | |||||||||
.clear() | returns void >> remove all elements from Collection | |||||||||
.isEmpty() | returns boolean | |||||||||
.size() | returns int >> total nos of Elements in Collection | |||||||||
Collections.sort(List_Object) & Collections.reverseOrder(); | Sort the List in accending order & reverse the order of current object | |||||||||
Interfaces of Collection down in Hierarchy :- | List Interface | Set Interface | Map Interface | |||||||
can have duplicate elements | no duplicate elements | Elements in Key Value pair, cant have duplicate Keys | Map object need to convert in Set object to read via Map.Entry Interface | |||||||
have Methods > | add(1, “abc”) > insert abc at index 1 and shift earlier elements to next index, returns void | have Methods > | add(1, “abc”) > returns false if duplicate value added in collection | have Methods > | Set<Map.Entry<Integer,String>> setObj = mapObj.entrySet();, Set<Integer> setObj = mapObj.keySet(); | |||||
get(5) > returns value at index 5 | entrySet() > returns all entries | |||||||||
set(1, “xyz”) > replace xyz at index 1 | keySet() > return all Keys | |||||||||
indexOf(“abc”) > return index of first occurrence of value abc | put(Key, Value) > add entry in Map object | |||||||||
lastIndexOf(“abc”) > return index of last occurrence of value abc | entry(Key, Value) | |||||||||
get(Key) > return value at that key | ||||||||||
getKey() > return Key | ||||||||||
getValue() > return Key Value at key in just above method | ||||||||||
have classes :- | Java new generic collection allows you to have only one type of object in a collection. ArrayList<String> al=new ArrayList<String>(); | have classes :- | have classes :- | |||||||
ArrayList Class > | maintain insertion order | HashSet > | returns element in Random Order due to mechanism Hashing (each object awarded hash code value which then return in accending order), allow one null value | HashMap > | returns keys in Random Order, have one null key | |||||
LinkedList Class > | maintains insertion order & have methods :- getFirst(); getLast(); addFirst(); addLast(), addAll(object) | LinkedHashSet > | returns element in inserted Order, allow one null value | LinkedHashMap > | returns keys in inserted Order, have one null key | |||||
Vector Class > | its Synchronised Class and hence slow | Sorted Set Interface > | Sorted Map Interface > | |||||||
TreeSet Class > | returns element in accending Order, contains one type of elements only, does not allow null value | TreeMap Class > | returns keys in accending Order, no null key | |||||||
65 | Exception Handling | Exception come during runtime which abruptly stops the execution of program | try { } catch(Exception e) { System.out.println(e.getClass().getName() + ” ” + e.getMessage()); } finally { } | method() throws FileNotFound, NullPointerException or Exception {} > this provide multiple exception | If the exception is handled in corresponding catch block, then normal flow of the program continues after executing “finally” block | If the exception is not handled, then the program ends execution abruptly after executing “finally” block | Error Class Exceptions :- | |||
When exception occurs inside method, it create Exception object and handover it to JVM, If exception handling not used in code then JVM handover exception to default exception handler which show exception detail in console and abruptly close the program. | multiple catch can be used with one try, Only finally can also be use with try w/o catch | method() throws Throwable { } < it means same as Exception, which is equal to throw Exception {} | throws or throw > throw new RuntimeException(“delibrate end”); | 1) OutOfMemory | ||||||
Some Types of Exception :- | Exception is the parent class of All type of Exceptions. catch(Exception e) is the top in hierarchy and its always comes down in line while writing code as when execution transfer to this then it catches the error and abruptly close the furthur execution of code | compile time exception – called checked exception | throw is used to deliberately/explicitly end the execution of code like > | 2) VirtualMachineError | ||||||
1) Airthmetic Exception | 3) AssertionError | |||||||||
2) NullPointer Exception | ||||||||||
3) ArrayIndexOutOfBounds Exception | ||||||||||
4) Runtime Exception | catch(RuntimeException e) { Print} | Runtime exception – called unchecked exception | ||||||||
5) Exception | ||||||||||
6) NoSuchElementFound Exception | ||||||||||
7) FileNotFound Exception | ||||||||||
8) NumberFormat Exception | Unchecked Exceptions >> | << Checked Exceptions | ||||||||
File Input, File Reader & exception Message | try { File file = new File(“\\user\\abc”); FileReader fr = new FileReader(file); } catch(Exception e) { System.out.println(e.getClass().getName() + ” –> ” + e.getMessage()); } | java.io.FileNotFoundException –> \user\abc (No such file or directory) | ||||||||