0% found this document useful (0 votes)
7 views

Java CheatSheet

Uploaded by

zahidzainad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Java CheatSheet

Uploaded by

zahidzainad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Java Programming Data Type Conversion • Static Array: size is fixed.

Data Type Conversion • Static Array: size is fixed. you have to manually increase the size of array. To Method Overloading
Java is a high level, general purpose programming language that produces software for multiple • Widening (byte<short<int<long<float<double) solve this issue we use -- ArrayList (dynamic Array) • Method Overloading is a feature that allows a class to have more than one method
platforms. It was developed by James Gasling in 1991 and released by Sun Microsystems in int i = 10; int ——>long • cannot store different data types. to solve this, use (ArrayList or Object having the same name, if their argument lists are different
1996 and is currently owned by oracle. long I = i; automatic type conversion Static Array) • Three ways to overload a method—login() is a good example here.
• Java is a programming language as well as a Platform • Narrowing • Declare and initialize one dimensional Array • Number of Parameters
• It is open source double d = 10.02; • Syntax for default values: int[] num = new int[5]; num[0]= 1; …. add(int, int)
long I =(long) d; explicit type casting • “ArrayIndexOutOfBoundsException" add(int, int, int)
Java Installation: • Syntax with values given: int[] num = {1,2,3,4,5}; • Data Type of Parameters
• Check if you have java installed: CMD >> java –version • Numeric Values to String • size of array: (num.length)it is NOT a method. add(int, int)
• Download JDK 1.8 from oracle website String str = String.valueof(value); • Sort array in ascending order: Arrays.sort(num); //sort() method is a java.util.Arrays class add(int, float)
• Java Development Kit • String to Numeric Values • how to print all the values of array: for loop • Sequence of data type parameters
int intValue= Integer.parseInt(str);
• Inside JDK, we have JRE (Java Runtime Environment). It gives an environment double doubleValue = Double.parseDouble(str); • Object Static Array : it only allows to store different data types but still static. add(int, float)
add(float, int)
to execute your code Object empData[] = new Object[3];
• It is platform independent. empData[0] = "Tom"; • If two methods have same name, same parameters and have different return type, then
String A = “100k”; >>cannot be converted and it throws: NumberFormatException this is not a valid method overloading
• Eclipse: Java Editor— used to write and run the code. (other IDEs: Netbeans, intelliJ) empData[1] = 25;
int add(int, int)
• For JDK 32 bit you have to download Eclipse 32 bit and vice versa. Decisive Statements empData[2] = 'm';
float add(int, int)
• If statement: Dynamic Array (ArrayList) : • Method overloading is an example of compile time polymorphism (many-forms)
How to get the author Before public class: if(condition){ • Can store any valued with different data types
/** Statement(s); }
* @author Ramsey • Create the object of ArralyList (it is a class in Java) ArrayList ar = new ArrayList(); Static Block, Methods and Variables
* This class is to understand data types in java • Nested if statement: When there is an if statement inside another if statement • add() to add value : • Static members are common for all the instances (objects) of the class but non-static
*/ if(condition_1) { • size() size of array: No length members are separate for each instance of class.
Statement1(s); • remove() removes on the basis of index //if removed, the size will • Memory is divided into two parts: Heap & Stack. When you create the object, it will be
General tips if(condition_2) { automatically adjusted. created in Heap section. Static methods will be stored in a section in Stack memory sec-
• Declaration: Declaration is when you declare a variable with a name, and a variable can Statement2(s); }} • get() gets the value of index tion and is called “Common Memory Allocation”
be declared only once. Example: int x; String myName; Boolean myCondition; • How ArrayList work internally?
• Initialization: is when we put a value in a variable, this happens while we declare a • If-else statement • The moment the object is created, virtually it is divided into 10 parts. Static Block
variable. Example: int x = 7; String myName = "Emi"; Boolean myCondition = false; if(condition) { (Default Capacity) • Static block is used for initializing the static variables
• Assignment: Assignment is when we already declared or initialized a variable, and we are Statement(s);} • Physical/actual size: the moment you add values in object. the remaining is • A class can have multiple Static blocks, which will execute in the same sequence in which
changing the value. You can change value of the variable as many time you want or you else { virtual size. they have been written into the program.
need. Statement(s); } • .size() gives you the actual size of the object. class JavaExample{
static int num;
• Class: A class can be defined as a collection of objects. It is the blueprint or template that
• If-else-if statement: • The moment the virtual size is 0, memory automatically increase it by 10. static String mystr;
describes the state and behavior of an object. this cycle continues.
Local variable: is a variable which we declare inside a Method. A method will often store • Switch statement is used when we have number of options (or choices) and we may static{
• need to perform a different task for each choice. • if you want to reach the virtual memory in the print console, it gives you num = 97;
its temporary state in local variables. "IndexOutOfBoundsException"
• class variable: Instance variable is a variable which is declared inside a Class but outside a • Case doesn’t always need to have order 1, 2, 3 and so on • to print all the values from ArrayList: for Loop
mystr = "Static keyword in Java"; }
public static void main(String args[]) {
Method. They can be both static and non static. If they are common among all methods, • You can also use characters in switch case • Generics in ArrayList. if not specified, you can store values of different type and it gives System.out.println("Value of num: "+num);
you can store it as static. You cannot create a static variable inside only one method. • The expression given inside switch should result in a constant value other- you warning. to remover the warning, we insert the data type Class System.out.println("Value of mystr: "+mystr); } }
• Class Name starts with Capital Letter wise it would not be valid ArrayList<Integer> marksList = new ArrayList<Integer>();
• Number at the beginning is not allowed; • Break statements are used when you want your program-flow to come out ArrayList<Double> bmiList = new ArrayList<Double>(); Static Variables
• Package name starts with lower letter. of the switch body. Break only works for loop and switch case NOT if state- ArrayList<String> studentNameList = new ArrayList<String>(); • A static variable is common to all the instances (or objects) of the class because it is a
• All keywords in Java start with lower case.
ment. • Difference between Array and ArrayList? class level variable
• Duplicate variables are NOT allowed in java.
switch (variable or an integer expression){
case constant: • Array • Static variables are also known as Class Variables.
• 1 byte (Ba’ayt)= 8 bits (Beets) //Java code; • Array is static • Unlike non-static variables, such variables can be accessed directly in static and non-
break; • Size of the array should be given at the time of array declara- static methods.
tion. We cannot change the size of array after creating it class JavaExample3{
Primitive Data Type (Java Memory Management) case constant:
//Java code; • Array can contain both primitive data types as well as objects static int var1;
break; • Arrays are multidimensional static String var2;
default: • ArrayList Static Methods
//Java code, acts as else condition in if statement; } • ArrayList is dynamic • Static Methods can be access without using object (instance) of the class, however non-
• Size of the array may not be required. It changes the size dy- static methods and non-static variables can only be accessed using objects.
Iterative Statements: Loop is used to avoid repetitive tasks. namically. Capacity of ArrayList increases automatically whenev- • How to call static methods: (No need to create the object of the class)
• While loop er we add elements to an ArrayList public static void getSchoolName( ){ }
While (condition) {expression} • ArrayList cannot contain primitive data types. It contains only • Call by class name className.getSchoolName();
int i = 0; // initialization objects • Call directly getSchoolName();
while (i <= 10) { // conditional • ArrayList is always single dimension • How to call non-static methods
System.out.println(i); // logic
i = i + 1; // Incremental className obj = new className();
Functions = methods obj.getSchoolName();
• Do while loop public void nameOfFunction( ){ } • Can you call static methods using object of the class? Yes, but IDE gives a warning bcz the
public static void main(String args[]){ • The purpose is usability object created occupies unnecessary space.
int i=10; • return variable; • Can we override/overload main method? Explain the reason? Can you override static
• A few points in Data Type do{ • void does not return anything method?
• float f1 = (float) 12.33;
System.out.println(i); • psvm is a function • We cannot override static method, so we cannot override main method.
• float f2 = 12.45f;
i--; • We cannot create a function inside the function but we can call them • However, you can overload main method in Java. But the program doesn't
• char c1 = 'a';
}while(i>1); } • Duplicate functions are not allowed execute the overloaded
• true and false are keywords in java • For loop—the initialization, condition and increment all are written in one line
• Types of Functions:
For (condition) {expression} • System defined functions (arraylist.size()) String
String Concatenation (Merging) for (int p = 1; p <= 10; p++) { // Starting point, Ending Point, Increment • User defined functions In java, a String is an object that represents a sequence of characters. java.lang.String class is
• Concatenation Operator = + System.out.println("Loop " + p); } • No input No return used to create String object. String is a collection of multiple characters including spaces.
public void test(){ Creating a String:
• Execution is done from left to right. • String str1 = “Welcome”; //using literal String
• int age = 25; • for - if - break System.out.println("test method");
• Str2 = new String (“Welcome”) //using new keyword
for (int number = 0; number <= 10; number++) { }
System.out.println("age of Tom is "+age); System.out.println(number); • No input SOME return Methods of Strings:
• you can do any arithmetic operation inside the Sysout if (number == 5) { public ArrayList<String> getPlayersName(){ String str = "I love java but I do not like javascript";
System.out.println(100 - 20); System.out.println("Ali is not here"); System.out.println("getPlayersName"); • str.length() //returns the number of characters presents in the string . Starting
• First inside parentheses are computed break; } } ArrayList<String> ar = new ArrayList<String>(); from 1 not 0. Here 37
System.out.println(x + z + (a + b)); ar.add("Virat"); • str.charAt(37) //extract i’th character. Here “t”
• Exception: only for byte (it automatically converts to int) • Enhanced for loop: Enhanced for loop is useful when you want to iterate ar.add("Sachin"); • str.charAt(38) //StringIndexOutOfBoundsException — if you go beyond str length
byte ba = 100; Array/Collections, it is easy to write and understand. ar.add("Sunil"); • str.indexOf(“I”) //pass the character and it gives the index number. Here 0
byte bb = 50; public static void main(String args[]){ return ar; } • str.indexOf("j", str.indexOf("j")+1)); //2nd j
byte diff = (byte) (ba - bb); int arr[]={2,11,45,9}; • Some input SOME return • str.indexOf("java") //7 it gives you from where java started
• Concatenate char: each char on the keyboard is assigned a value based on ASCII table. for (int num : arr) { public String getCountryCapital(String countryName){
• str.indexOf("Ramsey") //No exception. Returns -1
Then, when concatenated, instead they will give value in return. System.out.println(num); } } System.out.println("get Country Capital");
char c11 = 'a'; if(countryName.equals("India")){ • str.trim() //removes spaces from corners
char c12 = 'b'; Incremental & Decremental return "New Delhi"; //return inside if statement • str.replace("I", "You") //search and replace
System.out.println(c11 ); //return a int a = 1; } • str.replace(" ", "") //removes the spaces between words
System.out.println(c11 + c12); //return 195 int b = a++; else if(countryName.equals("USA")){ • str.toUpperCase() //returns string in ALL CAPS
post increment: give value of a to b, then increment a by one. returns 2 and 1 return "Washignton DC";
}
• str.toLowerCase() //returns string in ALL LOWERCASE
Java Operators else if(countryName.equals("Russia")){ • str.equals(“I love java but I do not like javascript”) //comparing two strings
• Assignment operator = int p = 1;
return "Moscow"; • Str.compareTo(“I love java but I do not like javascript”) //comparing two strings
• Comparison operator == int q = ++p;
} • Str.equalsIgnoreCase(“i Love java BUT I do not like javascript”)
• Not equal to != ! pre increment, returns 2 and 2
return null;} returns Nothing—mostly in If statement • Str.contains(“java”) //check for values
• Short circuit operator && int m = 2; • Sub String: it returns the substring of String
int n = m--; Another example: String s2 = "your total amount is 1500 USD";
post decrement, returns 1 and 2 public boolean isUSCitizen(String personName){ System.out.println(str.substring(21, s2.indexOf("USD")-1)); /give beg and end index
System.out.println("isUSCitizen method"); System.out.println(str.substring(0)); /from beginning till end
int g = 2; if(personName.equals("Naveen")){ • Split a string on basis of something. Converting String to Array
int h = --g; return false; String lang = "Java-Python-JavaScript-Ruby"; //it can be also based on space
pre decrement, returns 1 and 1 } String language[] = lang.split("-"); //stores in array.
else if(personName.equals("Elena")){ System.out.println(language[0]);
int c = -2; return true;
}
• Converting Array to String: Array.toString();
int d = --c;
return false; • Difference between String and StringBuffer? The most important difference between
pre decrement, returns –3 and –3 String and StringBuffer in java is that String object is immutable whereas StringBuffer
object is mutable.The StringBuffer class in java is same as String class except it is mutable
• How to call a function—create the object of the class : use the new keyword. The right i.e. it can be changed. By immutable, we mean that the value stored in the String object
Arrays in Java hand side of = is object. obj is only object reference name. when created, all the methods cannot be changed.
• Arrays: stores multiple values in a variable. created inside the class will be copied in object.
• There are two types of Array: One dimensional Array & Multidimensional Array L06FunctionsConcept obj = new L06FunctionsConcept();
Static Array: obj.test();
• Two Major Limitations of Static Array:
Object Oriented Programming in Java class A {//your parent class code} make use of it as you can implement more than one interface. • INTERFACE
• Java is an Object Oriented Programming language that produces software for multiple class B extends A {//your code} • class implements interface but an interface extends another interface. • To declare Interface we have to use interface keyword
platforms. An object-based application in Java is concerned with declaring classes, cre- class C extends B {//your code} • We can’t instantiate an interface in java. That means we cannot create the object of an • In an Interface keyword abstract is optional to declare a method as an ab-
ating objects from them and interacting between these objects. • Hierarchical inheritance: refers to a child and parent class relationship interface stract. Compiler treats all the methods as abstract by default
• OOPS stands for Object Oriented Programming System. It includes Abstraction, Encapsu- where more than one classes extends the same class. For example, classes B, • Interface provides full abstraction as none of its methods have body. • An interface can have only abstract methods
lation, Inheritance, Polymorphism, interface and.. C & D extends the same class A. • Class that implements any interface must implement all the methods of that interface, • An interface provides fully abstraction
class A {//your parent class code}
class B extends A {//your child class code}
else the class should be declared abstract. • An interface can have only public abstract methods
Java Object • Interface cannot be declared as private, protected or transient. • An interface can have only public static final variables
class C extends A {//your child class code} •
• An object is an instance of a class. Objects have state (variables) and behavior (methods). • Hybrid Inheritance: Combination of more than one types of inheritance in a
All the interface methods are by default abstract and public. • An interface can extend any number of interfaces
Example: A dog is an object of Animal class. The dog has its states such as color, name, single program • Interface variables must be initialized at the time of declaration otherwise compiler will • Interface supports multiple inheritance
breed, and behaviors such as barking, eating, wagging her tail. throw an error.
• Declaring and initializing an object • A class can implement any number of interfaces. When to use abstract class and interface in Java?
Test t = new Test(); • A class cannot implement two interfaces that have methods with same name but differ- • An abstract class is good if you think you will plan on using inheritance since it provides a
ent return type common base class implementation to derived classes.
Constructor interface MyInterface{
• An abstract class is also good if you want to be able to declare non-public members. In an
• Constructor is a block of code that initializes the newly created object. it doesn’t have a • The derived class inherits all the members and /* compiler will treat them as:
interface, all methods must be public.
* public abstract void method1();
return type. People often refer constructor as special type of method in Java. Constructor methods that are declared as public or protected. If the members or methods of super
* public abstract void method2(); */ • If you think you will need to add methods in the future, then an abstract class is a better
has same name as the class and looks like this in a java code. class are declared as private then the derived class cannot use them directly. The private choice. Because if you add new method headings to an interface, then all of the classes
members can be accessed only in its own class. Such private members can only be ac- public void method1();
public MyClass() { public void method2(); } that already implement that interface will have to be changed to implement the new
System.out.println("default const");} cessed using public or protected getter and setter methods of super class as shown in the methods. That can be quite a hassle.
example below. class Demo implements MyInterface {
/* This class must have to implement both the abstract methods
• Every class has a constructor whether it’s a normal class or a abstract class. * else you will get compilation error*/ final Keyword
• The new keyword creates the object of class and invokes the constructor to initialize this class Teacher {
private String designation = "Teacher"; public void method1() { System.out.println("implementation of method1");} • final variable: Once a variable is declared as final, then the value of the variable could not
newly created object. private String collegeName = "Beginnersbook"; public void method2() {System.out.println("implementation of method2"); }
• Methods like constructors method can also have name same as class name, but still they be changed. It is like a constant. final int AGE= 12;
have return type, though which we can identify them that they are methods not con- public static void main(String arg[]) { • It is considered as a good practice to have constant names in UPPER CASE
public String getDesignation() { (CAPS).
structors. MyInterface obj = new Demo();
• Constructor overloading is possible but overriding is not possible.
return designation; }
obj.method1(); } } • final method: A final method cannot be overridden. Which means even though a sub
protected void setDesignation(String designation) { class can call the final method of parent class without any issues but it cannot override it.
• Constructors can not be inherited. this.designation = designation; } • final class: We cannot extend a final class . No class can extend the final class.
• Types of constructors: protected String getCollegeName() { What is the difference between interface and a class? Example from your framework?
• Default: If you do not implement any constructor in your class, Java compiler return collegeName; } • Class: • A few more points:
inserts a default constructor into your code on your behalf. You would not protected void setCollegeName(String collegeName) { • Class will contain concrete methods • A constructor cannot be declared as final
find it in your source code (the java file) as it would be inserted into the code this.collegeName = collegeName;} • Class is extended • All variables declared in an interface are by default final
during compilation and exists in .class file. If you implement any constructor void does(){ • We can create an Object of the class
then you no longer receive a default constructor from Java compiler. System.out.println("Teaching"); } } • Class can inherit only one Class and can implement many interfaces final, finally and finalize
• No-arg: The signature is same as default constructor, however body can have • Interface • Final
public class JavaExample extends Teacher{ •
any code unlike default constructor where the body of the constructor is
String mainSubject = "Physics"; • Interface will have Interface keyword. It is keyword
empty.
public static void main(String args[]){ • Interface will contain only abstract methods • Used to apply restrictions on class, methods and variables
public Demo() { •
System.out.println("This is a no argument constructor"); } JavaExample obj = new JavaExample(); • We cannot create object of interface Final class cannot be inherited
• Parameterized: Constructor with arguments (or you can say parameters) is /* Note: we are not accessing the data members directly we are using • Interface needs to be implemented • Final method cannot be overridden
known as Parameterized constructor. public getter method to access the private members of parent class*/ • Class can extends many interfaces • Final variable cannot be changed
Employee(int id, String name){ System.out.println(obj.getCollegeName()); • We need to provide implementation to all methods when we implement • Finally
this.empId = id; System.out.println(obj.getDesignation());
System.out.println(obj.mainSubject);
interface to the class • Is a block
this.empName = name; } obj.does(); } } • Practical Example: Basic statement we all know in Selenium is • Used to place important code
• Difference between Constructor and Method • Up Casting: Child class object can be referred by parent class reference variable parent p
WebDriver driver = new FirefoxDriver(); • It will be executed whether the exception is handled or not
• The purpose of constructor is to initialize the object of a class while the = new child(); — it is like putting a small box into a larger box.
WebDriver itself is an Interface. We are initializing Firefox browser using Selenium WebDriver. It • Finalize
purpose of a method is to perform a task by executing java code. means we are creating a reference variable (driver) of the interface (WebDriver) and creating an •
• Reference Type concept: in this object created, you can access methods and Finalize is a method
• Constructors cannot be abstract, final, static and synchronised while meth- data members of parent, overridden but NOT child class because of men-
Object.
Here WebDriver is an Interface and FirefoxDriver is a class. • Used to perform clean up processing just before the object is garbage col-
ods can be. tioned rule. lected.
• Constructors do not have return types while methods do. • Down casting: BMW b1 = (BMW) new car(); - we never use Abstract
• It is fine in compile time but it gives you Exception during run time: Class- • Abstraction is a process where you show only “relevant” data and “hide” unnecessary
Polymorphism
Encapsulation CastException details of an object from the user. Example: Mobile Phone. • Polymorphism allows us to perform a task in multiple ways. Let’s break the word Poly-
• Encapsulation is also known as “data Hiding“.
• A layman who is using mobile phone doesn’t know how it works internally morphism and see it, ‘Poly’ means ‘Many’ and ‘Morphos’ means ‘Shapes’.
• If a data member is private it means it can only be accessed within the same class. No Method Overriding but he can make phone calls. • Assume we have four students and we asked them to draw a shape. All the four may
outside class can access private data member (class variables and Class methods) of other • When we declare the same method in child class which is already present in the parent • A class that is declared using “abstract” keyword is known as abstract class. It can have draw different shapes like Circle, Triangle, and Rectangle.
class. class, this is called method overriding. In this case when we call the method from child abstract methods (methods without body) as well as non abstract methods AKA concrete • We can perform polymorphism by ‘Method Overloading’ and ‘Method Overriding’
package JavaSessions; class object, the child class version of the method is called. However we can call the methods (regular methods with body) • There are two types of Polymorphism in Java
public class Artist { •
private String name;
parent class method using super keyword. • Abstract Method: An abstract method is a method that is declared without an implemen- Compile time polymorphism (Static binding) – Method overloading
• In this case the method in parent class is called overridden method and the method in tation (without braces, and followed by a semicolon). • Runtime polymorphism (Dynamic binding) – Method overriding
//getter method child class is called overriding method • In order to use an abstract method, you need to override that method in sub class.
public String getName() {return name; } • The main advantage of method overriding is that the class can give its own specific imple- • An abstract class has no use until unless it is extended by some other class. Non-Access Modifiers in Java
mentation to a inherited method without even modifying the parent class code.
• • A normal class (non-abstract class) cannot have abstract methods. Java provides a number of non-access modifiers to achieve many other functionalities.
//setter method Method Overriding is an example of runtime polymorphism
• A class which is not abstract is referred as Concrete class • The static modifier for creating class, methods and variables.
public void setNmae (String name) {this.name = name;}} • It is a good practice to write “@Override” annotation on the top of override method. • An abstract class can not be instantiated, which means you are not allowed to create • The final modifier for finalizing the implementations of classes, methods, and variables.
class ParentClass{
//Parent class constructor an object of it • The abstract modifier for creating abstract classes and methods.
package JavaSessions; •
public class Show { ParentClass(){System.out.println("Constructor of Parent"); } • Abstract classes may or may not include abstract methods The synchronized and volatile modifiers, which are used for threads.
public static void main(String[] args) { void disp(){ System.out.println("Parent Method");} } • Up casting is allowed
// creating instance of the encapsulated class • The class that extends the abstract class, has to implement all the abstract methods of it, Access Modifiers in Java
Artist s = new Artist(); class JavaExample extends ParentClass{ else you have to declare that class abstract as well. An access modifier restricts the access of a class, constructor, data member and method in
JavaExample(){System.out.println("Constructor of Child"); } • Since abstract class allows concrete methods as well, it does not provide 100% abstrac- another class
//setting value in the name member void disp(){System.out.println("Child Method"); //Calling the disp() method of tion. You can say that it provides partial abstraction. • default: The scope of default access modifier is limited to the package only. If we do not
s.setNmae("BTS"); parent class • If you declare an abstract method in a class then you must declare the class abstract as mention any access modifier, then it acts like a default access modifier.
super.disp(); } well. you can’t have abstract method in a concrete class. It’s vice versa is not always true: • private: The scope of private access modifier is only within the classes.
//getting value of the name member public static void main(String args[]){ If a class is not having any abstract method then also it can be marked as abstract. • Note: Class or Interface cannot be declared as private
System.out.println(s.getName()); }} //Creating the object of child class
JavaExample obj = new JavaExample();
• An abstract class must be extended and in a same way abstract method must be overrid- • protected: The scope of protected access modifier is within a package and also outside
den. If concrete methods use “final” keyword, they wont be overridden. the package through inheritance only.
obj.disp(); } }
• Advantages of Encapsulation: Output is: • Static methods can not be overridden • Note: Class cannot be declared as protected
• It improves maintainability and flexibility and re-usability: Constructor of Parent • Why abstract class? • public: The scope of public access modifier is everywhere. It has no restrictions. Data
• The fields can be made read-only (If we don’t define setter methods in the Constructor of Child • we force all the sub classes to implement this method( otherwise you will get members, methods and classes that declared public can be accessed from anywhere.
class) or write-only (If we don’t define the getter methods in the class). For Child Method compilation error) - set the rules
e.g. If we have a field (or variable) that we don’t want to be changed so we Parent Method
simply define the variable as private and instead of set and get both we just • Overloading vs Overriding in Java: abstract class Animal{ //abstract parent class
need to define the get method for that variable. Since the set method is not • Overloading happens at compile-time while Overriding happens at runtime
present there is no way an outside class can modify the value of that field. public abstract void sound(); //abstract method
• User would not be knowing what is going on behind the scene. They would • Performance: Overloading gives better performance compared to overriding. public void smell(); //concrete method with body }
The reason is that the binding of overridden methods is being done at
only be knowing that to update a field call set method and to read a field call runtime
get method but what these set and get methods are doing is purely hidden public class Dog extends Animal{ //Dog class extends Animal class
from them. • Overloading is being done in the same class while for overriding base and public void sound(){ System.out.println("Woof"); }
child classes are required. public void smell(); { System.out.println("Monkey"); }
Inheritance • Argument list should be different while doing method overloading. Argu-
ment list should be same in method Overriding. public static void main(String args[]){
• The process by which one class acquires the properties (data members) and functionali- • private and final methods can be overloaded but they cannot be overridden. Animal obj = new Dog();
ties (methods) of another class is called inheritance It means a class can have more than one private/final methods of same obj.sound();
• The aim of inheritance is to provide the reusability of code so that a class has to write name but a child class cannot override the private/final methods of their obj.smell();
only the unique features and rest of the common properties and functionalities can be base class. } }
extended from the another class. • Static binding is being used for overloaded methods and dynamic binding is
• Child class: The class that extends the features of another class is known as child class, being used for overridden/overriding methods. Difference between Abstract Class and Interface?
sub class or derived class.
• Parent Class: The class whose properties and functionalities are used (inherited) by
• ABSTRACT CLASS
another class is known as parent class, super class or Base class
Interface • To declare Abstract class we have to use abstract keyword
• Child can inherit from parent not vice versa.
• Interface looks like a class but it is not a class. An interface can have methods and varia- • In an Abstract class keyword abstract is mandatory to declare a method as
bles just like the class but the methods declared in interface are by default abstract (only an abstract
• Sibling to sibling inheritance is not allowed. method signature, no body). Also, the variables declared in an interface are public, static • An abstract class contains both abstract methods and concrete methods
• Types of Inheritance: & final by default (method with body)
• Single Inheritance: refers to a child and parent class relationship where a • Use of Interface in java? • An abstract class provides partial abstraction
class extends the another class • They are used for full abstraction. Since methods in interfaces do not have • An abstract class can have public and protected abstract methods
class A {//your parent class code}
class B extends A {//your child class code}
body, they have to be implemented by the class before you can access them.
The class that implements interface must implement all the methods of that
• An abstract class can have static, final or static final variables with any access
• Multilevel inheritance: refers to a child and parent class relationship where modifiers
interface. • An abstract class can extend one class or one abstract class
a class extends the child class. For example class C extends class B and class B • In java, multiple inheritance is not allowed, however you can use interface to • Abstract class doesn't support multiple inheritance
extends class A.
Java Exception Handling Cheat Sheet tion occurs or not. The statements present in this block will always execute regardless of static void checkEligibilty(int stuage, int stuweight){
• In Java, an exceptions is an event that disrupts the normal flow of the program. It is an whether exception occurs in try block or not such as closing a connection, stream etc. if(stuage<12 && stuweight<40) {
object which is thrown at runtime. Exception Handling is a mechanism to handle runtime • A finally block must be associated with a try block, you cannot use finally throw new ArithmeticException("Student is not eligible for registration");
errors. without a try block }
• When an exception occurs program execution gets terminated. • Finally block is optional, however if you place a finally block then it will else {
System.out.println("Student Entry is Valid!!");
• The good thing about exceptions is that they can be handled in Java. By handling the always run after the execution of try block.
exceptions we can provide a meaningful message to the user about the issue rather than • In normal case when there is no exception in try block then the finally block
}
}
a system generated message, which may not be understandable to a user. is executed after try block. However if an exception occurs then the catch
• System generated message is not user friendly so a user will not be able to understand block is executed before finally block
public static void main(String args[]){
what went wrong. In order to let them know the reason in simple language, we handle • The statements present in the finally block execute even if the try block System.out.println("Welcome to the Registration process!!");
exceptions contains control transfer statements like return, break or continue. checkEligibilty(10, 39);
• Advantage of Exception handling: • generally clean up codes are provided here. System.out.println("Have a nice day..");
• Exception handling ensures that the flow of the program doesn’t break when
public static int myMethod() {
}}
an exception occurs.
try {
• We can identify the problem by using catch declaration return 112; } Difference between throw and throws in java
finally { ) Throws clause is used to declare an exception, which means it works similar to the try-
Error vs Exception System.out.println("This is Finally block"); catch block. On the other hand throw keyword is used to throw an exception explicitly.
• Error System.out.println("Finally block ran even after return statement"); } ) If we see syntax wise than throw is followed by an instance of Exception class
• Impossible to recover from error and throws is followed by exception class names.
• Errors are of type unchecked exception Output of above program: ) Throw keyword is used in the method body to throw an exception, while throws is used
This is Finally block in method signature to declare the exceptions that can occur in the statements present in
• All errors are of type java.lang.error Finally block ran even after return statement the method.
• They are known to complier. 112 ) You can throw one exception at a time but you can handle multiple exceptions by declar-
• They happen at run time ing them using throws keyword.
• Errors are caused by the environment in which the application is running. • Flow of Control in try/catch/finally blocks
• Exception 1) If exception occurs in try block’s body then control immediately transferred
• Possible to recover from Exception (skipping rest of the statements in try block) to the catch block. Once catch Common Scenarios
• Exceptions can be checked type or unchecked type. block finished execution then finally block and after that rest of the program. • NullPointerException – When you try to use a reference that points to null.
• All exceptions are of type java.lang.exception 2) If there is no exception occurred in the code which is present in try block String b = null;
then first, the try block gets executed completely and then control gets
• Checked exceptions are known to complier where as unchecked exceptions transferred to finally block (skipping catch blocks). int i = Integer.parseInt(b);
are not known to compiler 3) If a return statement is encountered either in try or catch block. In this
• Exceptions are caused by the application. case finally block runs. Control first jumps to finally and then it returned • ArithmeticException – When bad data is provided by user.
back to return statement. int a = 10/0;
Types of Exception: • Nested try catch block: When a try catch block is present in another try block then it is
• ArrayIndexOutOfBoundsException – When you try to access the elements of an array out
• Checked exceptions: called the nested try catch block. If neither catch block nor parent catch block handles
of its bounds, for example array size is 5 (which means it has five elements) and you are
• All exceptions other than Runtime Exceptions are known as Checked excep- exception then the system generated message would be shown for the exception
trying to access the 10th element.
tions as the compiler checks them during compilation to see whether the //Main try block
try { int c[]= new int [5];
programmer has handled them or not c[10]= 50;
• Checked exception (compile time) force you to handle them, if you don’t statement 1;
statement 2;
handle them then the program will not compile.
//try-catch block inside another try block • NumberFormatException:
• Unchecked exceptions: try { String b = null;
• Runtime Exceptions are also known as Unchecked Exceptions. These excep- statement 3; int i = Integer.parseInt(b);
tions are not checked at compile-time so compiler does not check whether statement 4;
the programmer has handled them or not but it’s the responsibility of the //try-catch block inside nested try block • StringIndexOutOfBoundsException
programmer to handle these exceptions and provide a safe exit try { • RuntimeException
• unchecked exception (Runtime) doesn’t get checked during compilation statement 5; • NoSuchMethodException
statement 6; • NoSuchFieldException
Exception Hierarchy } • InterruptedException
 Object catch(Exception e2) {
//Exception Message
 Throwable } Garbage Collection

 Exceptions }
catch(Exception e1) { •
Garbage means unreferenced objects
It is a process to destroy the unused objects.
 RuntimeException //Exception Message • Advantages of garbage collection:
 ArithmeticException } • It makes java memory efficient because garbage collector removes the
 ClassCastException }
//Catch of Main(parent) try block •
unreferenced objects from heap memory.
It is automatically done by the garbage collector (a part of JVM) so we don't
 ArrayndexOutOfBoundsException catch(Exception e3) { need to make extra efforts.
 NullPointerException }
//Exception Message • How can an object be unreferenced?
 ….. • By nulling the reference
Employee e=new Employee();
 NoSuchMethodException throws clause e=null;
 SQLException • The “throws” keyword is used to declare exceptions. • By assigning a reference to another

 ClassNotFoundException
syntax
public void myMethod() throws ArithmeticException, NullPointerException
Employee e1=new Employee();
Employee e2=new Employee();
 IOException { e1=e2;
 Error }
// Statements that might throw an exception • By anonymous object etc.
 Virtual Machine Error • What is the need of having throws keyword when you can handle exception using try- •
new Employee();
The finalize() method is invoked each time before the object is garbage collected. This
 Assertion Error catch? method can be used to perform cleanup processing. This method is defined in Object
 ……. • The throws does the same thing that try-catch does but there are some class as
cases where you would prefer throws over try-catch. For example: protected void finalize(){}
Different ways to handle Exceptions:
Lets say we have a method myMethod() that has statements that can throw • The gc() method is used to invoke the garbage collector to perform cleanup processing.
either ArithmeticException or NullPointerException, in this case you can use The gc() is found in System and Runtime classes.
• Using try/catch: A risky code is surrounded by try block. If an exception occurs, then it is try-catch. But suppose you have several such methods that can cause excep- System.gc();
caught by the catch block which is followed by the try block. tions, in that case it would be tedious to write these try-catch for each meth-
• By declaring throws keyword: At the end of the method, we can declare the exception od. The code will become unnecessary long and will be less-readable. One
using throws keyword. way to overcome this problem is by using throws. declare the exceptions in
the method signature using throws and handle the exceptions where you are
calling this method by using try-catch.
Basic Exception • Another advantage of using this approach is that you will be forced to handle
try{ the exception when you call this method, all the exceptions that are declared
//code that may cause an exception using throws, must be handled where you are calling this method else you
} will get compilation error.
catch (exception(type) e(object))
{ public void myMethod() throws ArithmeticException, NullPointerException
//error handling code {
} // Statements that might throw an exception
//rest of the program }
finally { public static void main(String args[]) {
//statements to be executed try {
} myMethod();
• Try block: Risky code is surrounded by a try block. An exception occurring in the try block }
is caught by a catch block. Try can be followed either by catch (or) finally (or) both. But catch (ArithmeticException e) {
any one of the blocks is mandatory. // Exception handling statements
• Catch block: A catch block is where you handle the exceptions, this block must follow the }
try block. catch (NullPointerException e) {
• A single try block can have several catch blocks associated with it. // Exception handling statements
• You can catch different exceptions in different catch blocks. When an excep- }}
tion occurs in try block, the corresponding catch block that handles that
particular exception executes throw keyword
• you should place the catch blocks in such a way that the generic exception • The “throw’ keyword is used to throw an exception.
handler catch block is at the last • We can define our own set of conditions or rules and throw an exception explicitly using
• If no exception occurs in try block then the catch blocks are completely throw keyword. For example, we can throw ArithmeticException when we divide number
ignored. by 5, or any other numbers, what we need to do is just set the condition and throw any
• If you are wondering why we need other catch handlers when we have a exception using throw keyword.
generic that can handle all. This is because in generic exception handler you public void a(){
can display a message but you are not sure for which type of exception it throw new exception_class("error message"); }
may trigger so it will display the same message for all the exceptions and
user may not be able to understand which exception occurred. Thats the • Example:
reason you should place it at the end of all the specific exception catch In this program we are checking the Student age.if the student age<12 and weight <40 then our
blocks program should return that the student is not eligible for registration.
• Finally Block: contains all the crucial statements that must be executed whether excep- public class ThrowExample {
Java Programs al.add("Rock");
How to print “Hello” without main method? al.add("Becky");
Static block has the highest priority in java. So, any thing that is written in static block is execut-
ed first. HashSet<String> hs=new HashSet<String>();
static{ System.out.println("hello"); } for (int i=0; i<al.size(); i++) {
hs.add(al.get(i));}
How to find whether given number is odd number? System.out.println(hs);}
int a=22;
if (a%2!=0) { Find 2nd Largest Number in Array using Array
System.out.println(a+" is an odd number");
}else { import java.util.Arrays;
System.out.println(a+" is not an odd number"); } public class SecondLargestInArrayExample1{
Finding the max number (given three numbers) public static int getSecondLargest(int[] a, int total){
int x = 600; Arrays.sort(a);
int y = 700; return a[total-2];
int z = 300; }
if(x>y && x>z) {System.out.println("x is the highest number"); }
else if(y>z){ System.out.println("y is the highest number"); } public static void main(String args[]){
else{ System.out.println("z is the highest number"); } int a[]={1,2,5,6,3,2};
int b[]={44,66,99,77,33,22,55};
How to reverse a String System.out.println("Second Largest: "+getSecondLargest(a,6));
• Using for loop System.out.println("Second Largest: "+getSecondLargest(b,7));
String str = "I like Java but I hate Selenium"; }}
String reverse = "";
for (int i = str.length() - 1; i >= 0; i--) {
reverse = reverse + str.charAt(i); } Find 2nd Largest Number in Array using Collections
System.out.println(reverse); }
import java.util.*;
• Using StringBuffer class public class SecondLargestInArrayExample2{
String str = "I like Java but I hate Selenium";
StringBuffer sf = new StringBuffer(str); public static int getSecondLargest(Integer[] a, int total){
System.out.println(sf.reverse()); List<Integer> list=Arrays.asList(a);
Collections.sort(list);
How to reverse an Integer int element=list.get(total-2);
• Using algorithm return element;
int num = 12345; }
int rev = 0; public static void main(String args[]){
while (num != 0) { Integer a[]={1,2,5,6,3,2};
rev = rev * 10 + num % 10; Integer b[]={44,66,99,77,33,22,55};
num = num / 10;} System.out.println("Second Largest: "+getSecondLargest(a,6));
System.out.println(rev); System.out.println("Second Largest: "+getSecondLargest(b,7));
}}
• Using StringBuffer
int a = 123456;
String str = String.valueOf(a);
StringBuffer sb = new StringBuffer (str);
System.out.println(sb.reverse());
Remove junk/special chars in a String
• Regular Expression: [^a-zA-Z0-9]. Meaning, remove all except those in bracket.
String str ="#2. Baidu.com 百度";
String a = str.replaceAll("[^a-zA-Z0-9]", "");
System.out.println(a);
How to find min and max in an integer array
int[] numbers = { 2, 4, 6, 8, -10, 12 };
int largest = numbers[0];
int smallest = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > largest) {
largest = numbers[i];
} else if (numbers[i] < smallest) {
smallest = numbers[i];
} }
System.out.println("given array is " + Arrays.toString(numbers));
System.out.println("largest is :: " + largest);
System.out.println("smallest is :: " + smallest);
How to swap two integers
int x = 5;
int y = 10;
• Using third variable
int t;
t=x;
x = y;
y =t;
• Using (+ -) operators
x = x + y; //frist get the total and give to a variable
y = x-y; //now deduct from
x = x-y;
• Using (*/)operators
x = x * y;
y = x/y;
x = x/y;
How to swap two Strings
String x="Hello";
String y="TekSchool";
x = x+y;
y=x.substring(0, x.length()-y.length());
x= x.substring(y.length());
How to Find Duplicates Elements in Java Array?
String[] str = { "A", "B", "C", "D", "E", "B" };
• First method - good only for small arrays
for (int i = 0; i < str.length; i++) {
for (int j = i + 1; j < str.length; j++) {
if (str[i].equals(str[j])) {
System.out.println("Duplicate value is:: " + str[i]);}}}
• Using HashSet class. It does NOT store duplicate values.
HashSet<String> store = new HashSet<String>();
for(String names: str) {
if(store.add(names) == false) {
System.out.println("Duplicate Value is:: " + names);}}
How to remove all duplicates from an ArrayList?
List<String> al = new ArrayList<String>();
al.add("Ajay");
al.add("Becky");
al.add("Chaitanya");
al.add("Ajay");

You might also like