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

Java Notes

Java

Uploaded by

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

Java Notes

Java

Uploaded by

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

DSS

CLASSES

SUBJECT: JAVA

1
Class
1)Class is the collection of object
2)Class is not a real world Entity.it is just a templet or blue print.
3)class does not occupy the memory.
Syntax:

access-modifier class classname


{
-Methods
-constructors
-fields
-nested class
}

Example:
public class Demo {

public void abc() {

System.out.println("This is abc method");


}

public void pqr() {

System.out.println("This is pqr method");


}

public static void main(String[] args) {

Demo d = new demo();


d.abc();//This is abc method
d.pqr();//This is pqr method
}
}

2
Method

A set of code which perform a perticular task.

Syntax:

access-modifier returntype methodname(list of parameter)


{

Statments

}
Example:
public void pqr() {

System.out.println("This is pqr method");


}

-------------------------------------------------------------------------------------------

3
Object

-Object is an instance of class.


-Object is a real world entity.
-Object occupies memory

Syntax of Object Creation:-

Classname object= new Classname();


object.method name();
Example:
public static void main(String[] args) {

Demo d = new Demo();


d.abc();//This is abc method
d.pqr();//This is pqr method
}

4
Data types
Data type is a classification of the type of data that a variable or object can hold in a
computer programming

Ex :char, int,float,string etc.

Java support explicit declaration of the data types

Syntax :

datatype variable name

example:

int a;

or

int a=100;

In java we have two type of data type

1)Primitive data type


2)Non primitive data type

1)Primitive data type:

Integer data types

1) byte(8 bit)
ex:
byte a=10;

2) short(16 bits)
ex:
short a=87;

3) int(32 bits)
Ex
int a=10000;

4) long(64 bit)
ex:long d=1000000
5
Rational data type

5) float(32 bit)
ex
float a = 1.2;

6) double(64 bit)
ex
double b = 19.656565

Characters

7) char(16 bit)
ex
char a ='z';

Conditional

8)Boolean(1

bit)

ex
boolean
a=true;
boolean
b=false;

Non Primitive data type:


Array
String

6
Java Variables
A variable is a container which holds the value while the Java program is executed. A variable
is assigned with a data type.

Variable is a name of memory location. There are three types of variables in java: local,
instance and static.

There are two types of data types in Java: primitive and non-primitive.

Variable

A variable is the name of a reserved area allocated in memory. In other words, it is a name of
the memory location. It is a combination of "vary + able" which means its value can be
changed.

1. int data=50;//Here data is variable

Types of Variables

There are three types of variables in Java:

o local variable
o instance variable
o static variable

7
1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.

It is called an instance variable because its value is instance-specific and is not shared among
instances.

8
3) Static variable

A variable that is declared as static is called a static variable. It cannot be local. You can create
a single copy of the static variable and share it among all the instances of the class. Memory
allocation for static variables happens only once when the class is loaded in the memory.

Example to understand the types of variables in java

1. public class A
2. {
3. static int m=100;//static variable
4. void method()
5. {
6. int n=90;//local variable
7. }
8. public static void main(String args[])
9. {
10. int data=50;//instance variable
11. }
12. }//end of class

Java Variable Example: Add Two Numbers

1. public class Simple{


2. public static void main(String[] args){
3. int a=10;
4. int b=10;
5. int c=a+b;
6. System.out.println(c);
7. }
8. }

Output:

20

9
Access Modifiers in Java

There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.

There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.

10
Understanding Java Access Modifiers

Let's understand the access modifiers in Java by a simple table.

Access within within outside package by subclass outside


Modifier class package only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

1) Private

The private access modifier is accessible only within the class.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class,
so there is a compile-time error.

1. class A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}
4. }
5.
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
12. }

11
Role of Private Constructor

If you make any class constructor private, you cannot create the instance of that class from
outside the class. For example:

1. class A{
2. private A(){}//private constructor
3. void msg(){System.out.println("Hello java");}
4. }
5. public class Simple{
6. public static void main(String args[]){
7. A obj=new A();//Compile Time Error
8. }
9. }

Note: A class cannot be private or protected except nested class.

2) Default

If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It provides
more accessibility than private. But, it is more restrictive than protected, and public.

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.

1. //save by A.java
2. package pack;
3. class A{
4. void msg(){System.out.println("Hello");}
5. }

1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();//Compile Time Error

12
7. obj.msg();//Compile Time Error
8. }
9. }

In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.

3) Protected

The protected access modifier is accessible within package and outside the package but
through inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.

It provides more accessibility than the default modifer.

Example of protected access modifier

In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.

1. //save by A.java
2. package pack;
3. public class A{
4. protected void msg(){System.out.println("Hello");}
5. }

1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. obj.msg();
9. }
10. }
Output:Hello

13
4) Public

The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.

Example of public access modifier

1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }

1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }
Output:Hello

14
Non Access Modifier

static
static is the non-access modifier , use to make class variable and method as static.
If we make variable as a static this variable can use in static method, we can use it in normal
method also.
But if we make any vaiable without static , this can not accessible in static method.
If we make any class method as a static so for call this method not need to create an object ,
direct on class name we can call this method .

Example:
package nonAccessModifiers;

public class StaticDemo {

static int a=10;


int b = 20;

public static void abc() {


System.out.println(a);//10
// System.out.println(b);//compile time error

public void pqr() {


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

}
public static void main(String[] args) {
StaticDemo sd = new StaticDemo();
sd.abc();//10
StaticDemo.abc();//10
sd.pqr();//10

15
final :

Adding the final modifier to a variable declaration makes that variable unchangeable once
it's initialized.

package nonAccessModifiers;

public class FinalDemo {

public static void main(String args[]) {

int a;
int b;
final int c=0 ;
a=2;
b=4;
//c=5; compile time error
System.out.println(a);//2
System.out.println(b);//4
System.out.println(c);//0

abstract
abstract is non-access modifier which is use to create abstract classes and abstract methods.

We can make method as abstract , when we make any method as an abstract then we need to
make this class as a abstract.
abstract method do not having body, in next concrete class we extend the abstract class and in
that we can provide body to this abstract method.

16
abstract Class A
{
abstract void start(){
}
}

Class B extends A{
void start(){
System.out.println(“Hello Java”)
}
}
public static void main(String[] args) {
B obj = new B();
obj.start();
}

17
Java Operator

Operators are symbols that perform operations on variables and values. For example, + is an
operator used for addition, while * is also an operator used for multiplication.
Operators in Java can be classified into 5 types:

1. Arithmetic Operators

2. Assignment Operators

3. Relational Operators

4. Logical Operator

1. Java Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations on variables and data. For
example,

a + b;

Here, the + operator is used to add two variables a and b. Similarly, there are various other
arithmetic operators in Java.

Operation
Operator

+ Addition

- Subtraction

* Multiplication

/ Division

18
% Modulo Operation (Remainder after division)

Example 1: Arithmetic Operators

class Main {
public static void main(String[] args) {

// declare variables
int a = 12, b = 5;

// addition operator
System.out.println("a + b = " + (a + b));

// subtraction operator
System.out.println("a - b = " + (a - b));

// multiplication operator
System.out.println("a * b = " + (a * b));

// division operator
System.out.println("a / b = " + (a / b));

// modulo operator
System.out.println("a % b = " + (a % b));
}
}

Output

a + b = 17
a-b=7
a * b = 60
a/b=2
a%b=2

2. Java Assignment Operators

Assignment operators are used in Java to assign values to variables. For example,

int age;

19
age = 5;

Here, = is the assignment operator. It assigns the value on its right to the variable on its left.
That is, 5 is assigned to the variable age.
Let's see some more assignment operators available in Java.

Operator Example Equivalent to

= a = b; a = b;

+= a += b; a = a + b;

-= a -= b; a = a - b;

*= a *= b; a = a * b;

/= a /= b; a = a / b;

%= a %= b; a = a % b;

Example 2: Assignment Operators

class Main {
public static void main(String[] args) {

// create variables
int a = 4;
int var;

// assign value using =


var = a;
System.out.println("var using =: " + var);//4

// assign value using =+


var += a;
System.out.println("var using +=: " + var);//8

// assign value using =*


var *= a;
System.out.println("var using *=: " + var);//32
}

20
}

Output

var using =: 4
var using +=: 8
var using *=: 32

3. Java Relational Operators

Relational operators are used to check the relationship between two operands. For example,

// check is a is less than b


a < b;

Here, > operator is the relational operator. It checks if a is less than b or not.
It returns either true or false.
Operator Description Example

== Is Equal To 3 == 5 returns false

!= Not Equal To 3 != 5 returns true

> Greater Than 3 > 5 returns false

< Less Than 3 < 5 returns true

>= Greater Than or Equal To 3 >= 5 returns false

<= Less Than or Equal To 3 <= 5 returns true

Example 3: Relational Operators

class Main {
public static void main(String[] args) {

// create variables
int a = 7, b = 11;

// value of a and b

21
System.out.println("a is " + a + " and b is " + b);

// == operator
System.out.println(a == b); // false

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

// > operator
System.out.println(a > b); // false

// < operator
System.out.println(a < b); // true

// >= operator
System.out.println(a >= b); // false

// <= operator
System.out.println(a <= b); // true
}
}

Note: Relational operators are used in decision making and loops.

4. Java Logical Operators

Logical operators are used to check whether an expression is true or false. They are used in
decision making.
Operator Example Meaning

&& (Logical expression1 && true only if both expression1 and


AND) expression2 expression2 are true

expression1 || true if either expression1 or expression2 is


|| (Logical OR)
expression2 true

22
! (Logical NOT) !expression true if expression is false and vice versa

Example 4: Logical Operators

class Main {
public static void main(String[] args) {

// && operator
System.out.println((5 > 3) && (8 > 5)); // true
System.out.println((5 > 3) && (8 < 5)); // false

// || operator
System.out.println((5 < 3) || (8 > 5)); // true
System.out.println((5 > 3) || (8 < 5)); // true
System.out.println((5 < 3) || (8 < 5)); // false

// ! operator
System.out.println(!(5 == 3)); // true
System.out.println(!(5 > 3)); // false
}
}

Working of Program
 (5 > 3) && (8 > 5) returns true because both (5 > 3) and (8 > 5) are true.
 (5 > 3) && (8 < 5) returns false because the expression (8 < 5) is false.
 (5 < 3) || (8 > 5) returns true because the expression (8 > 5) is true.
 (5 > 3) && (8 > 5) returns true because the expression (5 > 3) is true.
 (5 > 3) && (8 > 5) returns false because both (5 < 3) and (8 < 5) are false.
 !(5 == 3) returns true because 5 == 3 is false.
 !(5 > 3) returns false because 5 > 3 is true.

23
Java If-else Statement
The Java if statement is used to test the condition. It checks boolean condition: true or false.
There are various types of if statement in Java.

o if statement
o if-else statement
o if-else-if ladder
o nested if statement

Java if Statement

The Java if statement tests the condition. It executes the if block if condition is true.

Syntax:

if(condition){
//code to be executed
}
Example:

//Java Program to demonstate the use of if statement.


public class IfExample {
public static void main(String[] args) {
//defining an 'age' variable
int age=20;
//checking the age
if(age>18){
System.out.print("Age is greater than 18");
}
}
}

Output:
Age is greater than 18

Java if-else Statement

24
The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.

Syntax:

if(condition){
//code if condition is true
}else{
//code if condition is false
}

Example:

//A Java Program to demonstrate the use of if-else statement.


//It is a program of odd and even number.
public class IfElseExample {
public static void main(String[] args) {
//defining a variable
int number=13;
//Check if the number is divisible by 2 or not
if(number%2==0){
System.out.println("even number");
}else{
System.out.println("odd number");
}
}
}

Output:

odd number

25
Java if-else-if ladder Statement

The if-else-if ladder statement executes one condition from multiple statements.

Syntax:

if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}

Example:

//Java Program to demonstrate the use of If else-if ladder.


//It is a program of grading system for fail, D grade, C grade, B grade, A grade and A+.
public class IfElseIfExample {
public static void main(String[] args) {
int marks=65;

if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");

26
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}

Output:

C grade

Program to check POSITIVE, NEGATIVE or ZERO:

public class PositiveNegativeExample {


public static void main(String[] args) {
int number=-13;
if(number>0){
System.out.println("POSITIVE");
}else if(number<0){
System.out.println("NEGATIVE");
}else{
System.out.println("ZERO");
}
}
}

Output:

NEGATIVE

Program to check POSITIVE, NEGATIVE or ZERO:


Accessing the value from user :
package Statment;

import java.util.Scanner;

27
public class IfDemo {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);


System.out.println("Enter the Number::");
int number = sc.nextInt();

//int a=60;
// int number=0;
if(number>0){
System.out.println("POSITIVE");
}else if(number<0){
System.out.println("NEGATIVE");
}else{
System.out.println("ZERO");
}

}
}

Java Nested if statement

The nested if statement represents the if block within another if block. Here, the inner if block
condition executes only when outer if block condition is true.

Syntax:

if(condition){
//code to be executed
if(condition){
//code to be executed
}
}

Example:1

//Java Program to demonstrate the use of Nested If Statement.


public class JavaNestedIfExample {
public static void main(String[] args) {
//Creating two variables for age and weight

28
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
}
}
}

Output:

You are eligible to donate blood

Example 2:

//Java Program to demonstrate the use of Nested If Statement.


public class JavaNestedIfExample2 {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=25;
int weight=48;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
} else{
System.out.println("You are not eligible to donate blood");
}
} else{
System.out.println("Age must be greater than 18");
}
}

29
Output:

You are not eligible to donate blood

Example 3:
package Statment;

public class JavaNestedIfExample {

public static void main(String[] args) {


//Creating two variables for age and weight
int age=17;
int weight=44;
//applying condition on age and weight
if(age>=18 && age<=50){
if(weight>=45 && weight<=90){
System.out.println("You are eligible to donate blood");
}
else {
System.out.println("You are not eligible to donate blood due to less
weight");
}
}
else {
System.out.println("You are not eligible to donate blood due to age limit");
}

30
Java Switch-Case Statement with Example
We all use switches regularly in our lives. Yes, I am talking about electrical switches we use
for our lights and fans.

As you see from the below picture, each switch is assigned to operate for particular electrical
equipment.

For example, in the picture, the first switch is for a fan, next for light and so on.

Thus, we can see that each switch can activate/deactivate only 1 item.

What is Switch Case in Java?

Similarly, switch in Java is a type of conditional statement that activates only the matching
condition out of the given input.

Let us consider the example of a program where the user gives input as a numeric value (only
1 digit in this example), and the output should be the number of words.

The integer variable iSwitch, is the input for the switch to work.

The various available options (read cases) are then written as case <value>alongwith a colon
“:”

This will then have the statement to be executed if the case and the input to the switch match.

31
Java Switch Example

class SwitchBoard{
public static void main(String args[]){
int iSwitch=4;
switch(iSwitch){
case 0:
System.out.println("ZERO");
break;

case 1:
System.out.println("ONE");
break;

case 2:
System.out.println("TWO");
break;

case 3:
System.out.println("THREE");
break;

case 4:
System.out.println("FOUR");
break;

default:
System.out.println("Not in the list");
break;
}
}
}

Output:

FOUR

Switch case same above example for user input

package JavaTheory;

32
import java.util.Scanner;

public class SwitchCaseUserInputDemo {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.println("Enter the number::");
int iSwitch = sc.nextInt();

switch(iSwitch){
case 0:
System.out.println("ZERO");
break;

case 1:
System.out.println("ONE");
break;

case 2:
System.out.println("TWO");
break;

case 3:
System.out.println("THREE");
break;

case 4:
System.out.println("FOUR");
break;

default:
System.out.println("Not in the list");
break;

}
}

Output:
Enter the number::
2
TWO

33
Loops in Java

1)for loop
2)while loop
3)do while loop
4)Enhanced for loop
-------------------------------------------
1)for loop
Syntax:

for(datatype variable=value(initialization);condition;increment/decrement) {

statment;

}
Example:
package javaPrograms;

public class ForLoopDemo {

public static void main(String[] args) {

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

}
--------------------------------------------------------

34
2)while loop
Syntax:

datatype variable= value;


while(condition) {
statment;
increment/decrement
}
Example:
public class WhileLoopDemo {

public static void main(String[] args) {

//print 1 -10 numbers

int i= 10;
while(i>=0) {
System.out.println(i);
i--;
}
}

}
-----------------------------------------------------

35
3)do while loop
Syntax:

initialization
do {
statment
inctrement/decrement;
}while(condition);

Example:
package javaPrograms;

public class DoWhileDemo {

public static void main(String[] args) {

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

}
----------------------------------------------------------------------------------

36
4)Enhanced for loop:-
Syntax:
for(datatype var:var){
Statment;
}

Example:
package javaPrograms;

public class EnhancedForLoopDemo {

public static void main(String[] args) {

String language[]= {"C","JAVA","C++"};

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

37
Constructor

1)class name same as method name


2)No return type
3)Access modifier:-public,protected,default,private
4)it exicute automatically when we create object
-----------------------------------------------
package javaPrograms;

public class ConstructorDemo {

public ConstructorDemo() {
System.out.println("This is constructor demo");
}

public static void main(String[] args) {

ConstructorDemo cd = new ConstructorDemo();

}
-------------------------------------------------------------------

38
Types of constructor:
1)Default constructor
2)User defined constructor
a)No argument constructor
b)Parameterized constructor

1)Default constructor:

package javaPrograms;

public class ConstructorDemo {

public static void main(String[] args) {

ConstructorDemo cd = new ConstructorDemo();

}
-----------------------------------------------------------------------------------
2)User defined constructor
a)No argument constructor
b)Parameterized constructor

a)No argument constructor: not provide the parameter

public class ConstructorDemo {

39
public ConstructorDemo() {
System.out.println("This is constructor demo");
}

public static void main(String[] args) {

ConstructorDemo cd = new ConstructorDemo();

b)Parameterized constructor:-provide the parameter

public class ConstructorDemo {

public ConstructorDemo(int a ) {

System.out.println("This is constructor demo");

40
public static void main(String[] args) {

ConstructorDemo cd = new ConstructorDemo(6);

41
Inheritance:

1)superclass----->subclasses

Types of Inheritance:
1)Single Inheritance
2)Multilevel inheritance
3)Hierarchical Inheritance
4)Multiple Inheritance
5)Hybrid Inheritance

1)Single Inheritance

subclass access the properties from super class .

Class 1
package Inheritance;

public class Test1 {

public void test1Demo() {


System.out.println("I am test1 demo");
}
}
---------------------------------------------
Class 2
package Inheritance;

public class Test2 extends Test1 {

42
public static void main(String[] args) {

Test2 t2 = new Test2();


t2.test1Demo();
}

}
-----------------------------------------------------------

2)Multilevel Inheritance

As per dia Class C is subclass of B and B is Subclass of A


C is access the properties from B and B is Access the properties from A

3)Hierarchical Inheritance
The multiple subclasses access the properties from one superclass

4)Multiple Inheritance
In multiple inheritance when one subclass try to access the properties from multiple super
classes
so the compiler is confused from which superclass he need to access the properties.so here
diamond ambiguity problem is occuerd. so the Multiple inheritance is not possible in java.

5)Hybrid Inheritance
Hybrid Inheritance is the combination of Hierarchical and multiple inheritance .this is not
supported
in java

43
Interface:

Interface are similar to abstract class but having all the method of abstract name.

Interfaces are the blueprint of the class

It is use to achieve abstraction

It support multiple inheritance

Variable: public static final int a =0;


(if we are declaring variable in interface that variable should be public static final ).

Methods:
public abstract void show();
(The method declared in interfaces that should be public abstract void methodname, we not
providing the body of that method).

Example:

Interface 1:
Program:
package InterfaceDemo;

public interface I1 {

public static final int a = 0;


public abstract void show();

}
----------------

44
Interface 2:
Program:
package InterfaceDemo;

public interface I2 {

public abstract void display();


}
----------------------------
Class(in class we implements the interfaces it means need to provide the body of
unimplemented methods which methods
are declared in interfaces)
Program:
package InterfaceDemo;

public class Test1 implements I1,I2 {

@Override
public void display() {
System.out.println("1");
}

@Override
public void show() {
System.out.println("2");
}

public static void main(String[] args) {

Test1 t1 =new Test1();


t1.show();

45
t1.display();

}
=====
Output
2
1

46
Abstraction

An abstraction means showing only essential features of application and hiding the details.

i.e focusing on main things.

If we are taking abstract method then we should make this class as abstract class.

In next class we extends the abstract class then we can access the abstract methods in this
class and can
provide body to this method.

---------------------------------
First class:(abstract class/method should be abstract)
Example:
package Abstraction;

public abstract class Vehicle {


int no_of_tyres;
abstract void start();

}
------
In Second class we just extends the abstract class and adding unimplemented
method of abstract class or providing body to them.
Example:
package Abstraction;

public class Car extends Vehicle {

47
@Override
void start() {
System.out.println("Start with Key");
}

}
-------------
next class we just extends the abstract class and adding unimplemented
method of abstract class or providing body to them.
and also taking main method and in that call the method of respective classes by creating
object of that particular class.
Example:
package Abstraction;

public class Scooter extends Vehicle{

@Override
void start() {
System.out.println("Start with Kick");

public static void main(String[] args) {

Scooter sc = new Scooter();


sc.start();

Car cr = new Car();


cr.start();
}
}

48
Polymorphism

1)Poly means "many " and morphism means "form"


2)it is the ability to take more than one form.
3)i.e one name many forms
e.g:Water-solid ,liquid ,Gas

Types of Polymorphism
1)compile time polymorphism
--static polymorphism
--method overloading

2)Run time polymorphism


--Dynamic polymorphism
--method overridding

-----------------------------------------------------------
1)Method Overloading
-Multiple methods with same name but different parameter
-same class
-parameters should be different
(no of parameter,type of parameter)
package Polymorphism;

public class Test {

public void show() {


System.out.println("1");

49
}
public void show(int a) {
System.out.println("2");
}
public void show(char a) {
System.out.println("3");
}
public void show(int a ,char b) {
System.out.println("4");
}

public static void main(String[] args) {

Test t = new Test();


t.show();//1
t.show(5);//2
t.show('p');//3
t.show(6, 'b');//4
}

}
------------------------------------------------------------------
2)Method Overriding
-one class having one method and next class having method which is same as first class,
method name
are same as well as parameter are also same it is called as method overridding.
-different class
-parameters should be same
(no of parameter, type of parameter)
-Need to use the concept Inheritance

50
Program1:
package Polymorphism;

public class OverriddingDemo1 {

public void show() {


System.out.println("1");
}

Program2:
package Polymorphism;

public class OverriddingDemo2 extends OverriddingDemo1 {

public void show() {


System.out.println("2");
}

public static void main(String[] args) {

OverriddingDemo1 demo1 = new OverriddingDemo1();


demo1.show();//1

OverriddingDemo2 demo2 = new OverriddingDemo2();


demo2.show();//2
}}

51
String Handling in Java

String is a sequence of character written in double quote

String abc = "Samarth";

String pqr = "123san@";


----------------------------------------------------
Program:

package StringHandling;

public class DemoString {

public static void main(String[] args) {

String mytool = "Selenium";


String mytools[] = {"UFT","Selenium","RFT"};

System.out.println(mytool);//Selenium

for(String tools:mytools) {
System.out.println(tools);
}
}

52
Concatenation of Strings:

1)String +String = Concatenation


2)String +Number = Concatenation
3)Number+String = Concatenation
----------------------------------------------------------

1)String +String = Concatenation

Ex:
String str1 = "Selenium";
String str2 = "Testing";

System.out.println(str1+str2);//SeleniumTesting
----------------------------------------------------------------------------------
2)String +Number = Concatination

Ex:
System.out.println("Selenium"+1+1);//Selenium11
-----------------------------------------------------------------------------------
3)Number+String = Concatination

Ex:
System.out.println(1+1+"Selenium");//2Selenium
------------------------------------------------------------------------------

53
String Comparison:

1)Using comparison operator


2)Using equals() method
3)Using compareTo() method
-------------------------------------------
1)Using comparison operator:

Ex:
String str1 = "SELENIUM";
String str2 = "Selenium";
String str3 = "SELENIUM";
String str4 = "ZSelenium";
System.out.println(str1==str3);//true
System.out.println(str1==str2);//false
System.out.println(str1==str4);//false
System.out.println(str1!=str4);//true
------------------------------------------------------------------------------------
2)Using equals() method

Ex:
String str1 = "SELENIUM";
String str2 = "Selenium";
String str3 = "SELENIUM";
String str4 = "ZSelenium";
System.out.println(str1.equals(str2));//false
System.out.println(str1.equals(str3));//true
-------------------------------------------------------------------------------------

54
3)Using compareTo() method

Ex:
String str1 = "SELENIUM";
String str2 = "Selenium";
String str3 = "SELENIUM";
String str4 = "ZSelenium";
System.out.println(str1.compareTo(str2));//negative
System.out.println(str2.compareTo(str1));//positive
System.out.println(str1.compareTo(str3));//0
-------------------------------------------------------------------------------------
concats()

Join two strings

Program:
package StringHandling;

public class StringConcatination {

public static void main(String[] args) {

String str1 = "Selenium";


String str2 = "Testing";

System.out.println(str1.concat(str2));//SeleniumTesting

55
-----------------------------------------------------------------------------------
charAt()

Return a character by position

Program:
package StringHandling;

public class StringMethodcharAt {

public static void main(String[] args) {

String str1 = "Selenium";

System.out.println(str1.charAt(3));//e

}
------------------------------------------------------------------------------
equalIgnoreCase()

In This method check two strings should be same then result will true otherwise
result will be false and ignoring there case .

Program:
package StringHandling;

56
public class StringMethod {

public static void main(String[] args) {

String str1 = "Selenium";


String str2 = "SELENIUM";

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

}
------------------------------------------------------------------------------------
toUppercase()

This method is used for convert string from lowercase to uppercase.

Program:
package StringHandling;

public class StringMethod {

public static void main(String[] args) {

String str1 = "selenium";

System.out.println(str1.toUpperCase());//SELENIUM

57
}

}
------------------------------------------------------------------------------------------
toLowercase()

This method is used for convert string from uppercase to lowercase .

Program:
package StringHandling;

public class StringMethod {

public static void main(String[] args) {

String str1 = "SELENIUM";

System.out.println(str1.toLowerCase());//selenium

}
----------------------------------------------------------------------------------------

58
trim()

This method used for reduce the space available before the string.

Program:
package StringHandling;

public class StringMethod {

public static void main(String[] args) {

String str1 = " Selenium ";

System.out.println(str1.trim());//Selenium

}
--------------------------------------------------------------------------------------
subString()

This method is used to select the string from the index provided in the subString parameter.

Program:
package StringHandling;

public class StringMethod {

59
public static void main(String[] args) {

String str1 = "Welcome to the Selenium Testing";

System.out.println(str1.substring(2));//lcome to the Selenium Testing

}
------------------------------------------------------------------------------------------------------
endsWith()

This method is used to check the given string is ended with selected parameter value.

Program:
package StringHandling;

public class StringMethod {

public static void main(String[] args) {

String str1 = "Welcome to the Selenium Testing";

System.out.println(str1.endsWith(" to the Selenium Testing"));//true

60
}

}
-------------------------------------------------------------------------------
length()

This method is used to return the length of given String.

Program:
package StringHandling;

public class StringMethod {

public static void main(String[] args) {

String str1 = "Selenium";


System.out.println(str1.length());//8

}
--------------------------------------------------------------------------------------------

61
Arrays

1)Java arrays is an object that holds a fixed number of values of a single data

Or

Array is collection of similar type of data

2)The length of an Array is established when the array is created.

------------------------------------------------------------------------------
Declaration of Array:

int abc[]; creating array


abc =new int[4];

int abc [] = new int[4];


abc[0]=10;
abc[1]=20;
abc[2]=30;
abc[3]=40;

Program:
package Array;

public class ArrayDemo {

public static void main(String[] args) {

62
int abc[]=new int[4];
abc[0]=10;
abc[1]=20;
abc[2]=30;
abc[3]=40;

System.out.println(abc[0]);//10
System.out.println(abc[1]);//20
System.out.println(abc[2]);//30
System.out.println(abc[3]);//40
System.out.println(abc[0]+abc[1]);
System.out.println(abc[0]-abc[1]);
System.out.println(abc[0]*abc[1]);
System.out.println(abc[0]/abc[1]);
System.out.println(abc[0]>abc[1]);
System.out.println(abc[0]<abc[1]);
System.out.println(abc[0]==abc[1]);
System.out.println(abc[0]!=abc[1]);

}
}
-------------------------------------------------------------------------------------------

int abc []={10,20,30,40,50};

Program:

package Array;

63
public class ArrayDemo1 {

public static void main(String[] args) {

int abc[]= {10,20,30,40};

System.out.println(abc[0]);//10
System.out.println(abc[1]);//20
System.out.println(abc[2]);//30
System.out.println(abc[3]);//40
System.out.println(abc[0]+abc[1]);
System.out.println(abc[0]-abc[1]);
System.out.println(abc[0]*abc[1]);
System.out.println(abc[0]/abc[1]);
System.out.println(abc[0]>abc[1]);
System.out.println(abc[0]<abc[1]);
System.out.println(abc[0]==abc[1]);
System.out.println(abc[0]!=abc[1]);

}
}
----------------------------------------------------------------------------------
How many types of array we can declare

package Array;

64
public class ArrayDemo2{

public static void main(String[] args) {

char abc[]= {'A','B','C'};


int xyz[]= {10,20,30,40};
String a[]= {"Selenium","UFT","JAVA","LoadRunner"};
boolean b[]= {true,false,true,false};

System.out.println(abc[0]);//A
System.out.println(abc[1]);//B
System.out.println(abc[2]);//C
System.out.println(xyz[1]);//20
System.out.println(a[1]);//UFT
System.out.println(b[3]);//false

}
}
--------------------------------------------------------------------
Array Operations:

Printing array using Enhanced for loop


Program:
package Java_Programs;

public class ArrayOperation {

public static void main(String[] args) {

int array1[]={1,2,3,4,5};

65
int array2[]=array1;

System.out.println(array2.length);

for(int abc:array2) {
System.out.println(abc);
}
}

}
--------------------------------------------------------------
Printing array using Normal for loop

Program:
package Java_Programs;

public class ArrayOperation1 {

public static void main(String[] args) {

int array1[]={1,2,3,4,5};
int array2[]=array1;

System.out.println(array2.length);

for(int i=0;i<array2.length;i++) {
System.out.println(array2[i]);
}
}

66
}
----------------------------------------------------------------

Two types of Arrays in Java

1)Single Dimensional Array


2)Multi Dimensional Array

----------------------------------------------------------
1)Single Dimensional Array

int array1[]={1,2,3,4,5};
System.out.println(array1[1]);
---------------------------------------------------------
2)Multi Dimensional Array

Example1:
package Array;

public class MultiDimensionalArray {

public static void main(String[] args) {

int abc[][] = new int[3][2];


abc[0][0] =10;
abc[0][1] =20;
abc[1][0] =30;
abc[1][1] =40;
abc[2][0] =50;
abc[2][1] =60;

67
System.out.println(abc[0][0]);//10
System.out.println(abc[0][1]);//20
System.out.println(abc[1][0]);//30
System.out.println(abc[1][1]);//40
System.out.println(abc[2][0]);//50
System.out.println(abc[2][1]);//60

}
------------------------

Example 2:

package Array;

public class MultiDimensionalArray {

public static void main(String[] args) {

int abc[][] = {{10,20},{30,40},{50,60}};

System.out.println(abc[0][0]);//10
System.out.println(abc[0][1]);//20
System.out.println(abc[1][0]);//30

68
System.out.println(abc[1][1]);//40
System.out.println(abc[2][0]);//50
System.out.println(abc[2][1]);//60

---------------------------------------------------------------------------

Advantages and Disadvantages of Array

Advantages:

1)Using arrays we can optimize the code,data can be retrived easily


2)We can get retrived data using index position
----------------------------------------------------------------------------
Disadvantages:

1)We can store fixed number of elements only.


2)we doesn't change its size during exicution.
3)We can add just similar type of data.
--------------------------------------------------------------------------

69
Print Array

Print Single dimensional Array

Program:
package Java_Programs;

public class ArrayOperation {

public static void main(String[] args) {

int array1[]={1,2,3,4,5};
int array2[]=array1;

System.out.println(array2.length);

for(int i=0;i<array2.length;i++) {
System.out.println(array2[i]);
}
}

}
-----------------------------------------------------------------------

Print Multi-dimensional Array

Program:
First way:

package Java_Programs;

70
public class ArrayOperation {

public static void main(String[] args) {

int array1[][]={{1,7,8,5},{5,8,9,4}};

System.out.println(array1[0][0]);//1
System.out.println(array1[0][1]);//7
System.out.println(array1[0][2]);//8
System.out.println(array1[0][3]);//5
System.out.println(array1[1][0]);//5
System.out.println(array1[1][1]);//8
System.out.println(array1[1][2]);//9
System.out.println(array1[1][3]);//4

}
}

------------------
Second way

Program:
package Java_Programs;

public class ArrayOperation {

71
public static void main(String[] args) {

int array1[][]={{1,7,8,5},{5,8,9,4}};

for(int i=0;i<=3;i++) {
for(int j=0;j<=3;j++) {
System.out.println(array1[i][j]);
}
}

}
}

--------------------------------------------------------------------
Copy One Dimensional Array

Program:
package Java_Programs;

public class ArrayOperation {

public static void main(String[] args) {

int array1[]={1,2,3,4,5};
int array2[]=array1;

System.out.println(array2.length);

72
for(int i=0;i<array2.length;i++) {
System.out.println(array2[i]);
}
}

}
--------------------------------------------------------------------

Copy Two Dimensional Array

Program:

package Java_Programs;

public class ArrayOperation {

public static void main(String[] args) {

int array1[][]={{1,7,8,5},{5,8,9,4}};
int array2[][]=array1;

for(int i=0;i<=3;i++) {
for(int j=0;j<=3;j++) {
System.out.println(array2[i][j]);
}
}

}}

73
Java Array List

Java Array is Static data structure , and ArrayList is Dynamic Data Structure
Array vs ArrayList

Array is static (its size is fixed)


int a[]=new int [4];
a[0]=10;
a[1]=20;
a[2]=30;
a[3]=40;
a[7]=70;//Run-time error.

ArrayList is Dynamic and we can add or remove elements dynamically.

ArrayList is predefined class that we have to import from java.utils package


----------------------------------------------------------------------------------------------
Examples:

1.Create an Integer type ArrayList and conduct some operations


Syntax:
ArrayList<type of ArrayList> ArrayList Name =new ArrayList <>();

ArrayList - Predefined class

type -Integer/Character/Double/String etc .

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

74
//Add element to ArrayList

a.add(100);
a.add(200);
a.add(300);

//Return/print an Array Element

int val = a.get(1);


System.out.println(val);//200

System.out.println(a.get(2));//300

//Return /Print size of the ArrayList

int size = a.size();


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

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

//Remove an Element

System.out.println(a.get(1));//200
System.out.println(a.get(2));//300
a.remove(1);
System.out.println(a.get(1));//300
//System.out.println(a.get(2));//Run time error "Array out of bound"

//Check the existance of elements

75
System.out.println(a.contains(100));true
System.out.println(a.contains(400));false

boolean status = a.contains(300);


System.out.println(status);//true

System.out.println(a.size());//2

a.add(400);
a.add(500);

System.out.println(a.size());//4

//Remove all Elements

a.clear();

System.out.println(a.size);//0
--------------------------------------------

2.Create String type ArrayList and perform operation

Syntax:
ArrayList<type of ArrayList> ArrayList Name =new ArrayList <>();

Example:

----------------------------------------------------------------------

76
3.Create Character type ArrayList and perform some operation

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

xyz.add('A');
xyz.add('b');
xyz.add('r');
xyz.add('t');

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

char val = xyz.get(2);


System.out.println(val);//r

System.out.println(xyz.get(2));//r

77
Java StringBuffer class

Java StringBuffer class is used to create mutable (modifiable) string.

Important Constructors of StringBuffer class


Constructor Description

StringBuffer() creates an empty string buffer with the initial capacity of 16.

StringBuffer(String str) creates a string buffer with the specified string.

StringBuffer(int capacity) creates an empty string buffer with the specified capacity as length.

What is mutable string

A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.

Important methods of StringBuffer class

1) StringBuffer append() method

The append() method concatenates the given argument with this string.

class StringBufferExample{

public static void main(String args[]){

StringBuffer sb=new StringBuffer("Hello ");


sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}

2) StringBuffer insert() method

The insert() method inserts the given string with this string at the given position.

78
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}

3) StringBuffer replace() method

The replace() method replaces the given string from the specified beginIndex and endIndex.

class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"ABC");
System.out.println(sb);//prints HABClo
}
}

4) StringBuffer delete() method

The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex.

class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
5) StringBuffer reverse() method

The reverse() method of StringBuilder class reverses the current string.

class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");

79
sb.reverse();
System.out.println(sb);//prints olleH
}
}

6) StringBuffer capacity() method

The capacity() method of StringBuffer class returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the number of character increases from its current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity
is 16, it will be (16*2)+2=34.

class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}

80
Java StringBuilder class:

Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder
class is same as StringBuffer class

Important Constructors of StringBuilder class


Constructor Description

StringBuilder() creates an empty string Builder with the initial capacity of 16.

StringBuilder(String str) creates a string Builder with the specified string.

StringBuilder(int length) creates an empty string Builder with the specified capacity as length.

Important methods of StringBuilder class

1) StringBuilder append() method

The StringBuilder append() method concatenates the given argument with this string.

class StringBuilderExample{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}

2) StringBuilder insert() method

The StringBuilder insert() method inserts the given string with this string at the given position.

81
class StringBuilderExample2{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
3) StringBuilder replace() method

The StringBuilder replace() method replaces the given string from the specified beginIndex
and endIndex.

class StringBuilderExample3{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}

4) StringBuilder delete() method

The delete() method of StringBuilder class deletes the string from the specified beginIndex to
endIndex.

class StringBuilderExample4{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
5) StringBuilder reverse() method

The reverse() method of StringBuilder class reverses the current string.

82
class StringBuilderExample5{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
6) StringBuilder capacity() method

The capacity() method of StringBuilder class returns the current capacity of the Builder. The
default capacity of the Builder is 16. If the number of character increases from its current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity
is 16, it will be (16*2)+2=34.

class StringBuilderExample6{
public static void main(String args[]){
StringBuilder sb=new StringBuilder();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}

Difference between String and StringBuffer

There are many differences between String and StringBuffer. A list of differences between
String and StringBuffer are given below:

83
No. String StringBuffer

1) String class is immutable. StringBuffer class is mutable.

2) String is slow and consumes more memory when StringBuffer is fast and consumes
you concat too many strings because every time it less memory when you cancat
creates new instance. strings.

Difference between StringBuffer and StringBuilder

Java provides three classes to represent a sequence of characters: String, StringBuffer, and
StringBuilder. The String class is an immutable class whereas StringBuffer and StringBuilder
classes are mutable. There are many differences between StringBuffer and StringBuilder. The
StringBuilder class is introduced since JDK 1.5.

A list of differences between StringBuffer and StringBuilder are given below:

No. StringBuffer StringBuilder

1) StringBuffer is synchronized i.e. thread safe. StringBuilder is non-synchronized i.e. not


It means two threads can't call the methods thread safe. It means two threads can call the
of StringBuffer simultaneously. methods of StringBuilder simultaneously.

2) StringBuffer is less efficient than StringBuilder is more efficient than


StringBuilder. StringBuffer.

StringBuffer Example

//Java Program to demonstrate the use of StringBuffer class.


public class BufferTest{
public static void main(String[] args){

84
StringBuffer buffer=new StringBuffer("hello");
buffer.append("java");
System.out.println(buffer);
}
}

hellojava

StringBuilder Example

//Java Program to demonstrate the use of StringBuilder class.


public class BuilderTest{
public static void main(String[] args){
StringBuilder builder=new StringBuilder("hello");
builder.append("java");
System.out.println(builder);
}
}
hellojava

85
Java Data Type Conversion

To conduct operation on data/for processing the data, some times


Data type conversion is required

Example:
//Integer to Byte
public class TypeCasting {

public static void main(String[] args) {


int a =10;
Byte b=20;
System.out.println(a+b);//30
int c = a+b;
System.out.println(c);//30
byte d= (byte) (a+b);

System.out.println(d);//30
}

}
Example:
// Byte to Integer
byte a=10;
int b=a;
System.out.println(b);//10
int a=10;
byte b=(byte) a;
System.out.println(b);//10
//long to long
long a=1000000;
long b= a;
System.out.println(b);//10

//long to int
long a=100;
int b= (int)a;
System.out.println(b);//100

86
//String to int
String a="10";
String b= "20";
System.out.println(a+b);//1020
int num1 =Integer.parseInt(a);
int num2 =Integer.parseInt(b);
System.out.println(num1+num2);//30

Note:We can convert numbers only from String type to Integer,


But we can’t convert Alphabet to Integer
String a="abcd";
int num= Integer.parseInt(a);
System.out.println(num);

//String to double
String a="10.234";
double val= Double.parseDouble(a);
System.out.println(val);

//Integer to double
int a=10;
double b= a;
System.out.println(b);

//double to Integer
double a=17.34;
int b= (int) a;
System.out.println(b);//17

87

You might also like