Java Full Course Tutorial

Java Full Course Tutorial, Java Environment Setup, Java Language Fundamentals, Java Programming Examples, and Java Object-Oriented Programming concepts.

Java Programming Language was developed by James Gosling in 1995 for Sun Microsystems, later It was acquired by Oracle in 2010.

Selenium Online Training with Project (by G C Reddy)

Java Full Course Tutorial

  1. Java Environment Setup

  2. Java Syntax

  3. Java Program Structure

  4. Comments in Java.

  5. Java Data Types

  6. Java Variables

  7. Java Operators

  8. Java Control Flow – Conditional/Decision Making Statements

  9. Java Control Flow – Loop Statements

  10. Java Control Flow – Branching Statements

  11. String handling in Java

  12. Java Arrays,

  13. ArrayLists in Java

  14. Java User Input

  15. Java File handling

  16. Java Methods – Predefined

  17. Java Methods – User-defined.

  18.  Java Constructor

  19. Java Exception handling

  20. Java Object-oriented programming

  21. Java – Inheritance

  22. Java – Polymorphism

  23. Java – Abstraction

  24. Java Encapsulation

Introduction to Java Programming

What is Java?

• Java is a General-purpose programming language, to be used for writing software in the widest variety of application domains.

• Java Programming language was developed by James Gosling with his team (Java Team, also known as Green Team) in 1995 for Sun Microsystems, later Java was acquired by Oracle in 2010.

• Java is an Object-oriented, and Platform independent Programming language.

• In java, everything is an object which has some data and behavior. Java can be easily extended since it is based on the Object model.

• Java code is compiled into an intermediate format (bytecode), which can be executed on any systems for which Java virtual machine is ported. That means you can write a Java program once and run it on Windows, Mac, Linux, or Solaris without re-compiling. Thus the slogan “Write once, run anywhere” of Java.

Features of Java

i. High Performance

• Java programs are faster in execution when it compares to other programming languages like C, C++, Python, etc,

• Java’s bytecode makes it a lot faster than other languages because of its innate similarity to native code.

• Java architecture is designed to reduce overheads during run-time. The concept of multithreading in Java also increases the execution speed of Java programs.

ii. Compiled and interpreted

• A Java program is first compiled into bytecode which JRE can understand. Byte code is then interpreted by the JVM making it an interpreted language.

iii. Object-Oriented Programming

• Object-oriented development includes concepts of Objects and Classes and many more. This enables developers to have a wide variety of options for designing their software.

iv. Platform-Independent

• Java is a platform-independent language unlike other languages like C, C++, etc. Because C and C++ are platform-dependent languages.

• Java code converted into bytecode by a compiler, this bytecode is a platform-independent code it can be run on multiple platforms, i.e., Write Once and Run Anywhere (WORA).

v. Simple

• Java coding style is very clean and easy to understand. It removes complexity because it doesn’t use complex and difficult features of other languages like C and C++.

vi. Multi-threaded

•  A thread is an independent path of execution within a program, executing concurrently. Multithreaded means handling multiple tasks simultaneously or executing multiple portions (functions) of the same program in parallel.

•  The code of java is divided into smaller parts and Java executes them in a sequential and timely manner.

vii. Portable

Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn’t require any implementation.

viii. Dynamic

•  Java supports dynamic compilation and automatic memory management (garbage collection).

•  Java is a dynamic language, it supports the dynamic loading of classes. It means classes are loaded on demand. It also supports functions from its native languages, i.e., C and C++.

ix. Secured

•  Java is best known for its security. With Java, we can develop virus-free systems.

JVM, JRE, and JDK

JVM

JVM (Java Virtual Machine) is an abstract machine that enables your computer to run a Java program.

JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform-dependent because the configuration of each OS is different from the other.

JRE

JRE (Java Runtime Environment) is used to provide the runtime environment for Java Applications, It is a software package that provides Java class libraries, Java Virtual Machine (JVM), and other components that are required to run Java applications.

JRE is the superset of JVM.

JDK

(Java Development Kit) is a software development kit required to develop applications in Java. When you download JDK, JRE is also downloaded with it.

JDK contains JRE + development tools.

Editions of Java

There are four platforms of the Java programming language:

1. Java Standard Edition (Java SE) / Core Java

2. Java Enterprise Edition (Java EE) / Advanced Java

3. Java Micro Edition (Java ME)

4. JavaFX

Applications/Uses of Java

Java is used to develop:

  1. Desktop GUI Applications / Windows Applications
  2. Web-based Applications
  3. Enterprise Applications
  4. Mobile Applications
  5. Scientific Applications
  6. Web-based Applications
  7. Embedded Systems
  8. Big Data Technologies
  9. Distributed Applications
  10. Cloud-based Applications
  11. Web servers and Application servers
  12. Software Tools (Ex: Selenium, JMeter, and SoapUI tools we developed using Java)
  13. Gaming Applications
  14. Smart Cards, Etc, 

1. Java Environment Setup

Java Environment is required is to write and execute Java programs. We have three steps in Computer Programming,

1. Write a Program (in an Editor)
2. Compile the Program
3. Run the program

Steps for Java Programming Environment Setup:

> Download Java Software (JDK) and Install
> Set Java Environment variable in the OS Environment
> Download Eclipse IDE and Extract
> Write Java Programs in Eclipse Editor and Run

Eclipse IDE:

Eclipse IDE is an Open Source software, It is a platform to write & execute Software programs like Java, C, C++, Perl, Python, Ruby, PHP, etc.

It provides an Editor for writing Programs, Syntax Guidance, Context Help, and Auto compilation, etc.

Launch Eclipse IDE, write a sample program, and execute the program.

Java Sample Program:

public class Sample {

public static void main(String[] args) {
int a=10, b=20;
System.out.println(“Addition of a, b is: “+ (a+b));

if (a>b){
System.out.println(“A is a Big Number”);
}
else {
System.out.println(“B is a Big Number”);
}
}
}

 


2. Java Syntax

1. Java is a case sensitive language

Note: All Java keywords and reserved words are small letters
(if, for, public, main, true, false, null…)

2. The first letter of class name should be in upper case

sample //Incorrect
Sample //Correct
Firstprogram //Correct
FirstProgram ////Correct

3. Java Method names should start with lower case

4. Java program file name should exactly match with the class name

5. Java program execution starts from the main method, which is mandatory in every Java program

6. Every statement /step should end with a semicolon (;)

7. Code blocks (Conditional, Loop, Method, etc, enclosed with {}).

8. Java supports Explicit declaration of Data Types

In Java,
int sno =123;//Correct
int x;//Correct
char a=’A’; //Correct
boolean y=true;
abc =100; //Incorrect

In VBScript
Dim city
city =100
.
city =”India”
.
city=1.23
.
city=#10/10/2010#

9. Java supports Explicit declaration of Variables

int a, b;
a=10;
b=20;
c=30;//Incorrect

In VBScript

Dim a
a=100
b=200 ‘Correct


3. Java Program Structure

Sections of Java Program:

1. Documentation Section – Optional

2. Package Statement – Mandatory

3. Import Statement/s – Depends on our program requirement

4. Class Definition { //Mandatory

5. Interface Section //Depends on our program requirement

6. main method(){
//Main Program contains normal statements and code blocks
Object Creation //Depends on our program requirement
Declarations/Initialization/Reading – normal statements
Operations/Display statements etc…
Code Blocks
Conditions/Decision-making blocks
Loop Blocks
Constructor Block
Etc…
}
Interface Section //Depends on our program requirement
}

Java Program Example:

//This program is for explaining Java Syntax and program Structure.

package abcd;

import java.util.Scanner;

public class Sample {
//Create a Non static method with arguments and return a value
public int add(int a, int b) {
int result;
result=a+b;
return result;
}
//Create a Non static method without arguments and returns Nothing
public void sub() {
int x=100;
int y=50;
System.out.println(x-y);
}
//Create a Static method with arguments and return a value
public static int multiply(int num1, int num2) {
int result= num1*num2;
return result;
}
//Create a Static method without arguments and returns Nothing
public static void comparision() {
int x=100, y=50;

if (x>y) {
System.out.println(“X is Big Number”);
}
else {
System.out.println(“Y is Big Number”);
}
}

public static void main (String [] args){
Scanner scan = new Scanner (System.in);

System.out.println(“Enter Your Name”);
String myName = scan.nextLine();
System.out.println(“My Name is: ” + myName);
int a; //Variable Declaration
a=100;
int b=200; // Variable Declaration with Initialization
char x=’Y’;
String myCountry = “India”;
int c, d, e; //Declaring multiple variables
int f=20, g=40, h=60; //Declaring multiple variables with Initialization
final int price=100;

if (a>b)
{
System.out.println(“A is Big Number”);
}
else
{
System.out.println(“B is Big Number”);
}
System.out.println(“”);

for (int i=1; i<=10; i++)
{ // Print 1 to 10 Numbers
System.out.println(i);
}
System.out.println(“”);

int i=1;
while (i<=5) {
System.out.println(i);
i++;
}
System.out.println(“My Output”);
//Print 1 to 5 Numbers except 4
for (int j=1; j<=5; j++) {
if (j!=4) {
System.out.println(j);
}
}

//Create Object and call non static methods
Sample obj = new Sample();
int val = obj.add(100, 200);
System.out.println(val);//300

System.out.println(obj.add(10, 20));//30

obj.sub();//50

//Call Static methods

val = multiply(10, 40);
System.out.println(val);//400

comparision();//X is Big Number
}
}


4. Java Comments

Comments are English words used for Code Documentation

Purpose of Comments:
To make the Code Readable
To make the code prevent from Execution

Note: Java Supports single-line comments and multiple-line comments.

Syntax:

a) Use // for Single line Syntax

b) Use /*……………….

…………………………..

…………………………..

……………….*/ for multiple line comments

Any text between /* and */ will be ignored by Java.

Note: It is up to you which you want to use. Normally, we use // for short comments, and /* */ for longer.

Example:

public static void main(String[] args) {
// It is a Sample Program
int a, b; //Declaration of Variables
a=10; b=20; // Initialization
System.out.println(a+b);//30

/*if (a > b){
System.out.println(“A is a Big Number”);
}
else {
System.out.println(“B is a Big Number”);
}*/

}
}


5. Java Data Types

What is Data Type?

Data Type is a classification of the type of data that a Variable or Constant or Method can hold in computer programming.

Data Types specify the different sizes and values that can be stored in the variable.

Example: Character, Number, Number with decimal values, Logical data, String, Date, Currency etc…

Note: Java supports the explicit declaration of Data Types.
(We need to specify the Data Type before declaring Variables, Constants, and methods…)

a. Declaring Variables with Data Types

Syntax:

dataType variableName;
Or
dataType variableName = value;
Or
dataType variable1Name, variable2Name, variable3Name;
or
dataType variable1Name=value, variable2Name= value, variable3Name=value;

Example:

int a;
a=10;
int b=100;
int c, d, e;
c=30; d=40; e=50;
int f=60, g=70, h=80;

b. Declaring A Method with Return Value

public int add (int a, int b, int c){
……………………..
……………………..
……………………..
return…;
}

Two Categories of Data Types in Java

1. Primitive Data Types
2. Non-primitive data Types

Primitive Data Types

a. Integer Data Types

1. byte (8 bits)

Minimum value is -128 (-2^7), Maximum value is 127 (inclusive)(2^7 -1)
Default value is 0
byte a=10;

2. short (16 bits)

Minimum value is -32,768 (-2^15)
Maximum value is 32,767 (inclusive) (2^15 -1)
Default value is 0.
short b=1000;

3. int (32 bits)

Minimum value is – 2,147,483,648 (-2^31)
Maximum value is 2,147,483,647(inclusive) (2^31 -1)
The default value is 0
int c =10000;
int d=12;
int e=1;

4. long (64 bits)

Minimum value is -9,223,372,036,854,775,808(-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)
Default value is 0L
long f =1000000000000000;

b. Relational Data Types (Numbers with Decimal Places)

5. float (32 bits)

float x = 10.23f;

6. double (64 bits)

double y = 1234.5678765;

c. Character Data Type

7. character

char z = ‘A’;
char s = ‘1’;
char r = ‘*’;

d. Conditional Data Type

8. boolean

boolean k = true/false;

Non Primitive data types / Reference data types

Non Primitive data types in Java are Objects (Strings, Array, etc.)

Example:

Sample a = new sample();
String x = ‘India”;

123 – Integer Data Type
‘Y’ -Character
123.34 – float/double
“Selenium Testing” – String
“abc123*&^” – String
“123” – String
1 – Integer
‘1’ – Character

Data Type Conversion:

Whenever we read data then the computer program considers that data as String type data, we need to convert the data in order to perform mathematical operations, Note: Generally we convert String type to Integer Type/ Relational type, we can’t convert Alpha bytes to numbers, etc.


6. Variables in Java

What is a Variable?

A named memory location to store the temporary data within a program.

Two types of Memory in Computer Environment
a. Primary Memory (RAM)
b. Secondary Memory (ROM / HDD, DVD, USB, etc.)

2. Declaration of Variables

Java supports the explicit declaration of variables

In Java

int a;
a=100;
b=200; //Incorrect

In VBScript
Dim a
a=100
b=200 ‘Correct

Variable Declaration Syntax:

dataType variableName;

dataType variableName=value;

dataType variable1Name, variable2Name, variable3Name;

dataType variable1Name=value, variable2Name=value, variable3Name=value;

3. Assign Values to Variables

a. Initialization

int x=100;// Initialization

int y;
.
.
y=200; // Initialization

int x=y; //Reading

b. Reading
i. Read input using input devices
ii. Read data from files
iii. Read data from Application Objects

4) Variable naming restrictions

a. Java variables are case sensitive

int a;
int B;
.
a=100;
B=200;
.
.
b=300; //Incorrect

b. Java Variable names should start with a letter, or _ or $

myvar
MYVAR
$myvar
_myvar
7myvar //Incorrect
myvar7
*myvar //Incorrect

c. Variable names should not match with Java keywords

int a;
int do; //Incorrect
int od;

if, for, do, while, public, private, new,
true, false, null etc…

d. Java variables must be unique in the scope of the declaration
int a;
int b, c, d;
int e, f, a; //Incorrect

e. Variable names must not exceed 255 characters
1 to 255

5. Types of Variables

Three types of variables in Java
a. Local variables (Local variable is declared in methods or blocks)
b. Instance Variable (Instance variables are declared in a class but outside of a method or any code block)
c. Static / Class Variables (Variable that is declared as static, it cannot be local

6. Variable Example

public class Sample {
static int x=100; //Static Variable
int z=200; //Non static variable

public int add() {
int a=10, b=20; //Local variables
return a+b+x+z;
}
public int add2() {
int c=30, d=20; //Local variables
return c+d+x+z;
}

public static void main(String[] args) {
//static int f=500;
Sample obj=new Sample();

System.out.println(obj.add());//330
System.out.println(obj.add2());//350

int s=400; //Non static variable
System.out.println(x+y);//300
System.out.println(x);//100
System.out.println(obj.z+s);//600

if (s>300) {
int g=22;
System.out.println(g+x+y);//322
}
//System.out.println(g+x+y);//322

}
static int y=200; //Static Variable
}


7. Operators in Java

Operators are used to performing Arithmetic, Comparison, and Logical Operations.
Operators are used to performing operations on variables and values.

Example:

public class JavaOperators {

public static void main(String[] args) {
int a=25, b=20;

int c=a+b;
int d=30*40;
System.out.println(c);//45
System.out.println(d);//70
System.out.println(100+200);//300
System.out.println(“Selenium” + ” Testing”);//Selenium Testing

if (a>b){
System.out.println(“A is a Big Number”);
}

for (int i=1; i<=5; i++){
System.out.println(i);
}
//System.out.println(i);// i is local variable
System.out.println(b);
}
}

Categories of Operators in Java

1. Arithmetic Operators

2. Unary Operators

3. Assignment Operators

4. Comparison / Relational Operators

5. Logical Operators
Etc.

1. Arithmetic Operators

Addition, Subtraction, Multiplication, Division, Modules, Exponentiation etc…..

i. Addition + (Addition, String Concatenation)

int a=10, b=20;
int c= a+b; //Addition

String d=”Selenium”;
String e= “Testing”;
String f=d+e; //Concatenation

ii. Subtraction – (Subtraction, Negation)

int a=10, b=20;
int c= a-b; //Subtraction

int d = -100; //Negation

iii. Multiplication *

iv. Integer Division /

v. Modules %

String + String = String
Number + Number = Number
String + Number = String
String + Number + Number = String
Number + Number + String = String

Example1:

int a=10, b=20;
String c=”10″, d=”20″;

System.out.println(a+b);//30
System.out.println(c+d);//1020
System.out.println(100+200);//300
System.out.println(“Java”+”Program”);//JavaProgram

System.out.println(“Addition of a, b is: “+(a+b));//Addition of a, b is: 30

System.out.println(1+1);//2
System.out.println(“A”+”B”);//AB
System.out.println(1+”A”);//1A
System.out.println(“A”+1);//A1

Example2:

int a=10, b=3;
double x=10, y=3;
String c=”10″, d=”20”;

System.out.println(a+b);//13
System.out.println(c+d);//1020
System.out.println(a-b);//7
System.out.println(-100);//-100
System.out.println(a*b);//30
System.out.println(a/b);//3
System.out.println(x/y);//3.33333333
double d= Math.pow(10, 4);
System.out.println(d);//10000
System.out.println(a%b);//1

2. Unary Operators

The Java Unary operators require only one operand, Unary operators are used to performing various operators like increment, decrements, etc.

Java Unary Operators

++, —

Example:

int x=10;

System.out.println(x);//10
//System.out.println(x++);//10
x++;
System.out.println(x);//11

System.out.println(++x);//12
++x;
System.out.println(x);//13
x–;
System.out.println(x);//12

System.out.println(–x);//11

for (int i=1; i<=5; i++) {
System.out.println(i);
}
System.out.println(“”);
for (int i=5; i>=1; i–) {
System.out.println(i);
}
}
}

Note: Arithmetic and Unary Operators return value based result, and Comparison / Relational Operators return Boolean / Logical Result (true/false)

3. Assignment Operators

int a=10, b=20;

System.out.println(a==b);//false (Comparison)
System.out.println(a=b);//20 (Assignment)

1. Assignment =

2. Add and Assign +=

3. Subtract and Assign -=

4. Multiply and Assign *=

Example:

int a=10;

System.out.println(a);//10

a=a+10;
System.out.println(a);//20

a-=10;
System.out.println(a);//10

a*=10;
System.out.println(a);//100

4). Comparison / Relational Operators

= Assignment operator
== Comparison operator

1. ==

2. !=

3. >

4. >=

5. <

6. <=

Example:

int a=10, b=20;

System.out.println(a>b);//false
System.out.println(100>200);//false
System.out.println(a>=b);//false
System.out.println(“”);
System.out.println(a<b);//true
System.out.println(a<=b);//true
System.out.println(“”);
System.out.println(a==b);//false
System.out.println(a!=b);//true

5. Logical Operators

i. Logical “Not” Operator !
ii. Logical “And” Operator &&
iii. Logical “Or” Operator ||

Example:

boolean a=true, b=false;

System.out.println(!(a&&b));//true

System.out.println((a&&b));//false

System.out.println(a||b);//true


8. Java Control Flow – Decision-Making Statements

Java Control Flow Statements
i. Decision-making statements (if, switch)
ii. Loop Statements (for, while, do while, and enhanced for)
iii. Branching statements (break, continue, and return)

Usage of Conditional/Decision-Making Statements

1. Execute a block of statements when a condition true

Syntax:

if (condition){
Statements
.
.
.
}

Example:

int a=100, b=50;

if (a>b){
System.out.println(“A is Big Number”);
}
System.out.println(“Hello”);

2. Execute a block of statements when a condition is true, otherwise execute another block of statements

Syntax:

if (condition){
.
.
}
else
{
.
.
}

Example:

int x=100, y=50;

if (a>b){
System.out.println(“X is Big Number”);
}
else
{
System.out.println(“Y is Big Number”);
}

3. Execute a block of statements when a compound condition is true

Syntax:

if ((condition1) && or || (condition2) && or || (condition3)){
.
.
}

Example:

int a=100, b=90, c=700;

if ((a>b) || (a>c)){
System.out.println(“A is Big Number”);
}

4. Execute a block of statements when a compound condition is true, otherwise, execute another block of statements.

Syntax:

if ((condition1) && or || (condition2) && or || (condition3)){
.
.
}
else {
statements
.
.
}

Example:

int a=100, b=90, c=700;

if ((a>b) && (a>c)){
System.out.println(“A is Big Number”);
}
else
{
System.out.println(“A is Not Big Number”);
}

5. Decide among several alternates (else if)

Syntax:

if (condition) {
.
.
}
else if (condition){
.
.
}
else if (condition){
.
.
}
else if (condition){
.
.
}
else {
.
.
}
———————
Problem: Initialize an Integer variable and verify the range

if the number is in between 1 and 100 then display “Number is Small Number”
if the number is in between 101 and 1000 then display “Number is Medium Number”
if the number is in between 1001 and 10000 then display “Number is Big Number”
if the Number is more than10000 then display “Number is High Number”
Otherwise, Display “Number is either Zero or Negative Value”

Solution:

int val=-100;

if ((val > 0) && (val <=100)) {
System.out.println(“Val is Small Number”);
}
else if ((val >100) && (val<=1000)) {
System.out.println(“Val is Medium Number”);
}
else if ((val >1000) && (val<=10000)) {
System.out.println(“Val is Big Number”);
}

else if (val>10000) {
System.out.println(“Val is High Number”);
}

else {
System.out.println(“Val is either Zero or Negative Number”);
}

}
}

6) Run / Execute a block of Statements/steps / Instructions when more than one condition is true (Nested if)

Syntax:

if (condition1){
if (condition2{
if (condition3) {
.
.
}
}
}

Example:
Check weather a variable (a) is having big value number among four variables, using Nested condition

int a=100, b=90, c=80, d=70;

if (a>b) {
if (a>c) {
if (a>d) {
System.out.println(“A is Big Number”);
}
}
}

7. Decide among several alternates (switch statement)

Syntax:

switch (expression) {

case1 value:
statements
.
.
break;

case2 value:
statements
.
.
break;

case3 value:
statements
.
.
break;

case4 value:
statements
.
.
break;

default:
statements
.
.
}

Example:

If the grade is A then print “Excellent”, B – “Good”, C – “OK”, Others – Invalid Grade

public static void main(String[] args) {
char grade =’D’;

switch (grade) {

case ‘A’:
System.out.println(“Excellent”);
break;

case ‘B’:
System.out.println(“Good”);
break;

case ‘C’:
System.out.println(“OK”);
break;

default:
System.out.println(“Invalid Grade”);
}


9. Java Control Flow – Loop Statements

1. for loop
2. while loop
3. do while loop
4. enhanced for loop

1. for

Description: It repeats a block of statements for a specified number of times

Syntax:

for (Initialization/Start Value; Condition/End Value; Increment or Decrement){
statements
.
.
}

Example1: Print 1 to 10 Numbers

for (int i=1; i<=10; i++) {
System.out.println(i);
}

Example2: Print 1 to 10 in reverse order except 4th and 7th Orders

for (int i=10; i>=1; i–) {
if ((i!=4)&&(i!=7)) {
System.out.println(i);
}
}

2. while loop

Description: It repeats a block of statements while the condition is true

Syntax:

Initialization;
while (condition){
statements
.
.
increment/decrement;
}

Example1: Print 1 to 10 Numbers…

int i=1;

while (i<=10){
System.out.println(i);
i++;
}

Example2: Print 1 to 10 Numbers in reverse Order except 4th and 9th numbers

int i=10;

while (i>=1){
if ((i!=4) && (i!=9)){
System.out.println(i);
}
i–-;
}

3. do while loop

Description: It repeats a block of statements while the condition is true and it executes statements at least once irrespective of the condition

Syntax:

Initialization;
do
{
Statements
.
.
Increment/Decrement;
} while (condition);

Example1:

Print 1 to 10 Numbers…

int i=1;

do
{
System.out.println(i);
i++;
} while(i<=10);

Example2:

int i=20;

do
{
System.out.println(i);
i++;
} while(i<=10);

4. Enhanced for loop

It executes all elements in an Array

Syntax:

Array Declaration;
for (declaration: Expression/Array){
Statements
.
.
}

Example1:

String [] languages={“COBOL”, “C”, “Java”, “VBScript”};

for (String lang: languages){
System.out.println(lang);

Example2:

public static void main(String[] args) {
int a=10, b=5;
int [] mathOperations = new int[3];

mathOperations[0]= a+b;
mathOperations[1]= a-b;
mathOperations[2]= a*b;

for (int operation: mathOperations){
System.out.println(operation);
}


10. Java Control Flow – Branching Statements

Branching statements are used to transfer control from one point to another in the code
Branching statements are defined by three keywords – break, continue and return

1) .break

break statement is used to stop the execution and comes out of the loop
Mostly break statements are used in switch and in loops….

Example:

for (int i=1; i<=10; i++){
System.out.println(i);
if (i==4){
break;
}
}

2. continue

continue statement is also same as break statement, the only difference is when break statement executes it comes out from the loop, whereas continue statement executes comes out from the loop temporarily.

Example:

for (int i=1; i<=10; i++){
if (i%2 != 0){
continue;
}
System.out.println(i);
}

3. return

return statement is used in User defined methods (methods with return value) and return statement must be always last statement in the method

Example:

public class ControFlow {

public int add(int a, int b){
int result=a+b;
return result;

public static void main(String[] args) {
ControFlow obj = new ControFlow();

int res= obj.add(100, 50);
System.out.println(res);//150

System.out.println(obj.add(100, 200));//300
}

}
}

//Create Object

(ClassName objectName = new ClassName();
ControFlow obj = new ControFlow();

DataType variableName = Object.Method(Values for Arguments)
int res= obj.add(100, 50);


11. String handling in Java

What is String?

The string is a sequence of characters written in double quotes

Syntax:

String stringName/VariableName = “Value”;

Example:

String val=”India”;

String may contain Alphabets, Numbers, and special characters

Examples:

String a=”INDIA”;
String b=”india”;
String c=”INdia”;
String f=”%^&”;
String g=”India123%^*”;
String l=”Selenium”;
String m=”Automated Testing using Selenium”;

String d=”100″;
int r=100;

String e=”123.34″;
double x=123.34;

String h=”A”;
char q=’A’;

String n=”true”;
boolean p=true;
——————
100
10.34
true
A

Karun

Hyderabad

A123

AP28 1234

Operations on Strings:

1) Concatenating Strings

String + String – String
String + Number – String
Number + Number – Addition

Example:

String str1= “Selenium”;
String str2 = ” Testing”;
//String concatenation using + operator
System.out.println(str1+str2);//Selenium Testing

//String concatenation using “concat” Method
System.out.println(str1.concat(str2));//Selenium Testing

System.out.println(“Selenium”+”Testing”);//SeleniumTesting
System.out.println(“Selenium”+1+1);//Selenium11
System.out.println(1+1+”Selenium”);//2Selenmium
System.out.println(1+11);//12

2) String Comparison

In Computer programming we have two types of comparisons,
1) 2-way Comparison (Logical/ true or false)
2) 3-way Comparison (Zero, Greater than Zero, Less than Zero)

Ways of String Comparison

a) String Comparison using Relational Operator (==)
It supports 2-way comparison

b) String Comparison using equals() method
It supports 2-way comparison

c) String Comparison using compareTo() method
It supports 3-way Comparison

Result criteria for 3-way comparison

if string1 == string2 then 0
if string1 > string 2 then Positive Value
if string1 < string 2 then Negative value

Comparing two number – based on their values (3>2)
Comparing two strings – based on ANSI values
3>2 – false
“Delhi” > “Mumbai” – false
“delhi” > “Mumbai” – true

ANSI character codes

A to Z (65 to 90)
a to z (97 to 122)
0- to 9 (48 to 57)

Example:

String str1 = “SELENIUM”;
String str2 = “selenium”;
String str3 = “SELENIUM”;
String str4 = “zsele”;

//String Comparison using Relational (==) Operator
System.out.println(str1 == str2);//false
System.out.println(str1 == str3);//true

//String Comparison using equals() Method
System.out.println(str1.equals(str2));//false
System.out.println(str1.equals(str3));//true

//String comparison using compareTo()
System.out.println(str1.compareTo(str2));//Negative value
System.out.println(str1.compareTo(str3));//0
System.out.println(str4.compareTo(str1));//Positive value


12. Arrays in Java

In Java, Array is an Object that holds a fixed number of values of a single data type
The length of the Array is established when the Array is created.
Array length is fixed and index starts from zero to n-1,

Declaration of Arrays

1st Method

Syntax:

dataType arrayName[]; Declare an Array/ Create an Array
arrayName = new dataType[size]; //Define size
arrayName[index] = value; //Assign a value
.
.
.

Example:
int a[];
a=new int[3];
a[0] = 10;
a[1] = 20;
a[2] = 30;

System.out.println(a[1] + a[2]);//50

2nd Method

dataType [] arrayName = new dataType [size]; //Create an Array with length
arrayName[index] = value; //Assign value
.
.

Example:
int [] a = new int [3];
a[0] =10;
a[1] =20;
a[2] =30;
System.out.println(a[1] + a[2]);//50

3rd Method

dataType [] arrayName = {value1, value2, value3, value4};//Create an Array with Initialization

Example:

int [] a= {10, 20, 30, 40};
System.out.println(a[1] +a[3]);//60

Creating different type Arrays

int [] a= {10, 20, 30, 40, 50}; //Array of Integers

char [] b= {‘A’, ‘S’, ‘1’, ‘*’};//Array of Characters

String [] c = {“UFT”, “Selenium”, “RFT”, “SilkTest”};//Array of Strings

double [] d ={1.234, 3.456, 6.45, 7.890}; // Array of decimal point values

boolean [] e = {true, true, false, true, false}; //Array of Boolean Values / Logical Values

System.out.println(a[2]);//30
System.out.println(d[3]);//7.890
System.out.println(e[0]);//true

Two-Dimensional Array

data_type [] [] array_name = new data_type[row_size][column_size];

int[][] myarray = new int[2][2];
myarray[0][0] = 1;
myarray[0][1] = myarray[1][0] = 0;
myarray[1][1] = 1;


13. Java ArrayList

Java Array is Static Data Structure and ArrayList is Dynamic Data Structure

Array versus ArrayList in Java

Java Array is Static (its size is fixed), ArrayList is Dynamic….

Java Array Example:

int [] a= new a[4];
a[0]=10;
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50; //Error

ArrayList is Dynamic and you can add or remove elements….
Note: ArrayList is predefined class that we have to import from java.util package

ArrayList Examples:

1. Create Integer type ArrayList and conduct operations

ArrayList <Integer> abc = new ArrayList <> ();

//Add elements to ArrayList
abc.add(100);
abc.add(200);
abc.add(300);

//Return & Print an Array Element
int val=abc.get(2);
System.out.println(val);//300

//Print an Array Element
System.out.println(abc.get(1));//200

//Return & Print Size of the ArrayList
int x = abc.size();
System.out.println(x);//3

//Print Size of the ArrayList
System.out.println(abc.size());//3

//Remove an element
System.out.println(abc.get(1));//200
abc.remove(1);
System.out.println(abc.get(1));//300

System.out.println(abc.size());//2
abc.add(400);
abc.add(500);
System.out.println(abc.size());//4

//Check the existence of Elements
System.out.println(abc.contains(200));//false
System.out.println(abc.contains(300));//true

//Remove all elements
System.out.println(abc.size());//4
abc.clear();
System.out.println(abc.size());//0
abc.add(123);
abc.add(234);
System.out.println(abc.size());//2

2. Create String type ArrayList

ArrayList <String> myTool = new ArrayList<> ();

myTool.add(“Selenium”);
myTool.add(“UFT”);
myTool.add(“JMeter”);

String val = myTool.get(1);
System.out.println(val);//UFT

int x= myTool.size();
System.out.println(x);//3

boolean y=myTool.contains(“JMeter”);
System.out.println(y);//true

myTool.clear();
System.out.println(myTool.size());//0

3. Create Character type ArrayList

ArrayList <Character> xyz = new ArrayList<> ();

xyz.add(‘A’);
xyz.add(‘3’);
xyz.add(‘&’);

System.out.println(xyz.size());//3

char a= xyz.get(2);
System.out.println(a);//&


14. Java User Input

The Scanner class is used to get user input, and it is found in the java.util package.

To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation.

Input Types and Method Description

1) nextLine() – Reads a String value from the user
2) nextByte() – Reads a byte value from the user
3) nextShort() – Reads a short value from the user
4) nextInt() – Reads a int value from the user
5) nextLong() – Reads a long value from the user
6) nextFloat() – Reads a float value from the user
7) nextDouble() – Reads a double value from the user
8) nextBoolean() – Reads a boolean value from the user
9) scan.next().charAt(index) – Reads a character value from the user

Example for Reading input from the User:

Scanner scan = new Scanner (System.in); //Input Stream

System.out.println(“Enter Your Name”);
String name = scan.nextLine();
System.out.println(“Your name is: “+name);

System.out.println(“Enter a City”);
String city = scan.next();
System.out.println(“Your City is: “+city);

System.out.println(“Enter Your Mobile Number”);
long mobile = scan.nextLong();
System.out.println(“Your Mobile Number is: “+mobile);

System.out.println(“Enter your ID”);
int id = scan.nextInt();
System.out.println(“Your ID is: “+id);

System.out.println(“Enter a Value”);
boolean val=scan.nextBoolean();
System.out.println(“Your value is: “+val);

System.out.println(“Enter a Number with decimal places”);
double d = scan.nextDouble();
System.out.println(“Your Number is: “+d);

System.out.println(“Enter a Charcter”);
char a = scan.next().charAt(0);
System.out.println(“Your Char is: “+a);

Read a value multiple times using for loop

for (int i=1; i<=5; i++){
System.out.println(“Enter a Character”);
char a = scan.next().charAt(0);
System.out.println(“Your Char is: “+a);
}

Write Output on the Console

int a=10, b=20;

System.out.println(100);//100
System.out.println(a);//10
System.out.println(a+b);//30
System.out.println(“”);//Blank Line
System.out.println(“Hello Java World”);//Hello Java World
System.out.println(“Addition of a, b is: “+(a+b));
System.out.println(“A value is: “+a+” B value is: “+b);


15. File handling in Java

From the User’s point of view different types of files are there, Text File/Flat File, Excel File, Word Doc, PDF, etc, but computer point of view, everything is a file – Drive, Folder, File, Database File, etc.

Java Input and Output Operations – Using Scanner and System predefined classes

File Handling in Java –

File Class – Drive, Folder, Flat File….
Reading & Writing for Flat files (BufferedReader and BufferedWriter)
Excel File – jxl.jar…*Import third-party jar files and add to Java Project and handle….

Examples:

1. Create a Folder on Desktop

File fileObject = new File (“C:/Users/admin/Desktop/Selenium”);
fileObject.mkdir();

2. Delete a Folder

File fileObject = new File (“C:/Users/admin/Desktop/Selenium”);
fileObject.delete();

3. Create a Text File

File fileObject = new File (“C:/Users/admin/Desktop/Selenium.txt”);
fileObject.createNewFile();

File fileObject = new File (“C:/Users/admin/Desktop/Selenium.xls”);
fileObject.delete();

Note: Using File Object we can create and delete all type files, but we can’t conduct internal operations

4. Read a Text File

//Open the Specified file in “Read” Mode
FileReader xyz = new FileReader (“C:\Users\admin\Desktop\selenium.txt”);

//Read Data from the opened file
BufferedReader br = new BufferedReader(xyz);
String line;

while ((line =br.readLine()) != null){
System.out.println(line);
}
br.close();
xyz.close();

5. Write Data to a Text file

//Open the Specified file in “Write” Mode
FileWriter file = new FileWriter(“C:\Users\admin\Desktop\selenium.txt”);

//Write data to the opened file
BufferedWriter bw = new BufferedWriter(file);

String data = “Welcome to Selenium World”;
bw.write(data);
bw.close();
file.close();

6. Read a Text File and write to another file

String line;

FileReader file1 = new FileReader (“C:\Users\admin\Desktop\selenium.txt”);
FileWriter file2 = new FileWriter (“C:\Users\admin\Desktop\abc.txt”);

BufferedReader br = new BufferedReader (file1);
BufferedWriter bw = new BufferedWriter (file2);

while ((line = br.readLine()) != null){
bw.write(line);
bw.newLine();
}
bw.close();

br.close();
file2.close();
file1.close();

7. Read a text file (a range of lines (3 to 8 lines)) and write to another file

//Open a specified text file in “Read” mode
FileReader file1 = new FileReader(“C:\\Users\\user\\Desktop\\August.txt”);

//Open a specified text file in “Write” mode
FileWriter file2 = new FileWriter(“C:\\Users\\user\\Desktop\\July.txt”);

//Read data from the opened file in “Read” mode
BufferedReader br = new BufferedReader(file1);

//Write data to the opened file in “Write” file
BufferedWriter bw = new BufferedWriter(file2);

String line;
int count=0;

while ((line = br.readLine()) != null) {
count = count+1;
if ((count>2) &&(count<9)) {
bw.write(line);
bw.newLine();
}
}
bw.close();

br.close();
file2.close();
file1.close();
}
}


16. Java Standard library methods/ Built-in methods

The Java Development Kit comes with many libraries which contain classes and methods for you to use. These are classes and methods that other people have written to solve common tasks.

Categories of Java Built-in methods

i. String Methods
ii. Number Methods
iii. Character Methods
iv. Array Methods
Etc…

i. String Methods in Java

The String class has a set of built-in methods that you can use on strings.

1. compareTo() Method

It Compares two strings and supports a 3-way comparison

a. Result criteria for 2-way Comparison
if string1 == string2 then true
if string1 != string2 then false

b. Result criteria for 3-way Comparison
if string1 == string2 then 0
if string1 > string2 then Positive Value
if string1 < string2 then Negative Value

Comparing two numbers – based on their values
Comparing two strings – based on ANSI charcter codes

A-Z (65 to 90)
a-z (97 to 122)
0 to 9 (48 to 57)

5 > 3 – true
“UFT” > “Selenium” – true

Example:

String str1= “selenium”;
String str2= “SELENIUM”;
String str3 = “seleniuma”;
String str4 = “selenium”;

System.out.println(str1.compareTo(str2));//Positive Values
System.out.println(str1.compareTo(str3));//Negative Value
System.out.println(str1.compareTo(str4));//0

2. equals() Method

It Compares two strings and supports 2-way comparison

Example:
String str1= “selenium”;
String str2= “SELENIUM”;
String str3 = “selenium”;
System.out.println(str1.equals(str2));//false
System.out.println(str1.equals(str3));//true

3. concat() Method

It concat two strings,

String str1= “Selenium”;
String str2= ” Testing”;

System.out.println(str1.concat(str2));//Selenium Testing
System.out.println(“Selenium”.concat(” Java”));//Selenium Java

4. charAt() Method

Returns a Character value by Index

Example:
String str1= “Selenium”;

System.out.println(str1.charAt(1));//e
System.out.println(str1.charAt(7));//m

5). equalsIngoneCase();

It compares two strings and ignores letters (Upper case or Lower case)

Example:
String str1 = “selenium”;
String str2 = “SELENIUM”;
String str3 = “UFT”;

System.out.println(str1.equalsIgnoreCase(str2));//true
System.out.println(str2.equalsIgnoreCase(str3));//false

6. toUpperCase() Method

It conversts values to Upper Case

Example:
String str1 = “selenium”;
String str2 = “SELENIUM”;
String str3 = “SELEnium”;
String str4 = “Selenium123”;

System.out.println(str1.toUpperCase()); //SELENIUM
System.out.println(str2.toUpperCase());//SELENIUM
System.out.println(str3.toUpperCase());//SELENIUM
System.out.println(str4.toUpperCase());//SELENIUM123

7. toLowerCase() Method

It converts values to lower case

Example:
String str1 = “selenium”;
String str2 = “SELENIUM”;
String str3 = “SELEnium”;
String str4 = “Selenium123”;

System.out.println(str1.toLowerCase()); //selenium
System.out.println(str2.toLowerCase());//selenium
System.out.println(str3.toLowerCase());//selenium
System.out.println(str4.toLowerCase());//selenium123

8. trim() Method

It removes spaces from both sides of a string

Example:
String str = ” Selenium “;
System.out.println(str);
System.out.println(str.trim());

9. substring() method

Returns part of a string based on index position/s

Example:
String str = “Welcome to Selenium Testing”;

System.out.println(str.substring(11));//Selenium Testing
System.out.println(str.substring(20));//Testing
System.out.println(str.substring(11, 19));//Selenium
System.out.println(str.substring(8, 10));//to

10. endsWith() Method

It checks if a string ends with a specified suffix or not? And supports 2-way comparison (true/false)

Example:
String str = “Welcome to Selenium Testing”;

System.out.println(str.endsWith(“Selenium Testing”));//true
System.out.println(str.endsWith(“Testing”));//true
System.out.println(str.endsWith(“Selenium”));//false

11. length()

Returns length of a String

String str = “Selenium Testing”;
String str2 = “Selenium”;
System.out.println(str.length());//16
System.out.println(str2.length());//8

ii. Number methods in Java

1. compareTo() method

Integer Class wraps a value of primitive data type int ia an Object

Comparing two numbers in 3-way comparison
Number1 == Number2 then 0
Number1 > Number2 then 1
Number1 < Number2 then -1

Example:

int x=7;
Integer a=x;
//Making primitive Data Type x is an Integer Object using Integer Class…

System.out.println(a.compareTo(7));//0 System.out.println(a.compareTo(5));//1
System.out.println(a.compareTo(9));//-1

2. equals() Method

It compares two numbers and supports 2-way comparison
int x=7;
Integer a=x;
System.out.println(a.equals(7));//true
System.out.println(a.equals(6));//false
System.out.println(a.equals(9));//false

3. abs() Method

It Returns absolute value

double a = 10.234;
double b = 10.789;
double c= -20.345;
int d=100;
int e=-23;

System.out.println(Math.abs(a));//10.234
System.out.println(Math.abs(b));//10.789
System.out.println(Math.abs(c));//20.345
System.out.println(Math.abs(d));//100
System.out.println(Math.abs(e));//23

4. round() Method

It rounds a value to nearest Integer

example:
double a=10.456;
double b=10.897;
double c=-10.345;

System.out.println(Math.round(a));//10
System.out.println(Math.round(b));//11
System.out.println(Math.round(c));//-10

5. min() Method

It returns minimum value between two numbers

Example:
int a=5;
int b=7;
double c=10.234;
double d = 10.789;

System.out.println(Math.min(a, b));//5
System.out.println(Math.min(c, d));//10.234
System.out.println(Math.min(11, 17));//11
System.out.println(Math.min(109.34, 103.45));//103.45

6. max() method

It returns maximum value between two numbers
int a=5;
int b=7;
double c=10.234;
double d = 10.789;
System.out.println(Math.max(a, b));//7
System.out.println(Math.max(c, d));//10.789
System.out.println(Math.max(9, 7));//9
System.out.println(Math.max(109.34, 103.45));//109.34

7. Random Number

It generates a Random Number

Example:
System.out.println(Math.random());

Usage:

String myEmail =”Suman”+Math.random()+”@gmail.com”;
System.out.println(myEmail);

iii. Array Methods in Java

1. length()

It returns the length of an Array

Example:
int [] a= {10, 20, 30, 40, 50};
System.out.println(a.length);//5

2. Copy an Array to a String

int [] a= {10, 20, 30, 40, 50};
String str= Arrays.toString(a);
System.out.println(str);

String [] a = {“UFT”, “Selenium”, “RFT”, “SilkTest”};
String str = Arrays.toString(a);
System.out.println(str);

3. Print Array using for loop

public static void main(String[] args) {
String [] a = {“UFT”, “Selenium”, “RFT”, “SilkTest”, “LoadRunner”};

for (int i=0; i<=a.length-1; i++){
System.out.println(a[i]);

4. Print Array using enhanced for loop

String [] a = {“UFT”, “Selenium”, “RFT”, “SilkTest”, “LoadRunner”};

for (String val: a){
System.out.println(val);
}

5. Check if an Array contains a certain value or not?

String [] a = {“UFT”, “Selenium”, “RFT”, “SilkTest”, “LoadRunner”};

boolean val = Arrays.asList(a).contains(“UFT”);
boolean val2 = Arrays.asList(a).contains(“Java”);
System.out.println(val);//true
System.out.println(val2);//false

iv. Character Methods

1. isLetter() Method

It checks if a value is Alphabet or not? And returns boolean result

Example:
char a=’Z’;
char b=’1′;

System.out.println(Character.isLetter(a));//true
System.out.println(Character.isLetter(b));//false
System.out.println(Character.isLetter(‘B’));//true
System.out.println(Character.isLetter(‘2’));//false
System.out.println(Character.isLetter(‘*’));//false

2). isDigit()

It checks if a Value is number or not?

Example:
char a=’Z’;
char b=’1′;

System.out.println(Character.isDigit(a));//false
System.out.println(Character.isDigit(b));//true
System.out.println(Character.isDigit(‘4’));//true
System.out.println(Character.isDigit(‘C’));//false
System.out.println(Character.isDigit(‘%’));//false

3. isLowerCase()

It checks if a value is Lower case or not? and returns a boolean result

Example:

char a=’Z’;
char b=’a’;
char c=’1′;

System.out.println(Character.isLowerCase(a));//false
System.out.println(Character.isLowerCase(b));//true
System.out.println(Character.isLowerCase(a));//false
System.out.println(Character.isLowerCase(‘s’));//true
System.out.println(Character.isLowerCase(‘Z’));//false
System.out.println(Character.isLowerCase(‘4’));//false

4). isUpperCase

It checks if a value is upper case value or not?

char a=’Z’;
char b=’a’;
char c=’1′;
System.out.println(Character.isUpperCase(a));//true
System.out.println(Character.isUpperCase(b));//false
System.out.println(Character.isUpperCase(c));//false
System.out.println(Character.isUpperCase(‘s’));//false
System.out.println(Character.isUpperCase(‘Z’));//true
System.out.println(Character.isUpperCase(‘4’));//false


17. Java User-defined methods

i. Introduction to Java Methods

What is Method?

Java Method is a block of code /set of statements/steps that are grouped together to perform a certain action.

You can pass data, known as parameters, into a method.

Methods are equivalent to Functions in Structure Programming

In Structured programming (Ex: C language) we have Functions (Built-in and User-defined Functions)

In Object-oriented programming (Ex: Java Language) we have methods (Built-in and User-defined methods)

In Python, we have both Functions and Methods

When we choose Methods?

Whenever we want to perform any operation multiple times then we choose Methods

Advantages of Methods

1. Code reusability, so that we can reduce the code size
2. Code maintenance is easy

ii. Types of Methods

Two types of Methods in Java
1. Built-in Methods / Standard Library Methods
2. User-defined methods

iii. User-defined methods

1. Method with return a Value (Perform an Operation and return a Value)
Static method (we call static methods directly or using the class name)
Non-static method (we call non-static methods by invoking an object)

2. Method without return any Value (Perform an Operation)
Static method
Non-static method

Examples:

1a. Method with return a Value -Non-static method

The syntax for creating a method:

accessModifier methodReturnType methodName(arguments){
statements
.
.
return statement
}

Syntax for calling a method:

//Create an Object
ClassName objectName = new ClassName();

dataType variableName = object.method(values….);

Note: We create methods in Interface section (outside of main method and within class), and we call methods in main program.

Example:

public class Sample {
//Non static method with return a value, no arguments
public int add() {
int a=100, b=200;
int result = a+b;
return result;
}

//Non static method with return a value, and arguments
public int add2(int a, int b) {
int result = a+b;
return result;
}
public static void main(String[] args) {
Sample obj = new Sample();

int res= obj.add();
System.out.println(res);//300

int x=res+45;
System.out.println(x);//345

System.out.println(obj.add());//300

int res= obj.add2(123, 234);
System.out.println(res);

int res2= obj.add2(123, 234);
System.out.println(res2);

int res3= obj.add2(245, 567);
System.out.println(res3);

int res4= obj.add2(890, 3456);
System.out.println(res4);
}
}

1b. Method with return a Value -Static method

Syntax for creating a Satic method

accessModifier static returnType methodName(arguments){
statements
.
.
return statement
}

Syntax for calling the method

Call directly or using class name

Example:

public class Sample {
//Create a static method with return a value, no arguments
public static int add1() {
int num1=100, num2=200;
int res= num1+num2;
return res;
}
//Create a static method with return a value, and arguments
public static int add2(int x, int y) {
int res= x+y;
return res;
}

public static void main(String[] args) {

int res= add1();
System.out.println(res);//300

int res2=add2(3456, 4568);
System.out.println(res2);
}
}

public class Class2 {

public static void main(String[] args) {
int x=Sample.add2(100, 300);
System.out.println(x);

}
}

2a. Method without return any Value -Non static method

Syntax:

accessModifier returnTypeNothing/void methodName(arguments){
statements
.
.
}

Call a non static method
//Create Object an call the non static method

ClassName objectName = new ClassName();

Call
object.method(values…);

Example:

public class Sample {
public void comparison(int num1, int num2) {
if (num1>num2) {
System.out.println(“Number 1 is Big Number”);
}
else {
System.out.println(“Number 2 is Big Number”);
}
}

public static void main(String[] args) {
Sample obj = new Sample();

obj.comparison(345, 323);//Number 1 is Big Number

obj.comparison(345, 363);//Number 2 is Big Number
}
}

2b. Method without return any Value -static method

Syntax:

accessModifier static returnsNothing void methodName (arguments){
statements
.
.
}

Call static method with returns nothing

call directly/or using class name

method(values…);

Example:

public class Sample {
public static void comparison(int num1, int num2) {
if (num1>num2) {
System.out.println(“Number 1 is Big Number”);
}
else {
System.out.println(“Number 2 is Big Number”);
}
}

public static void main(String[] args) {

comparison(123, 234);//Number 2 is Big Number

comparison(323, 234);//Number 1 is Big Number
}
}

Grand Example for Creating and Calling Java Static and Non Static Class Members

public class Class1 {
//Create Static Variables
static int x=100, y=200;
//Create Non static Variables
int a=123, b=456;

//Create a Static method with return a Value
public static int add() {
int num1=10, num2=20;
int res=num1+num2;
return res;
}
//Create a Static method without returning any Value
public static void sub() {
int num1=100, num2=200;
int res=num1-num2;
System.out.println(res);
}
//Create a Non static method with return a Value
public int multiply() {
int x=123, y=30;
int res=x*y;
return res;
}

//Create a Non static method without returning any Value
public void comparison() {
int a=100, b=90;

if (a>b) {
System.out.println(“A is Big Number”);
}
else {
System.out.println(“B is Big Number”);
}
}
public static void main(String[] args) {
Class1 obj = new Class1();

//Call Static Class Members (Variables)
System.out.println(x+y);//300

//Call Non Static Class Members (Variables)
System.out.println(obj.a+obj.b);//579

System.out.println(“”);

//Call Static Class Members (Methods)
int res= add();
System.out.println(res);//30

System.out.println(add());//30

sub();//-100
System.out.println(“”);

//Call Non static Class Members (Methods)

int res2= obj.multiply();
System.out.println(res2);

obj.comparison();//A is Big Number
}
}

Calling Java Static and Non Static Class Members from an another Class

package abcdef;

public class Class2 {

public static void main(String[] args) {
Class1 abc = new Class1();
//Call Static Class Members (Variables)
System.out.println(Class1.x+Class1.y);//300

//Call Non Static Class Members (Variables)
System.out.println(abc.a+abc.b);//579

System.out.println(“”);

//Call Static Class Members (Methods)
int res= Class1.add();
System.out.println(res);//30

System.out.println(Class1.add());//30

Class1.sub();//-100
System.out.println(“”);

//Call Non static Class Members (Methods)

int res2= abc.multiply();
System.out.println(res2);

abc.comparison();//A is Big Number
}
}


19. Java Exception Handling

An exception is an event that occurs during the execution of a program when the normal execution of the program is interrupted.

Exception handling is a mechanism to handle run-time errors

Common Scenarios where Exception may occur

1. Scenario where ArithmeticException may occur

If we divide any number by zero then ArithmeticException occurs

Ex:
int a=10/0; //ArithmeticException

2. Scenario where NumberFormat Exception occurs

The wrong format of any value

String s1=”abc”;
String s2=”123″;

int a= Integer.parseInt(s1);
int a= Integer.parseInt(s2);

System.out.println(a); //NumberFormatException

3. Scenario where NullPointerException occurs

String s=null;
System.out.println(s.length()); //NullPointerException

4. Scenario where ArrayIndexOutOfBoundsException occurs

If we assign any value in the wrong index of an Array

Ex:
int [] a= new int[3];
.
.
.
int a[7]=70;
System.out.println(a[7]); //ArrayIndexOutOfBoundsException

Program with Exception (Run-time Error):

int a=10;
int b=0;

int result=a/b;
System.out.println(result);
System.out.println(“Hello Java”);
System.out.println(“Hello Selenium”);

Use try catch block

Syntax:

try {
Statements
…………..
…………..
…………..
catch (ExceptionName name){
exception Handling code
}

Java Program with Exception handling code

int a=10;
int b=0;

try {
int result=a/b;
System.out.println(result);
}
catch (ArithmeticException e1){
System.out.println(“Divided by Zero Error”);
}
System.out.println(“Hello Java”);
System.out.println(“Hello Selenium”);

Handle multiple exceptions

int a=10;
int b=0;
int result;
int [] array1= new int[4];
try {
result=a/b;
System.out.println(result);
}
catch (ArithmeticException e1){
System.out.println(“Divided by Zero Error”);
}
System.out.println(“Hello Selenium”);
try {
array1[1]=100;
System.out.println(array1[10]);
}
catch (ArrayIndexOutOfBoundsException e2){
System.out.println(“Array Out of Bound Error”);
}
System.out.println(“Hello Java World”);


20 Java Object Oriented Programming

Project, Package, Class, Interface, Object, Method, Constructor, etc…

A class is a template, blueprint, or contract that defines what an object’s data fields and methods will be.

An object is an instance of a class. We can create many instances of a class. A Java class uses variables to define data fields and methods to define actions. Additionally,a class provides methods of a special type, known as constructors, which are invoked to create a new object.

Principles of Object Oriented Programming

1. Inheritance
2. Polymorphism
3. Abstraction
4. Encapsulation


21. Java Inheritance

It is a process of inheriting (reusing) Class members (Variables and methods) from one class to another

The Class where the class members are getting inherited is called Super Class / Parent Class / Base Class

The Class to which the class members are getting inherited is called Sub Class / Child Class / Derived Class

The Inheritance between parent Class and Child Class is achieved using the ‘extends’ keyword

Reuse class members from another class without Inheritance

Class1:

public class Sample {
//Declare Static variables
static int a=10, b=20;

//Declare Nonstatic variables
int c=30, d=40;

//Create a static method with return a value
public static int add() {
int result=a+b;
return result;
}

//Create a Non static method with return a value
public int multiply() {
int result = c*d*a;
return result;
}
public static void main(String[] args) {
//Call static class members
System.out.println(a+b);//30
int x= add();
System.out.println(x);//30

//Call Non static class members
Sample obj = new Sample();
//System.out.println(c+d);
System.out.println(obj.c+obj.d);//70
int y= obj.multiply();
System.out.println(y);//12000
}

}

Class2

public class Class2 {

public static void main(String[] args) {
//Call Static class members
System.out.println(Sample.a+Sample.b);//30
int x= Sample.add();
System.out.println(x); //30

//Call Non static class members
Sample abc = new Sample();
System.out.println(abc.c+abc.d);//70
int y= abc.multiply();
System.out.println(y);//12000

}
}

Reuse class members from another class with inheritance

public class Class2 extends Sample{

public static void main(String[] args) {
//Call Static class members
System.out.println(a+b);//30
int x= Sample.add();
System.out.println(x); //30

//Call Non static class members
Class2 abc = new Class2();
System.out.println(abc.c+abc.d);//70
int y= abc.multiply();
System.out.println(y);//12000

}
}

Types of Inheritance

i. Single Inheritance
In single inheritance, subclasses inherit the features of one superclass.

ClassB extends ClassA

ii. Multi-Level Inheritance

In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the derived class also act as the base class to other classes.

ClassB extends ClassA
ClassC extends ClassB

iii. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one sub class.

ClassB extends ClassA
ClassC extends ClassA
ClassD extends ClassA

iv. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. Since java doesn’t support multiple inheritance with classes, hybrid inheritance is also not possible with classes.

ClassB extends ClassA
ClassC extends ClassA
ClassC extends ClassD

v. Multiple Inheritance (* Java doesn’t support multiple inheritances)
ClassB extends ClassA
ClassB extends ClassZ

Example: Reusing class members from different classes

Class 1:

public class Class1 {
int a =10, b=20;
public int add(){
int result = a+b;
return result;
}
public static void main(String[] args) {

}
}

Class 2:
public class Class2 extends Class1 {
int a =100, b=200;
public int add(){
int result = a+b;
return result;
}
public static void main(String[] args) {
Class2 obj = new Class2();
System.out.println(obj.add());//300

Class1 obj2 = new Class1();
System.out.println(obj2.add());//30
}
}

Multi Level Inheritance

//Class 1:

package abcd;

public class Class1 {
int a =10, b=20;
public int add(){
int result = a+b;
return result;
}
public static void main(String[] args) {
Class1 obj = new Class1();
System.out.println(obj.add());//30
}
}

//Class 2:

public class Class2 extends Class1 {
int a =100, b=200;
public int add2(){
int result = a+b;
return result;
}
public static void main(String[] args) {
Class2 obj2 = new Class2();

System.out.println(obj2.add2());//300

System.out.println(obj2.add());//30

}
}

//Class3:

public class Class3 extends Class2{
int a =1, b=2;
public int add3(){
int result = a+b;
return result;
}
public static void main(String[] args) {
Class3 obj3 = new Class3();

System.out.println(obj3.add());//30
System.out.println(obj3.add2());//300
System.out.println(obj3.add3());//3

}
}

Two classes in same project but in two different packages

//Class 1 in Package 1:
package package1;

public class Class1 {
int a =10, b=20;
public int add(){
int result = a+b;
return result;
}
public static void main(String[] args) {
}
}

//Class 2 in Package 2:

package package2;

import package1.Class1;

public class Class2 extends Class1 {

public static void main(String[] args) {
Class2 obj = new Class2();
System.out.println(obj.add());//30

}
}

Two Classes in two different Projects

Project 1:

package package1;

public class Class1 {

int a =10, b=20;
public int add(){
int result = a+b;
return result;
}
}

Project 2:

package package2;

import package1.Class1;

public class Class2 extends Class1{

public static void main(String[] args) {
Class2 obj = new Class2();
System.out.println(obj.add());
}
}


22. Java Polymorphism

The existence of Object Behavior in many forms is called Polymorphism.

We have 2 types of Polymorphism,

1. Compile Time Polymorphism / Method Overloading
2. Run-Time Polymorphism / Method Overriding

1. Compile Time Polymorphism / Method Overloading

if two are more methods with the same name in the same class but differ in the following ways,

a. Number of Arguments
b. Type of Arguments

Example:

public class Class1 {
public void add(int a, int b){
System.out.println(a+b);
}
public void add(int a, int b, int c){
System.out.println(a+b+c);
}
public void add (double a, double b){
System.out.println(a+b);
}
public static void main(String[] args) {
Class1 obj = new Class1 ();
obj.add(10.345, 10.567);
obj.add(10, 20);
obj.add(10, 20, 30);
}
}

2. Run Time Polymorphism / Method Overriding

If two or more methods with same name that available in the parent class and child class

Example:

Class1:

package abcd;

public class Class1 {
int a =10, b=20;
public void add(){
System.out.println(a+b);
}
public static void main(String[] args) {
Class1 obj = new Class1();
obj.add();//30
}
}

Class2:

package abcd;

public class Class2 extends Class1{
int a=1, b=2;
public void add(){
System.out.println(a+b);
}
public static void main(String[] args) {
Class2 obj2 = new Class2();
obj2.add();//3
}
}


23. Java Abstraction

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Two types of Methods

1. Concrete Methods (The Methods which are having body)

Example:
public void add(){
Statements
…………..
…………..
…………..
}

2. Abstract Methods (The Methods which are not having the body)

Example:

public abstract void add();

When we go for Abstract Methods?

If we know the method name but don’t know the method functionality then we go for Abstract methods.

Java Class contains 100% concrete methods.

Abstract Class contains one or more Abstract Methods

Class 1 (having 10 Methods)

10 Methods are Concrete Methods
It is a Java Class

Class 2 (having 10 Methods)

9 Methods are Concrete Methods and One Method is Abstract Method
It is a Java Abstract Class

Class 3 (having 10 Methods)

All 10 Methods are Abstract Methods
It is a Java Abstract Class

Example for Abstract Class:

public abstract class Bikes {

public void handle(){
System.out.println(“Bikes have Handle”);
}
public void seat(){
System.out.println(“Bikes Have Seat”);
}

public abstract void engine();
public abstract void wheels();

public static void main(String[] args) {
//Bikes obj = new Bikes();
}
}

Note: We Cannot create Object in Abstract Class

Inherit Abstract Class (Class Members)

public class HeroHonda extends Bikes{
public void engine() {
System.out.println(“Bikes have Engine”);
}
public void wheels() {
System.out.println(“Bikes have Wheels”);
}
public static void main(String[] args) {

HeroHonda obj = new HeroHonda();
obj.seat();
obj.handle();
obj.engine();
obj.wheels();
}
}

public void handle(){
System.out.println(“Bikes have Handle”);
}
public void seat(){
System.out.println(“Bikes Have Seat”);
}

public abstract void engine();
public abstract void wheels();

public static void main(String[] args) {
HeroHonda obj2 = new HeroHonda();
obj2.handle();
obj2.engine();
}
}

How to call methods in Home Class/Abstract Class?

Create Object using Child Class name (We complete implementation in Child Class), then call methods.


24. Java Encapsulation

Encapsulation is a process of wrapping code and data into a single unit

Ex: capsule (Mixer of Several medicines)

Encapsulation is the technique of making the fields in a class private and providing access via public methods.

It provides control over the data

By providing getter and setter methods we can make a class read only or write only.

Example:

Class 1:

package abcd;

public class Class1 {
private String name =”Test Automation”;

public String getName(){ //Accessing Private fields vai Public method/s (Reading)
return name; //Accessing name variable value
}
public void setName(String newName){ //Accessing Private field/s and Writing another value via Public method/s
name = newName; //Writing new value to “name” variable
}
public static void main(String[] args) {
Class1 obj = new Class1();
String val = obj.getName();
System.out.println(val);//Test Automation

obj.setName(“Selenium Testing”);
val= obj.getName();
System.out.println(val);//Selenium Testing
}
}

Class 2:

public class Class2 extends Class1{
public static void main(String[] args) {
Class2 abc = new Class2();
String res = abc.getName();
System.out.println(res);//Test Automation

abc.setName(“UFT Testing”);
res = abc.getName();
System.out.println(res);//UFT Testing
}
}

Follow me on social media: