Java Full Notes
Java Full Notes
You will be writing Automation scripts in Java, to execute test cases automatically.
Methods, Variables
4. Set path, copy the path of JDK from your installed folder path of java
Java Architecture
We will write a program in an editor like editplus, Eclipse
So whenever we write java code, the editor will have 2 components internally :
1. Compiler
2. Interpreter
● Syntax
● Rules
Because The byte code can be executed at any device, any platform.
.class file is an intermediate file which is given as input to an interpreter which will
convert the .class file to a binary file.
JIT : Just in time - It is responsible to convert from .class file to binary format
JDK : Java development kit : It is a kit which consists of all the library files and
utilities to develop the java programs.
.
Tokens in Java :
In Tokens we have :
1. Identifiers
2. Keywords
3. Literals
4. Operators
5. Separators.
English - 26 alphabets.
abstract
Continue
Default
Do
Double
Else
Enum
Extends
Final
Finally
Float
For
Goto
Assert
Boolean
Break
Byte
Case
Catch
Char
Class
Const
If
Implements
Import
Instance of
Int
Interface
Long
Native
New
Package
Private
Protected
Public
Return
Short
Static
Strict fp
Super
Switch
Synchronise
This
Throw
Transient
Try
Void
Volatile
while
Literals
[Link] literal
Empty String - “”
If you give Double quotes and not write anything in between quotes, then it is called
an Empty String
Operators – they are the symbols which is used to perform an operation on the
operands.
1. Unary Operators :
Postfix
(expression) ++,
(expression) - -
Prefix
++(expression),
-- (expression)
2. Arithmetic operator –
a)Multiplicative - *,/,%
2*2 = 4
4*4 = 16
4/2= 2
10/2=5
9%3 = 0
10%3 = 1
90%7= 6
b) Additive -> +, -
<<4 = 16
10000
Right shift
4 >> = 5
100
00100
3. Relational operators :
To find the which variable greater than each other ,less than each other, equal to
each other, not equal to each other
3. Bitwise
1&1=1
1&0=0
0&1=0
0&0=0
1^1= 0
1^0= 1
0^1=1
0^0=0
Bitwise Inclusive OR - |
1|1=1
1|0=1
0|1=1
0|0=0
4. Logical Operator –
Example -
Requirement - I want to check for both the condition, and return true only if both of
them are satisfied.
Passed
} else
Failed
LOGICAL OR - ||
Example -
sysout(“Happy”);
6. Assignment operator - = , += , -= , *=, /=,%=, &=,^=, |=, <<=,>>=
A +=10;
A = A +10;
A= -10;
A = A-10;
A+b = C
Separators -
Braces - {} - Opening and closing Your class, Method, some loop statement.
Conditional Statement.
System - is a class,
Variables -
Variable is a named memory location which can store some value , and it can
change n number of times.
Byte - 0
Short - 0
Int - 0
Long - 0
Float - 0.0
Double - 0.0
Char - \u0000
Boolean - false
2. Non Primitive - Reference Variable type/ class type - Array, string or any
class type.
1. Global variable
2. Local variable.
Local Variable :
● The scope of the local variable is from the beginning of method till end of
the method.
● Any variable which is declared outside the method and inside the class is
called as Global variable.
● The scope of global variable is from the beginning of class till the end of
class.- it can be inside methods also.
● Once Global variable is declared immediately in the next line we dont have
to initialise or reinitialize.
Variable declaration :
Syntax -
Datatype variable_name;
Int number;
Float pi ;
Variable Initialization :
Syntax -
Variable_name = value;
Example -
Number = 10;
Pi = 3.142;
Variable Utilisation :
[Link](pi)
Variable Re initialization
Int y = 15;
y= 20;
[Link](y)
Int c = 30;
Int d;
d= c;
Byte - 0
Short - 0
Int - 0
Long - 0
Float - 0.0
Double - 0.0
Char - \u0000
Boolean - false
Note :
the default value of char in java is \u0000 which denotes null character and this is
why blank is printed as default value.
If you assign '\u0000' to any char variable then also you will find the same output as
shown above.
Assignment -
Account number , account name , Bank name , IFSC code, Branch name, Available
balance , Gender - M/F.
5) Write a program to print the remainder of numbers using the remainder method.
remainder=a%b
Modifier - Static
Modifier - Static
Whenever we want to give input for the method from Main method, then we go
for Method with parameter.
int result;
result = a+b;
[Link](result);
}
add(10,15);
1. Change the Return type of method from void to the datatype of the
returning variable. (Example from void to int in add program)
int result;
result = a+b;
return result;
//the return keyword internally returns the value to the main method
//[Link](result);
int addition;
addition =add(10,15);
// with the help of result variable , we are able to store the returned
[Link](addition);
Assignment -
1. WP for method with return type as well as method with parameter for
dividing 2 numbers , multiplying and area of circle.( 3 programs)
Static Keyword
Any member declared with the keyword static is called as static member of
the class.
Properties of static :
Syntax :
Static pool area - is a part of memory , where all the static members
are stored.
Non static :
Properties of static :
a.
Static - Class
For variables :
Object.variable_name;
New classname().variable_name();
For methods :
[Link]();
New classname().methodname();
new class_name();
● And the constructor will initialise the non static members into Heap
memory.
Note :
Multiple copes meaning for Non static - When we want to access non
static members multiple times, we have to create object multiple times.
Heap memory is a memory allocation for non static and objects., used to
store non static members.
Class loader - Whenever we execute a class, then the class loader loads the
class for execution.
Stack - is a data structure, in where the elements which are added first can
only be removed last . Stored in First in , Last out format.
Static pool area : is a memory allocation for Static members, used to store
static members of the class.
Conditional statements:
1. if(Condition)
2. if(Condition)
} else
if I study Java now, I will get placed. Else Not get job
If i eat the food, then food will get digested else I will stay hungry
If I party, next morning I will wake up late, else I will wake up early.
3. if(Condition)
} else
if ( condition )
Else
Syntax :
For static :
[Link];
[Link]();
if(Condition){
if(Condition){
} else {
} else {
For Loop :
Condition -
Syntax :
}
While loop :
Meaning of while -
while (condition) {
Do While loop :
do {
// Code to be executed
while (condition);
Note :
● do-while loop guarantees that the block of code inside the loop will be
executed at least once, and then it checks the condition. The loop will
● String Literal
Programs :
package Day2;
public class Dowhiledemo {
public static void main(String[] args) {
int num=11;
//do while loop makes sure that the do clock gets executed atleast once , irrespective
// whether the condition is true or false.
do {
[Link](num);
num++;
}while(num<=10);
}
}
2.
package Day2;
public class even {
public static void main(String[] args) {
// even numbers from 1 to 10
for(int i=1;i<=10;i++) {
if(i%2==0) {
[Link](i);
}
}
//1%2 =1
// 2%2=0
//3%2=1
//4%2=0
}
}
3.
package Day2;
public class fordemo {
public static void main(String[] args) {
// requirement is i have to print 1 to 10
// I have to skip 26 value
int n =50;
for(int i=1;i<=n;i++) {
if(i==26) {
if(i>=46) {
[Link](i);
}
}
4. package Day2;
public class ifelse {
public static void main(String[] args) {
int number=5;
if(number==50) {
}else
if(number>50)
else
}
}
5. package Day2;
public class Method3 {
[Link](res);
}
public static String concat(String name1,String name2) {
return result;
}
}
6.
package Day2;
public class nestedif {
public static void main(String[] args) {
int marks=34;
if(marks>35) {
if(marks>80) { // nested if
[Link]("Distinction");
}
else // nested if ends here
[Link]("Exam passed");
[Link]("failed");
}
int res;
res = mod();
[Link](res);
}
public static int mod() {
int a =10;
int b =3;
// Method with return type - It should return a variable to the main method
return result;
}
8.
package Day2;
public class subtract {
int a;
public static void main(String[] args) {
char c = 'a';
[Link](result);
9.
package Day2;
public class whiledemo {
public static void main(String[] args) {
// Requirement - 1 to 100
int i=1;
while(i<=100) {
if(i==100) {
break;
}
[Link](i);
i++;
}
}
10.
package stringdemo;
public class StringMethods {
public static void main(String[] args) {
String s1 = "masai";
String s4 ="MASAI";
[Link](s1);
[Link](s2);
// CharAt Method
[Link]([Link](0));
[Link]([Link](2));
//Concat method
[Link]([Link](s2));
// Contains
[Link]([Link]("Z"));
[Link]([Link]("E"));
// To Uppercase
[Link]([Link]());
[Link]([Link]());
//Starts with
[Link]([Link]("M"));
// Equals
[Link]([Link](s1));
[Link]([Link](s1));
[Link]([Link]()>[Link]());
[Link]([Link]('a', 'b'));
[Link](s1); // Strings are Immutable - Mutation means change
for(int i=0;i<[Link];i++) {
[Link]("Individual element"+spl[i]);
for(int j=0;j<[Link];j++) {
[Link](spl2[j]);
}
}
JVM memory
Heap memory is a memory allocation for non static and objects., used to
store non static members.
Class loader - Whenever we execute a class, then the class loader loads the
class for execution.
Stack - is a data structure, in where the elements which are added first can
only be removed last . Stored in First in , Last out format.
Method area - It is used to store method body and definition.
Static pool area : is a memory allocation for Static members, used to store
static members of the class.
Method with parameter, method with return type and also it should follow with
2 different class with object creation.
Method with parameter, method with return type and also it should follow with
2 different [Link] object creation.
Object - Object is a real time entity which has state and behaviour.
State defines what data it can hold , and behaviour defines the way object
behaves.
Assignment -
Write 5 programs that should contain 2 classes, one with main method, other
with all the methods both static and non static.
Create an object to access all non static members - local methods, global
nk - reference variable
object was created with new Nokia(), and we are storing the object inside a reference
variable which is of the type Nokia class.
Class cherry{
sys(“note1”);
sys(“note2”);
sys(“note3”);
}
Class Home{
main(){
rederence_var.notes();
Arrays :
Interview Question :
Properties / Disadvantages of Array :
1. Array Declaration .
Syntax :
Datatype[] array_name;
Int[] rollno;
String[] names;
2. Array Initialization :
Syntax :
Example -
Syntax :
Array_name[index ] = value;
Rollno[0] = 1;
4. Array Utilisation
[Link](rollno[0]);
[Link](rollno[1]);
Syntax : [Link] ;
[Link]([Link]);
[Link](rollno[i])
Rollno[4] = 20;
Syntax :
Example -
WAP to declare, initialise and utilise arrays - string , int , char datatypes
- IPL team
Programs :
package objectdemo2;
public class Car {
public static void main(String[] args) {
[Link]();
[Link]();
[Link]();
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}
}
Class 2 :
package objectdemo2;
public class Tesla {
[Link]("Autopilot fetaure");
[Link]("Safetyfeatures");
2. Scanner Demo -
package stringdemo;
import [Link];
public class ScannerDemo {
public static void main(String[] args) {
// Step 1 - Create object of Scanner class
[Link](name);
[Link](weight);
[Link](citizenof_earth);
[Link](height);
}
}
3. Switch Case
package stringdemo;
import [Link];
public class SwitchcaseDemo {
public static void main(String[] args) {
// I want to write the logic for Multiple choices
// I will design a calculator
int a = [Link]();
int b = [Link]();
switch (operation) {
case "add":
[Link](a+b);
break; // we need to break from the switch when we execute a operation.
case "subtract":
[Link](a-b);
break;
case "Multiply":
[Link](a*b);
break;
case "Divide":
[Link](a/b);
break;
default:
[Link]("Invalid value : add only +, - , * , / for operations");
break;
}
}
4. package ObjectsDemo;
public class array1 {
public static void main(String[] args) {
//Integer array
array1[0]=123;
array1[1]=234;
array1[2]=435;
array1[3]=88;
array1[4]=123;
array1[5]=909;
[Link](array1[5]);
for(int i=0;i<=[Link]-1;i++) {
[Link](array1[i]);
}
}
}
5. package ObjectsDemo;
public class chararray {
public static void main(String[] args) {
char c[] = new char[5];
/*
* c[0]='r'; c[1]='a'; c[2]='h'; c[3]='u'; c[4]='l';
*/
[Link](c[2]);
for(int j=0;j<[Link];j++) {
[Link](c[j]);
}
}
}
6.
package ObjectsDemo;
public class Masai {
7.
package ObjectsDemo;
public class MoolyaEd {
public static void selenium() {
// using reference variable and . operator we can access methods from Masai
[Link]();
[Link]();
[Link]([Link]);
[Link](ms.min_marks);
[Link]();
[Link]();
// Through objects
//[Link]();
//[Link]();
[Link]();
}
}
8.
package ObjectsDemo;
public class StringArrayDemo {
public static void main(String[] args) {
String str[] = {"razi","omkar","rahul","prashanti","rushi","jyotsna"};
[Link](str[2]);
[Link](str[i]);
}
}
}
9.
package ObjectsDemo;
import [Link];
public class switchdemo {
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
[Link]("Enter the operation");
int a =10;
int b =9;
switch (operation) {
case "+":
[Link](a+b);
break;
case "-":
[Link](a-b);
break;
default:
break;
}
}
}
Access Specifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors,
methods, and class by applying the access modifier on it.
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
Constructors :
Class cherry{
New Cherry();
Here , Cherry(); is a constructor.
this keyword
We use this keyword while initialising global variables in Constructor , when the
name of the global variable is the same as the variables declared in
Constructor.
This keyword is used when global variable name is same as local variable
name.
Inheritance :
Inheriting the properties from one class to another class is called Inheritance.
3. Hierarchical Inheritance.
4. Multiple Inheritance.
5. Hybrid Inheritance.
Super class : The class from which the subclass in inheriting the properties
from is called as Super class
Subclass : The class where the properties are being inherited is called a
Subclass - Child Class.
Programs :
1) Constructor program
package Day4;
public class Amazon {
// Why constructor? - TO initialise some data members.
String username;
long mobile;
String emailid;
//Step 2 - Define constructor and Initialise Data members with Method with Paramater.
username=uname;
mobile=mob;
emailid=email;
public Amazon() {
}
// Step 3 - Create an object - and pass the values from the constructor in the paramater.
public static void main(String[] args) {
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
// Values of Default constructor will print the default values of thier respictice data
types
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}
}
2. Constructor Program 2
package Day4;
public class Infosys {
// This program demonstrates the usage of this keyword (When global and local variable are
having
//same name)
String CEO_name;
int emp_count;
[Link](inf.CEO_name);
[Link](inf.emp_count);
}
}
package Overload_Day4;
public class Multiplication {
public static void main(String[] args) {
[Link]();
void multiply(){
int a=10;
int b=99;
[Link](a*b);
}
return a*b;
return c*d;
return e*f;
return g*h;
}
package inheritance;
//this is my parent class
public class Meta {
String CEO="Mark zuckerberg";
long emp_count=10000;
}
public void video_team() {
Child class
package inheritance;
//this is my child class
public class Instagram extends Meta{
// empty class
}
Main method class :
package inheritance;
public class Test {
// Implementation of Single level Inheritance
public static void main(String[] args) {
[Link]();
ig.video_team();
[Link]([Link]);
[Link](ig.emp_count);
[Link]([Link]);
}
}
Inheritance :
Inheriting the properties from one class to another class is called Inheritance.
3. Hierarchical Inheritance.
4. Multiple Inheritance.
5. Hybrid Inheritance.
Super class : The class from which the subclass in inheriting the properties
from is called as Super class
Subclass : The class where the properties are being inherited is called a
Subclass - Child Class.
2. Multi Level Inheritance :
3. Hierarchical Inheritance
Multiple subclasses inheriting the property from only one super class is called
Hierarchical Inheritance.
4. Multiple Inheritance
A subclass inheriting the property from multiple super class is called Multiple
Inheritance.
● Since both parent classes extends Object class which is the supermost
class,
● This will create ambiguity/ confusion to the child class as to which class it
needs to inherit from
5. Hybrid Inheritance.
It is a combination of two types of Inheritances.
Multi level Inheritance - Create an object of Son and access both father and
grandfather methods.
Hierarchical Inheritance : Create object for uncle and father and access Gfather
methods
Prepare for Complete Inheritance and types of Inheritance and present in class.
Pass by reference.
● And when we don't have to create object multiple times, then we can just
pass the reference and access the data members(Variables and methods)
Method Overloading :
Developing multiple methods with the same name but variation in the
arguments list is called as Method overloading.
Method Overriding :
Developing a method in the subclass/ child class with the same name and
signature as in the super class/ parent class but with different
implementation in the subclass.
2 classes,
// basics java
Rules :
1. The method name and signature should be the same as in the super
class.
Interview :
2. Runtime Polymorphism :
● The Method Declaration getting binded to its definition at the
Run time by the JVM based on the objects created is called
as Run time Polymorphism.
· WHile executing, It will have a look at both the classes - because of Inheritance
· Jvm will implement child class implementation and choose not to implement
parent class method.
Assignment :
Programs :
int founded_date=1976;
String founder= "Steve jobs";
[Link]("Apple 1 architecture");
}
}
package multilevel_inheritance;
//Intermediate class (Parent class)
public class macintosh extends Apple{
[Link]("Portable computers");
}
package multilevel_inheritance;
// Sub class of macintosh
public class VisionPro extends macintosh{
public static void virtualreality() {
[Link]("Launched in 2023");
}
}
package multilevel_inheritance;
public class Test {
// Implementing Multi level Inheritance in this package
public static void main(String[] args) {
//[Link]();
[Link]();
package multilevel_inheritance;
public class Test {
// Implementing Multi level Inheritance in this package
public static void main(String[] args) {
VisionPro vp = new VisionPro();
//[Link]();
[Link]();
}
package overriding;
public class Windows11 extends Windows{
//The decision of JVM to execute the overridden implementation is happening at the
run
// time , that is why it is called as Run time Polymorphism.
[Link]();
[Link]();
Abstraction :
Hiding the complexity of the system and exposing only the required
functionality to the end user is called as Abstraction.
Concrete Method : Any method which has both declaration and body is
called as Concrete method.
Example :
Int var1;
[Link](“asdsadasdsavcx”);
Concrete class :
Example :
Class A{
Int rollno;
String name;
Void display(){
[Link](“asdsadasdsavcx”);
Abstract method :
Any method which is declared with the keyword abstract and which doesn’t
have a method body is called as Abstract method.
Example :
Any class which is declared with the keyword abstract is called as Abstract
class.
Abstract classes might have both abstract methods and concrete methods.
Hiding the data members using Private access specifiers, and giving indirect
access to the user from only getters and setters is called Encapsulation.
Step 1 :We can create a fully encapsulated class in Java by making all the data
members of the class private.
Step 2 : Now we can use setter and getter methods to set and get the data in it.
By providing only a setter or getter method, you can make the class read-only or
write-only
It is a way to achieve data hiding in Java because other class will not be able to
access the data through the private data members.
Company – Infosys
//It has a private data member and getter and setter methods.
package [Link];
return name;
[Link]=name
[Link]("vijay");
[Link]([Link]());
Wrapper class :
The wrapper class in Java provides the mechanism to convert primitive into object
and object into primitive.
Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects
and objects into primitives automatically. The automatic conversion of primitive into
an object is known as autoboxing and vice-versa unboxing.
AutoBoxing
UnBoxing.
For every Primitive data type , we have a subsequent wrapper class as shown
above.
Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper
class is known as auto boxing
For example, byte to Byte, char to Character, int to Integer, long to Long, float to
Float, boolean to Boolean, double to Double, and short to Short.
int i =30;
Integer jobj=i;
char c='k';
Character jkobj=c;
Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is
known as unboxing.
It is the reverse process of autoboxing. Since Java 5, we do not need to use the
intValue() method of wrapper classes to convert the wrapper type into primitives.
//Unboxing example - converting from object type to primitive type
int num = a;
1. toString() Method
We can use the toString() method to convert the Wrapper object or primitive to
String. There are a few forms of the toString() method:
A. public String toString(): Every wrapper class contains the following
toString() method to convert Wrapper Object to String type.
Example :
class Demo {
String s = [Link]();
[Link](s);
String s1 = [Link]('a');
[Link](s1);
[Link](s1);
}
Programs :
1. Wrapper programs
package wrapperdemo;
public class CharacterDemo {
public static void main(String[] args) {
char c = 'a';
char c1='0';
String s1 = [Link](c1);
[Link](status);
[Link](digitstatus);
}
}
2. Wrapper Demo 2
package wrapperdemo;
public class Demo1 {
public static void main(String[] args) {
int i=50; // primitive data type variable
[Link]("primitive value"+i);
// Autoboxing - is used to convert primitive to Wrapper Class type
Integer wrapper_variable = i;
char c = 'a';
[Link](c);
Character obj2 = c;
[Link](c);
@SuppressWarnings("removal")
Integer i1 = new Integer(100);
[Link]("Primitive"+num);
}
}
3. Wrapper Demo 3
package wrapperdemo;
public class Wrappermethods {
String s1 = "moolyaEd100";
float f1 = 4.5f;
[Link](num);
//[Link](num1);
[Link](strvar);
}
}
Encapsulation Program
1.
package encapsulation;
public class BankOfAustralia {
}
2. package encapsulation;
public class Customer {
public static void main(String[] args) {
BankOfAustralia ba = new BankOfAustralia();
[Link]("9021-21432-324234");
[Link]("123435");
[Link]([Link]());
[Link]([Link]());
}
}
return password;
// setter method
[Link] = password;
[Link]("09sadlan*(*(*");
[Link]("randompassword");
[Link](password);
}
}
Abstraction program :
[Link] abstraction;
public abstract class Airtel {
//cooncrete method
//If you want to override a method , then we should not use static
public static void call() {
// Abstract methods
}
2.
package abstraction;
public class AirtelMain extends Airtel{
[Link]();
am.internet4g();
[Link]();
}
@Override
public void internet4g() {
[Link]("4g service from Airtel Main");
}
@Override
public void roaming() {
[Link]("Roaming service from Airtel Main");
}
@Override
public void sms() {
[Link]("Sms service from Airtel Main");
}
}
Interface
Interface name_of_Interface
The Exception Handling in Java is one of the powerful mechanisms to handle the
runtime issues so that the normal flow of the application can be maintained.
1. IOException.
2. SQLException.
3. ClassNotFound Exception
5. Arithmetic Exception.
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception
1. Checked Exception
2. Unchecked Exception
Difference between Checked and Unchecked
Exceptions
1) Checked Exception
The exceptions which occur at Compile time are called Checked Exceptions. Also
called as Compile time Exception
The classes that directly inherit the Throwable class except RuntimeException and
Error are known as checked exceptions. For example, IOException, SQLException,
etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The exception that will occur at Run time is called an Unchecked Exception.
The classes that inherit the RuntimeException are known as unchecked exceptions.
example,ArithmeticException,NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
3) Error
Java provides five keywords that are used to handle the exception. The following table describes
each.
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception
code. It means we can't use try block alone. The try block must be followed by
either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block
later.
finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.
throws The "throws" keyword is used to declare exceptions. It specifies that there may
occur an exception in the method. It doesn't throw an exception. It is always used
with method signature.
Difference Between throw and Throws.
Throw Throws
Interview Question –
if(age<18) {
else {
1. int a=50/0;//ArithmeticException
String s=null;
2. [Link]([Link]());//NullPointerException
String s="abc";
3. int i=[Link](s);//NumberFormatException
Assignment - 1) Write 2 programs to demonstrate Encapsulation - Password , Bank
details.
Throws Keyword
For example -
Interview Question - What else in Java we can use instead of if else condition
without using if and else?
Try catch block will only work as If else condition if an exception occurs at try
Block.
Answer – throw.
Programs :
package interfaceprograms;
public interface Government {
void corporatepolicies();
void taxpolicies();
void pensionpolicies();
void corporatepolicies(String s1, String s2);
package interfaceprograms;
public class CityGovernment implements Government{
String citymayor;
int seats;
citymayor=mayor;
CityGovernment(int seats){
[Link]=seats;
}
@Override
public void corporatepolicies(String s1,String s2) {
// TODO Auto-generated method stub
[Link](s1);
[Link](s2+"Policies");
}
@Override
public void taxpolicies() {
// TODO Auto-generated method stub
[Link]("implementation of tax in city");
}
@Override
public void pensionpolicies() {
// TODO Auto-generated method stub
[Link]("implementation of pension in city");
}
@Override
public void corporatepolicies() {
// TODO Auto-generated method stub
[Link]("implementation of corporate in city");
}
package interfaceprograms;
public class Test {
public static void main(String[] args) {
CityGovernment cg = new CityGovernment("Ravindra Bhosle");
[Link]([Link]);
//[Link];
[Link]();
[Link]();
[Link]();
}
}
package exceptionhandling;
public class ArithematicExceptionDemo {
public static void main(String[] args) {
try {
[Link](9/0);
catch(ArithmeticException a){
[Link]();
int a =100;
String name="omkar";
}
}
package exceptionhandling;
public class NullPointerDemo {
public static void main(String[] args) {
try {
String a = null;
[Link]([Link]());
catch(Throwable t) {
[Link]();
[Link]("Exception handled");
}
}
package exceptionhandling;
public class NumberFormatDemo {
public static void main(String[] args) {
try {
String s= "Satyam123";
int a=[Link](s);
[Link](a);
// try catch block will not solve your exception , it will only handle the exception
// handling the abrupt stopping of execution.
catch(NumberFormatException n) {
[Link]("exception handled");
[Link]();
finally {
[Link](a+b);
}
}
}
package exceptionhandling;
public class Throwkeyworddemo {
public static void main(String[] args) {
int age =16;
try {
if(age<18) {
}
else
[Link]("Eligible");
catch(MasaiException e) {
[Link]();
[Link]("Exception handled");
}
finally {
[Link]("after age checking execute this statement");
}
[Link]("after finally");
}
}
package exceptionhandling;
// This is a Custom Exception class
//We are handling exception using this exception class which extends the Exception class
public class MasaiException extends Throwable {
String message;
MasaiException(String message){
[Link]=message;
Disadvantages of Array :
Collections :
Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.
Iterable Interface
The Iterable interface is the root interface for all the collection classes. The
Collection interface extends the Iterable interface and therefore all the subclasses of
Collection interface also implement the Iterable interface.
Collection Interface
The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have
. In other words, we can say that the Collection interface builds the foundation on which the
collection framework depends.
Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll
( Collection c), void clear(), etc. which are implemented by all the subclasses of Collection
interface
List Interface
List interface is the child interface of Collection interface. It inhibits a list type data structure
in which we can store the ordered collection of objects. It can have duplicate values.
List -
3 4 3 5 3 10 3
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
ArrayList
The ArrayList class implements the List interface.
It uses a dynamic array to store the duplicate element of different data types.
Queue Interface
.
9 8 7 6 5 4 3
Properties :
[Link] we want the objects/ elements to have a First in First out processing.
PriorityQueue
The PriorityQueue class implements the Queue interface. It holds the elements or
objects which are to be processed by their priorities. PriorityQueue doesn't allow
null values to be stored in the queue.
If we try to add elements which are not comparable with each other, then it will
throw ClassCastException.
· boolean add(E element): This method inserts the specified element into
this priority queue.
· public peek(): This method retrieves, but does not remove, the head of
this queue, or returns null if this queue is empty.
· public poll(): This method retrieves and removes the head of this queue,
or returns null if this queue is empty.
[Link]("Amit Sharma");
Iterator itr=[Link]();
while([Link]()){
[Link]([Link]());
[Link]();
[Link]();
Set Interface
It is unordered collection.
Set is the only interface out of 3 , where we cannot store duplicate values.
It represents the unordered set of elements which doesn't allow us to store the duplicate
items. We can store at most one null value in Set. Set is implemented by HashSet,
LinkedHashSet, and TreeSet.
HashSet
It is unordered collection.
[Link]("Ravi"); [Link]("Vijay");
Map Interface -
When we need to store the data in the form of Key, Value Pair.
123 Omkar
1234 Rahul
432 Saran
○ Java HashMap may have one null key and multiple null values.
You cannot store duplicate keys in HashMap. However, if you try to store duplicate
key with another value, it will replace the value.
HashMap<Integer,String> map=newHashMap<Integer,String>();
[Link](2,"Apple");
[Link](1);
Programs :
package collectionsdemo;
import [Link];
import [Link];
public class ArrayListTest {
public static void main(String[] args) {
// ArrayList Declaration
[Link](1);
[Link]('k');
[Link]("january batch");
[Link](false);
[Link](1.67f);
[Link](90.09302903);
[Link](83242342);
[Link](2);
[Link](ar);
[Link](ar2);
[Link]([Link]());
[Link](ar2);
[Link](4);
[Link]("omkar");
[Link](ar);
[Link]("omkar");
[Link](4);
[Link]();
[Link](null);
[Link](null);
[Link](ar2);
}
}
package collectionsdemo;
import [Link];
import [Link];
[Link]("jyotsna");
[Link]("rahul");
[Link]("saran");
[Link]("saran");
[Link](null);
[Link](null);
[Link]('M');
[Link](true);
[Link](false);
[Link](hs);
[Link](true);
[Link](hs);
[Link]('v');
[Link]('a');
[Link]('l');
[Link]('1');
[Link](null);
[Link](hc);
[Link](1);
[Link](1);
[Link](90);
[Link](45);
[Link](0);
[Link](h);
[Link](h);
[Link](ar);
package collectionsdemo;
import [Link];
public class PQueueDemo {
// Priority Queue will allow duplicates, but will not allow null values
public static void main(String[] args) {
PriorityQueue pq = new PriorityQueue();
[Link](100);
[Link](101);
[Link](200);
[Link](201);
[Link](900);
[Link](pq);
[Link](700);
[Link](800);
[Link](pq);
[Link]();
[Link]("after peek"+pq);
[Link](820);
//[Link](7.5);
//[Link]("india");
[Link](pq);
[Link](10000);
[Link](420);
[Link](820);
[Link](pq);
//[Link](pq1);
// IT compares both the quees and retains only the common element and it removes other
elements
[Link](420);
[Link](820);
//[Link](null);
}
}
package collectionsdemo;
import [Link];
import [Link];
import [Link];
[Link](1);
[Link](1);
[Link](2);
[Link](2);
[Link](2);
[Link](3);
[Link](3);
[Link](null);
[Link](13);
[Link](4);
[Link](4);
[Link](4);
[Link](5);
[Link](null);
[Link](ar);
if([Link](i)!=[Link](i+1)) {
[Link]([Link](i));
[Link](ar);
[Link](hs);
package Day7;
import [Link];
import [Link];
public class ToSortCollection {
public static void main(String[] args) {
ArrayList<Integer> a = new ArrayList<Integer>();
[Link](45);
[Link](23);
[Link](53);
[Link](13);
[Link](99);
[Link](69);
[Link](a);
[Link](a);
[Link](a);
}
}