SlideShare a Scribd company logo
1 of 44
JAVA1
Session 1
Run a sample Java program on notepad
public class LetsLearn {
/* I am trying to change
* I will try to print sum of two numbers
*/
public static void main(String []args) {
int sum=0,a=10,b=20;
sum = a + b;
System.out.println("The sum is " + sum); // Will print sum of a and b
}
}
Run a sample Java program on notepad
public class LetsLearn {
/* I am trying to change
* I will try to print sum of two numbers
*/
public static void main(String []args) {
int sum=0,a=Integer.parseInt(args[0]),b=Integer.parseInt(args[1]);
sum = a + b;
System.out.println("The sum is " + sum); // Will print sum of a and b
}
}
Important Features of Java
• Simple
• Platform Independent
• Architectural Neutral: A Language or Technology is said to be Architectural neutral which can run on
any available processors in the real world without considering their development and compilation.
• Portable: If any language supports platform independent and architectural neutral feature known as
portable.
• Multi Threading: A flow of control is known as a thread. When any Language executes multiple thread
at a time that language is known as multithreaded e. It is multithreaded.
• Distributed: Using this language we can create distributed applications. In distributed application
multiple client system depends on multiple server systems so that even problem occurred in one server
will never be reflected on any client system.
• Networked: It is mainly designed for web based applications, J2EE is used for developing network
based applications.
• Robust: Simply means of Robust are strong. It is robust or strong Programming Language because of
its capability to handle Run-time Error, automatic garbage collection
• Dynamic: It supports Dynamic memory allocation due to this memory wastage is reduce and improve
performance of the application.
• Secured: It is a more secure language compared to other language; In this language, all code is
covered in byte code after compilation which is not readable by human.
• Object Oriented: It supports OOP's concepts because of this it is most secure language
JAVA Architecture
Class Loader
Runtime Area
Method
Area
Heap Stack
PC
Register
Native
Method
Stack
Execution
Engine
Native Method
Interface
Native Library
Variables and Data Types
Reserve area in memory (int data=50;)
Local variable : Declared inside method.
Instance variable : Inside class but outside method. It is not declared as static.
Static variable : Declared as static. It cannot be local.
public class Test {
int k = 90; // instance variable
static int l = 20; //static variable
int j = 20; //instance variable
public void testLogin(int a){
int p = 90; // local variable
}
public void testClick(int b){
int f= 90; // local variable
}
}
Primitive Non Primitive
Numeric
Integer Floating
point
Double FloatByte Short
Longint
Non Numeric
Character Boolean
Data Types
Strings
Arrays
User defined
Data Type Default Value Default size
boolean false 1 bit
char 'u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
Primitive data types
Non-primitive data types: Class Type
• String s1;
• Student obj;
• Employee emp;
Increment/Decrement operator:
Increment Operator: Increments the value by 1
Decrement operator: Decrements the value by 1
package com.twoPir.FirstSession;
public class IncrementAndDecrementOperator {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i=10;
int k = ++i;
System.out.println(k);
int j =11;
int l=--j;
System.out.println(l);
}
}
Increment/Decrement operator:
What should be the output of below program?
package com.twoPir.FirstSession;
public class ArithmeticIncrementOp {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i =10;
int j = i++ + ++i;
System.out.println(j);
}
}
Lets run it in eclipse and see the Output. Then understand the output in next slides
Increment/Decrement operator:
Let’s see the output
package com.twoPir.FirstSession;
public class ArithmeticIncrementOp {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i =10;
int j = i++ + ++i;
System.out.println(j);
}
}
Value of “i” used in the expression
is 10, but “i” is updated in memory
to 11
Value of “i” is updated to 12. As it
was already 11 in memory
If block:
Java if statement is used to check condition. It checks Boolean condition: true or false.
Syntax:
If(Condition){
//code to be executed
}
condition
Code inside if
Code outside if
False
True
If Else block:
Java if else block is used to check condition. It executes if statement if condition is true otherwise
it executes code in else block
Syntax:
If(Condition){
//code to be executed
}else
//code to be executed
condition
Code inside if
Code after else
False
True
Code inside else
Nested If block:
A nested if is an if statement that is the target of another if or else. Nested if statements mean an
if statement inside an if statement. Yes Java allows us to nest if statements within if statements
Syntax:
If(Condition 1)
{
Executes when condition 1 is true
if(Condition 2)
{
Executes when condition 2 is true
}
}
Switch Statement:
The Java switch statement executes one statement from multiple conditions
Syntax:
switch(Expression)
{
Case 1:
//code to be executed
break; //optional
Case 2:
//code to be executed
break; //optional
Default:
//code to be executed if none of the case matches
}
For Loop:
For loop in java is used to iterate chunk of codes several times. If the number of times is fixed
then its recommended to use For loop.
3 types of For loop:
• Simple For Loop
• For-each or Enhanced for loop
• Labeled for loop
Simple For Loop
Syntax:
for(initialization; condition; incr/decr){
//Code to be executed
}
Initialization: We initialize the variable, it marks the start of for loop. An already declared variable can be used or can be declared in for
loop tself
Condition: Every iteration will be performed if the condition is true otherwise fol loop terminates
Incr/decr: Updates the variable for next iteration
For Loop:
For Each loop will iterate over each data in given array or set of data.
Syntax:
for(dataType var : array){
//Code to be executed
}
package com.twoPir.FirstSession;
public class ForEachLoopExample1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[]= {1,2,3,4};
for(int i:arr) {
System.out.println(i);
}
}
}
For Loop:
Labeled For loop : Can have name of each for loop. We use label before the for loop
Syntax:
labelName:
for(initialization; condition; incr/decr){
//Code to be executed
}
package com.twoPir.FirstSession;
public class LabeledForLoopExample1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
aa:for (int i = 0; i < 3; i++) {
bb:for (int j = 1; j <=3; j++) {
if(i==2&&j==2) {
break aa;
}
System.out.println(i+" "+j);
}
}
}
}
While Loop:
The Java while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed, it is recommended to use while loop.
Simple For Loop
Syntax:
while(condition){
//Code to be executed
}
Session 2
OOPS Concept
Class: In lay man term it means the group of object.
Suppose I call a cow by its class, i.e. Animal. My statement will be “Animal is grazing”. No one will
understand that to which animal am referring to. So statement should be Cow is grazing. Here Animal is
class, Cow, Elephant etc are objects.
Object: Which had properties and behavior
e.g. Ram has properties like (color, height, weight) and behavior like he can (Walk ,eat run etc.)
Method: Definition of behavior of object is call as Method
e.g. (Walk ,eat run etc.)
public class Car{
String color = “Magenta";
public void drive() {
String Speed = "10 KM";
}
public static void main(String[] args) {
Car obj = new Car();
obj.drive();
}
}
Static and Non Static
• Static Members of class are accessed by class Name, Since static members are class
• Non Static members of class are accessed by object. Non Static members are object members
int i =0
int i =0
int i =0
obj1
obj2
obj3
Int j
Name Convention
class name should start with uppercase letter
interface name should start with uppercase letter
method name should start with lowercase letter
variable name should start with lowercase letter
package name should be in lowercase
constants name should be in uppercase letter
Naming convention
Constructor in Java
• A constructor in Java is a block of code similar to a method that’s called when an
instance of an object is created. Here are the key differences between a constructor
and a method:
1. A constructor doesn’t have a return type.
2. The name of the constructor must be the same as the name of the class.
3. Unlike methods, constructors are not considered members of a class.
4. A constructor is called automatically when a new instance of an object is
created.
Types of constructors:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
public class Cow {
public Cow() {
}
public Cow(int weight) {
}
}
Q: Is it possible to Create object of default constructor when we have only parameterized
constructor in class
Answer: - NO (when we explicitly create parameterized constructors in class then java compiler
will not keep by default constructor in class)
Use Constructor in Java
• The purpose of constructor is to initialize the object of class
• Default constructor is used to provide the default values to the object like 0, null etc.
depending on datatype
• Parameterized is used to provide different values to different variable.
Q. Is constructor overloading is possible?
Ans: Yes
This is a java keyword. It works as a reference to
current object.
This in Java:
1. this can be used to refer current class instance
variable.
2. this can be used to invoke current class method
(implicitly)
3. this() can be used to invoke current class
constructor.
4. this can be passed as an argument in the method
call.
5. this can be passed as argument in the constructor
call.
6. this can be used to return the current class instance
from the method.
7. It is available only for non static
public class Cow {
int speed = 5;
public Cow() {
}
public Cow(Cow c) {
}
public Cow(int weight, Cow p) {
this();
}
public void run(int speed){
this.speed = speed;
walk(this);
}
public Cow walk( Cow w){
return this;
}
public void eat(){
new Cow(this);
}
}
Return Type of JAVA:
The data type of the return value must match the method's declared return type
We can't return an integer value from a method whose declaration type is void.
public class Example1 {
public void test1() {}
public int test2() {
return 3;}
public double test3() {
return 3.99;}
public boolean test4() {
return true;}
public char test5() {
return 'a';}
public String test6() {
return "Test";}
public Example1 test7() {
return new Example1();}
public int[] test8() {
return new int[7];}
• In test1() method when we try to return integer data we will get compile
time error. since method declaration type is void
• In test2() method when we try to return String data we will get compile
time error. since method declaration type is Integer
• In test3() method when we try to return String data we will get compile
time error. since method declaration type is double
• In test4() method when we try to return void data we will get compile
time error. since method declaration type is Boolean
• In test7() method we are returning object since method declaration is
class type.
• object declaration syntax
• Example1 obj = new Example1(); that's why we are
returning new Example1() for method test7()
• test8() method we are returning array object since method declaration is
array type.
• object declaration syntax for array
• int[] a = new int[7]; that's why we are returning new int[7] for method
test8()
What is method?
Definition of particular action.
Access specifier
Return type
Name of method
Parameters
Body of method
Method Overloading In Java
Method Overloading allow us to create more than one methods with same name by changing the
number of method arguments.
Similar to constructor overloading.
Compile time polymorphism.
Method Overloading is called as compile time polymorphisms.
Arguments list can be different in following ways
1) Numbers of parameters to method
2) Data Type of parameters
3) Sequence Type of parameters
Advantages:
1) Multiple methods with same name, but different params
2) Cleanliness of code
3) Increases readability of code
4) Methods can have different return type
5) Constructor overloading
Inheritance in Java
Points to Note:
1. Through inheritance child class will acquire all static / non static members of class.
2. We can't inherit private member of class.
public class ParentClass {
public void test() {
System.out.println("From ParentClass test()");
}
public int test1() {
System.out.println("From ParentClass test1()");
return 3;
}
public void test2() {
System.out.println("From ParentClass test2()");
}
}
public class ChildClass extends ParentClass {
public static void main(String[] args) {
ParentClass obj = new ChildClass();
obj.test();
obj.test1();
obj.test2();
}
}
Session 3
Join us for a Free Webinar on this Interesting topic
“Working with Selenium Grid”
Date: 4th April, 2019Time: 9 PM to 10 PM IST
Registration Link: https://bit.ly/2CC4Pd0
Interface in Java
• Interface has only unimplemented methods.
• Interface members are by default (Public static final).
• We call interface as 100 % abstract class.
• Multiple inheritance is possible in case of interface.
• We cannot create object of interface, since all the members are unimpeded.
• We cannot create constructor of interface. Since object creation for interface is not possible
• We cannot create object of interface. Since members are unimplemented.
• We can have multiple inheritance in interface
• We can have implemented methods in interface [Java 8]
Abstract Class in Java
· Abstract class will have implemented and unimpeded methods.
· We Cannot create object of Abstract class.
· We Can write constructor in Abstract class.
· To make class Abstract class we need to have at least one method as Abstract method.
· We can create Reference of Abstract class and object of child class.
The key technical differences between an abstract class and an interface are:
· Methods and members of an abstract class can be defined with any visibility, whereas
all methods of an interface must be defined as public (they are defined public by default).
· When inheriting an abstract class, a concrete child class must define the abstract
methods, whereas an abstract class can extend another abstract class and abstract
methods from the parent class don't have to be defined.
· Similarly, an interface extending another interface is not responsible for implementing
methods from the parent interface. This is because interfaces cannot define any
implementation.
· A child class can only extend a single class (abstract or concrete), whereas an
interface can extend or a class can implement multiple other interfaces.
· A child class can define abstract methods with the same or less restrictive visibility,
whereas a class implementing an interface must define the methods with the exact same
visibility (public)
public class TestInterface implements Example1,Example2,Example3
public interface D extends A,B (here A, B is interface)
What Is an Exception?
An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructio
Exception hierarchy in java
Difference between checked and unchecked exceptions
1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as checked
exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time rather they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Types of exception
public class TypesOfExceptions extends Test1{
static String s1;
//Exception in thread "main" java.lang.ArithmeticException: / by zero
public static void airthmeticException(){
int a = 9/0;
}
//Exception in thread "main" java.lang.NullPointerException
public static void nullPointerException(){
System.out.println(s1.concat("Test"));
}
//Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
public static void stackOverFlow(){
ArrayList<Integer> array = new ArrayList<Integer>();
while(true){
array.add(10);
}
}
//Exception in thread "main" java.lang.NumberFormatException: For input string: "Test"
public static void numberFormateException(){
String s1 = "Test";
int t = Integer.parseInt(s1);
int a = 9;
Double.parseDouble(s1);
Short.parseShort(s1);
Long.parseLong(s1);
Boolean.parseBoolean(s1);
}
//Exception in thread "main" java.io.FileNotFoundException: C:/Test.xls (No such file or dire
public static void fileNotFoundException() throws FileNotFoundException {
FileReader f = new FileReader("C://Test.xls");
}
//Exception in thread "main" java.lang.ClassNotFoundException: Test124
public static void classNotFoundException() throws ClassNotFoundException{
Class.forName("Test124");
}
//Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
public static void arrayIndexOutodbound(){
int[] a = new int[5];
System.out.println(a[5]);
}
//Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
public static void outOfMemoryException(){
long data[] = new long[1000000000];
}
//Exception in thread "main" java.lang.ClassCastException: coreJavaTutorial.ExcepionInJava.
//cannot be cast to coreJavaTutorial.ExcepionInJava.TypesOfExceptions
public static void classCastException(){
Test1 obj = new Test1();
System.out.println((TypesOfExceptions)obj);
}
//Exception in thread "main" java.lang.NullPointerException
public static void inputOutputException(){
InputStreamReader obj = new InputStreamReader(null);
}
//Exception in thread "main" java.lang.IllegalStateException: Scanner closed
public static void illigalStateException(){
String s = "Hello World";
Scanner scanner = new Scanner(s);
System.out.println("" + scanner.nextLine());
scanner.close();
System.out.println("" + scanner.nextLine());
}
// Checked Exception
public void test() throws InterruptedException{
Thread.sleep(2000);
}
How to handle the exception?
By Try Catch Block:
• As we know that when exception comes execution of program will terminate. To avoid that we
need to handle the exception.
• We need to use try catch block to handle the exception
public class Example1 {
public static void main(String[] args) {
try {
int i = 9/0;
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("test is runnign
evenafter exception");
}
}
public class Example1 {
public static void main(String[] args) {
String s1 = null;
try {
s1.toLowerCase();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("test is runnign
evenafter exception1");
System.out.println("test is runnign
evenafter exception2");
System.out.println("test is runnign
evenafter exception3");
}
}
Q: Is it possible to catch particular exception by catch block
Answer: - Yes
Q: - Is it possible to write multiple catch block for singe try block.
Answer: - Yes
public class Example2 {
public static void main(String[] args) {
try {
int a = 9 / 0;
int[] array = new int[3];
System.out.println(array[4]);
} catch (ArithmeticException e) {
System.out.println("ArithmeticException is gettign called");
e.printStackTrace();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException is gettign called");
e.printStackTrace();
}
System.out.println("Runnign code aftre exception1");
System.out.println("Runnign code aftre exception2");
System.out.println("Runnign code aftre exception3");
}
}
· In This program, when we get ArithmeticException catch block with ArithmeticException will get executed.
· When We get ArrayIndexOutOfBoundsException catch block with ArrayIndexOutOfBoundsException will g

More Related Content

What's hot (20)

Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Core java Essentials
Core java EssentialsCore java Essentials
Core java Essentials
 
Introduction to-programming
Introduction to-programmingIntroduction to-programming
Introduction to-programming
 
Core java
Core java Core java
Core java
 
Core java concepts
Core java concepts Core java concepts
Core java concepts
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)
 
Learn Java Part 2
Learn Java Part 2Learn Java Part 2
Learn Java Part 2
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
 
Basics java programing
Basics java programingBasics java programing
Basics java programing
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
Invoke dynamics
Invoke dynamicsInvoke dynamics
Invoke dynamics
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
Project Coin
Project CoinProject Coin
Project Coin
 
Method Handles in Java
Method Handles in JavaMethod Handles in Java
Method Handles in Java
 

Similar to Java For Automation

Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for seleniumapoorvams
 
JAVA(module1).pptx
JAVA(module1).pptxJAVA(module1).pptx
JAVA(module1).pptxSRKCREATIONS
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentJayaprakash R
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2Rakesh Madugula
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsMahika Tutorials
 
Introduction to Kotlin for Android developers
Introduction to Kotlin for Android developersIntroduction to Kotlin for Android developers
Introduction to Kotlin for Android developersMohamed Wael
 
core java material.pdf
core java material.pdfcore java material.pdf
core java material.pdfRasa72
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructorShivam Singhal
 
java basic for begginers
java basic for begginersjava basic for begginers
java basic for begginersdivaskrgupta007
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT studentsPartnered Health
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptxVijalJain3
 

Similar to Java For Automation (20)

Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for selenium
 
JAVA(module1).pptx
JAVA(module1).pptxJAVA(module1).pptx
JAVA(module1).pptx
 
Java
JavaJava
Java
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App development
 
core java
core javacore java
core java
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2
 
Java tut1
Java tut1Java tut1
Java tut1
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 
Introduction to Kotlin for Android developers
Introduction to Kotlin for Android developersIntroduction to Kotlin for Android developers
Introduction to Kotlin for Android developers
 
Module 1.pptx
Module 1.pptxModule 1.pptx
Module 1.pptx
 
core java material.pdf
core java material.pdfcore java material.pdf
core java material.pdf
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
 
Core java
Core javaCore java
Core java
 
java basic for begginers
java basic for begginersjava basic for begginers
java basic for begginers
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT students
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
 
Cse java
Cse javaCse java
Cse java
 

Recently uploaded

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 

Recently uploaded (20)

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 

Java For Automation

  • 3. Run a sample Java program on notepad public class LetsLearn { /* I am trying to change * I will try to print sum of two numbers */ public static void main(String []args) { int sum=0,a=10,b=20; sum = a + b; System.out.println("The sum is " + sum); // Will print sum of a and b } }
  • 4. Run a sample Java program on notepad public class LetsLearn { /* I am trying to change * I will try to print sum of two numbers */ public static void main(String []args) { int sum=0,a=Integer.parseInt(args[0]),b=Integer.parseInt(args[1]); sum = a + b; System.out.println("The sum is " + sum); // Will print sum of a and b } }
  • 5. Important Features of Java • Simple • Platform Independent • Architectural Neutral: A Language or Technology is said to be Architectural neutral which can run on any available processors in the real world without considering their development and compilation. • Portable: If any language supports platform independent and architectural neutral feature known as portable. • Multi Threading: A flow of control is known as a thread. When any Language executes multiple thread at a time that language is known as multithreaded e. It is multithreaded. • Distributed: Using this language we can create distributed applications. In distributed application multiple client system depends on multiple server systems so that even problem occurred in one server will never be reflected on any client system. • Networked: It is mainly designed for web based applications, J2EE is used for developing network based applications.
  • 6. • Robust: Simply means of Robust are strong. It is robust or strong Programming Language because of its capability to handle Run-time Error, automatic garbage collection • Dynamic: It supports Dynamic memory allocation due to this memory wastage is reduce and improve performance of the application. • Secured: It is a more secure language compared to other language; In this language, all code is covered in byte code after compilation which is not readable by human. • Object Oriented: It supports OOP's concepts because of this it is most secure language
  • 7. JAVA Architecture Class Loader Runtime Area Method Area Heap Stack PC Register Native Method Stack Execution Engine Native Method Interface Native Library
  • 8. Variables and Data Types Reserve area in memory (int data=50;) Local variable : Declared inside method. Instance variable : Inside class but outside method. It is not declared as static. Static variable : Declared as static. It cannot be local. public class Test { int k = 90; // instance variable static int l = 20; //static variable int j = 20; //instance variable public void testLogin(int a){ int p = 90; // local variable } public void testClick(int b){ int f= 90; // local variable } }
  • 9. Primitive Non Primitive Numeric Integer Floating point Double FloatByte Short Longint Non Numeric Character Boolean Data Types Strings Arrays User defined
  • 10. Data Type Default Value Default size boolean false 1 bit char 'u0000' 2 byte byte 0 1 byte short 0 2 byte int 0 4 byte long 0L 8 byte float 0.0f 4 byte double 0.0d 8 byte Primitive data types Non-primitive data types: Class Type • String s1; • Student obj; • Employee emp;
  • 11. Increment/Decrement operator: Increment Operator: Increments the value by 1 Decrement operator: Decrements the value by 1 package com.twoPir.FirstSession; public class IncrementAndDecrementOperator { public static void main(String[] args) { // TODO Auto-generated method stub int i=10; int k = ++i; System.out.println(k); int j =11; int l=--j; System.out.println(l); } }
  • 12. Increment/Decrement operator: What should be the output of below program? package com.twoPir.FirstSession; public class ArithmeticIncrementOp { public static void main(String[] args) { // TODO Auto-generated method stub int i =10; int j = i++ + ++i; System.out.println(j); } } Lets run it in eclipse and see the Output. Then understand the output in next slides
  • 13. Increment/Decrement operator: Let’s see the output package com.twoPir.FirstSession; public class ArithmeticIncrementOp { public static void main(String[] args) { // TODO Auto-generated method stub int i =10; int j = i++ + ++i; System.out.println(j); } } Value of “i” used in the expression is 10, but “i” is updated in memory to 11 Value of “i” is updated to 12. As it was already 11 in memory
  • 14. If block: Java if statement is used to check condition. It checks Boolean condition: true or false. Syntax: If(Condition){ //code to be executed } condition Code inside if Code outside if False True
  • 15. If Else block: Java if else block is used to check condition. It executes if statement if condition is true otherwise it executes code in else block Syntax: If(Condition){ //code to be executed }else //code to be executed condition Code inside if Code after else False True Code inside else
  • 16. Nested If block: A nested if is an if statement that is the target of another if or else. Nested if statements mean an if statement inside an if statement. Yes Java allows us to nest if statements within if statements Syntax: If(Condition 1) { Executes when condition 1 is true if(Condition 2) { Executes when condition 2 is true } }
  • 17. Switch Statement: The Java switch statement executes one statement from multiple conditions Syntax: switch(Expression) { Case 1: //code to be executed break; //optional Case 2: //code to be executed break; //optional Default: //code to be executed if none of the case matches }
  • 18. For Loop: For loop in java is used to iterate chunk of codes several times. If the number of times is fixed then its recommended to use For loop. 3 types of For loop: • Simple For Loop • For-each or Enhanced for loop • Labeled for loop Simple For Loop Syntax: for(initialization; condition; incr/decr){ //Code to be executed } Initialization: We initialize the variable, it marks the start of for loop. An already declared variable can be used or can be declared in for loop tself Condition: Every iteration will be performed if the condition is true otherwise fol loop terminates Incr/decr: Updates the variable for next iteration
  • 19. For Loop: For Each loop will iterate over each data in given array or set of data. Syntax: for(dataType var : array){ //Code to be executed } package com.twoPir.FirstSession; public class ForEachLoopExample1 { public static void main(String[] args) { // TODO Auto-generated method stub int arr[]= {1,2,3,4}; for(int i:arr) { System.out.println(i); } } }
  • 20. For Loop: Labeled For loop : Can have name of each for loop. We use label before the for loop Syntax: labelName: for(initialization; condition; incr/decr){ //Code to be executed } package com.twoPir.FirstSession; public class LabeledForLoopExample1 { public static void main(String[] args) { // TODO Auto-generated method stub aa:for (int i = 0; i < 3; i++) { bb:for (int j = 1; j <=3; j++) { if(i==2&&j==2) { break aa; } System.out.println(i+" "+j); } } } }
  • 21. While Loop: The Java while loop is used to iterate a part of the program several times. If the number of iteration is not fixed, it is recommended to use while loop. Simple For Loop Syntax: while(condition){ //Code to be executed }
  • 23. OOPS Concept Class: In lay man term it means the group of object. Suppose I call a cow by its class, i.e. Animal. My statement will be “Animal is grazing”. No one will understand that to which animal am referring to. So statement should be Cow is grazing. Here Animal is class, Cow, Elephant etc are objects. Object: Which had properties and behavior e.g. Ram has properties like (color, height, weight) and behavior like he can (Walk ,eat run etc.) Method: Definition of behavior of object is call as Method e.g. (Walk ,eat run etc.) public class Car{ String color = “Magenta"; public void drive() { String Speed = "10 KM"; } public static void main(String[] args) { Car obj = new Car(); obj.drive(); } }
  • 24. Static and Non Static • Static Members of class are accessed by class Name, Since static members are class • Non Static members of class are accessed by object. Non Static members are object members int i =0 int i =0 int i =0 obj1 obj2 obj3 Int j
  • 25. Name Convention class name should start with uppercase letter interface name should start with uppercase letter method name should start with lowercase letter variable name should start with lowercase letter package name should be in lowercase constants name should be in uppercase letter Naming convention
  • 26. Constructor in Java • A constructor in Java is a block of code similar to a method that’s called when an instance of an object is created. Here are the key differences between a constructor and a method: 1. A constructor doesn’t have a return type. 2. The name of the constructor must be the same as the name of the class. 3. Unlike methods, constructors are not considered members of a class. 4. A constructor is called automatically when a new instance of an object is created. Types of constructors: 1. Default constructor (no-arg constructor) 2. Parameterized constructor public class Cow { public Cow() { } public Cow(int weight) { } } Q: Is it possible to Create object of default constructor when we have only parameterized constructor in class Answer: - NO (when we explicitly create parameterized constructors in class then java compiler will not keep by default constructor in class)
  • 27. Use Constructor in Java • The purpose of constructor is to initialize the object of class • Default constructor is used to provide the default values to the object like 0, null etc. depending on datatype • Parameterized is used to provide different values to different variable. Q. Is constructor overloading is possible? Ans: Yes
  • 28. This is a java keyword. It works as a reference to current object. This in Java: 1. this can be used to refer current class instance variable. 2. this can be used to invoke current class method (implicitly) 3. this() can be used to invoke current class constructor. 4. this can be passed as an argument in the method call. 5. this can be passed as argument in the constructor call. 6. this can be used to return the current class instance from the method. 7. It is available only for non static public class Cow { int speed = 5; public Cow() { } public Cow(Cow c) { } public Cow(int weight, Cow p) { this(); } public void run(int speed){ this.speed = speed; walk(this); } public Cow walk( Cow w){ return this; } public void eat(){ new Cow(this); } }
  • 29. Return Type of JAVA: The data type of the return value must match the method's declared return type We can't return an integer value from a method whose declaration type is void. public class Example1 { public void test1() {} public int test2() { return 3;} public double test3() { return 3.99;} public boolean test4() { return true;} public char test5() { return 'a';} public String test6() { return "Test";} public Example1 test7() { return new Example1();} public int[] test8() { return new int[7];} • In test1() method when we try to return integer data we will get compile time error. since method declaration type is void • In test2() method when we try to return String data we will get compile time error. since method declaration type is Integer • In test3() method when we try to return String data we will get compile time error. since method declaration type is double • In test4() method when we try to return void data we will get compile time error. since method declaration type is Boolean • In test7() method we are returning object since method declaration is class type. • object declaration syntax • Example1 obj = new Example1(); that's why we are returning new Example1() for method test7() • test8() method we are returning array object since method declaration is array type. • object declaration syntax for array • int[] a = new int[7]; that's why we are returning new int[7] for method test8()
  • 30. What is method? Definition of particular action. Access specifier Return type Name of method Parameters Body of method
  • 31. Method Overloading In Java Method Overloading allow us to create more than one methods with same name by changing the number of method arguments. Similar to constructor overloading. Compile time polymorphism. Method Overloading is called as compile time polymorphisms. Arguments list can be different in following ways 1) Numbers of parameters to method 2) Data Type of parameters 3) Sequence Type of parameters Advantages: 1) Multiple methods with same name, but different params 2) Cleanliness of code 3) Increases readability of code 4) Methods can have different return type 5) Constructor overloading
  • 32. Inheritance in Java Points to Note: 1. Through inheritance child class will acquire all static / non static members of class. 2. We can't inherit private member of class. public class ParentClass { public void test() { System.out.println("From ParentClass test()"); } public int test1() { System.out.println("From ParentClass test1()"); return 3; } public void test2() { System.out.println("From ParentClass test2()"); } } public class ChildClass extends ParentClass { public static void main(String[] args) { ParentClass obj = new ChildClass(); obj.test(); obj.test1(); obj.test2(); } }
  • 34. Join us for a Free Webinar on this Interesting topic “Working with Selenium Grid” Date: 4th April, 2019Time: 9 PM to 10 PM IST Registration Link: https://bit.ly/2CC4Pd0
  • 35. Interface in Java • Interface has only unimplemented methods. • Interface members are by default (Public static final). • We call interface as 100 % abstract class. • Multiple inheritance is possible in case of interface. • We cannot create object of interface, since all the members are unimpeded. • We cannot create constructor of interface. Since object creation for interface is not possible • We cannot create object of interface. Since members are unimplemented. • We can have multiple inheritance in interface • We can have implemented methods in interface [Java 8]
  • 36. Abstract Class in Java · Abstract class will have implemented and unimpeded methods. · We Cannot create object of Abstract class. · We Can write constructor in Abstract class. · To make class Abstract class we need to have at least one method as Abstract method. · We can create Reference of Abstract class and object of child class.
  • 37. The key technical differences between an abstract class and an interface are: · Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public (they are defined public by default). · When inheriting an abstract class, a concrete child class must define the abstract methods, whereas an abstract class can extend another abstract class and abstract methods from the parent class don't have to be defined. · Similarly, an interface extending another interface is not responsible for implementing methods from the parent interface. This is because interfaces cannot define any implementation. · A child class can only extend a single class (abstract or concrete), whereas an interface can extend or a class can implement multiple other interfaces. · A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility (public) public class TestInterface implements Example1,Example2,Example3 public interface D extends A,B (here A, B is interface)
  • 38. What Is an Exception? An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructio Exception hierarchy in java
  • 39. Difference between checked and unchecked exceptions 1) Checked Exception The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time. 2) Unchecked Exception The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime. 3) Error Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc. Types of exception public class TypesOfExceptions extends Test1{ static String s1; //Exception in thread "main" java.lang.ArithmeticException: / by zero public static void airthmeticException(){ int a = 9/0; } //Exception in thread "main" java.lang.NullPointerException public static void nullPointerException(){ System.out.println(s1.concat("Test")); }
  • 40. //Exception in thread "main" java.lang.OutOfMemoryError: Java heap space public static void stackOverFlow(){ ArrayList<Integer> array = new ArrayList<Integer>(); while(true){ array.add(10); } } //Exception in thread "main" java.lang.NumberFormatException: For input string: "Test" public static void numberFormateException(){ String s1 = "Test"; int t = Integer.parseInt(s1); int a = 9; Double.parseDouble(s1); Short.parseShort(s1); Long.parseLong(s1); Boolean.parseBoolean(s1); }
  • 41. //Exception in thread "main" java.io.FileNotFoundException: C:/Test.xls (No such file or dire public static void fileNotFoundException() throws FileNotFoundException { FileReader f = new FileReader("C://Test.xls"); } //Exception in thread "main" java.lang.ClassNotFoundException: Test124 public static void classNotFoundException() throws ClassNotFoundException{ Class.forName("Test124"); } //Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 public static void arrayIndexOutodbound(){ int[] a = new int[5]; System.out.println(a[5]); } //Exception in thread "main" java.lang.OutOfMemoryError: Java heap space public static void outOfMemoryException(){ long data[] = new long[1000000000]; }
  • 42. //Exception in thread "main" java.lang.ClassCastException: coreJavaTutorial.ExcepionInJava. //cannot be cast to coreJavaTutorial.ExcepionInJava.TypesOfExceptions public static void classCastException(){ Test1 obj = new Test1(); System.out.println((TypesOfExceptions)obj); } //Exception in thread "main" java.lang.NullPointerException public static void inputOutputException(){ InputStreamReader obj = new InputStreamReader(null); } //Exception in thread "main" java.lang.IllegalStateException: Scanner closed public static void illigalStateException(){ String s = "Hello World"; Scanner scanner = new Scanner(s); System.out.println("" + scanner.nextLine()); scanner.close(); System.out.println("" + scanner.nextLine()); } // Checked Exception public void test() throws InterruptedException{ Thread.sleep(2000); }
  • 43. How to handle the exception? By Try Catch Block: • As we know that when exception comes execution of program will terminate. To avoid that we need to handle the exception. • We need to use try catch block to handle the exception public class Example1 { public static void main(String[] args) { try { int i = 9/0; } catch (Exception e) { e.printStackTrace(); } System.out.println("test is runnign evenafter exception"); } } public class Example1 { public static void main(String[] args) { String s1 = null; try { s1.toLowerCase(); } catch (Exception e) { e.printStackTrace(); } System.out.println("test is runnign evenafter exception1"); System.out.println("test is runnign evenafter exception2"); System.out.println("test is runnign evenafter exception3"); } }
  • 44. Q: Is it possible to catch particular exception by catch block Answer: - Yes Q: - Is it possible to write multiple catch block for singe try block. Answer: - Yes public class Example2 { public static void main(String[] args) { try { int a = 9 / 0; int[] array = new int[3]; System.out.println(array[4]); } catch (ArithmeticException e) { System.out.println("ArithmeticException is gettign called"); e.printStackTrace(); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBoundsException is gettign called"); e.printStackTrace(); } System.out.println("Runnign code aftre exception1"); System.out.println("Runnign code aftre exception2"); System.out.println("Runnign code aftre exception3"); } } · In This program, when we get ArithmeticException catch block with ArithmeticException will get executed. · When We get ArrayIndexOutOfBoundsException catch block with ArrayIndexOutOfBoundsException will g