0% found this document useful (0 votes)
131 views96 pages

Basics of Java

Java is a general-purpose, object-oriented programming language developed by James Gosling at Sun Microsystems in 1991. It is formally known as OAK but was renamed to Java in 1995 when Sun Microsystems took ownership. Java applications can be standalone, enterprise, web-based, or mobile. The Java Development Kit includes tools for developing Java programs, while the Java Runtime Environment executes Java programs.

Uploaded by

Harshal Bordia
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
131 views96 pages

Basics of Java

Java is a general-purpose, object-oriented programming language developed by James Gosling at Sun Microsystems in 1991. It is formally known as OAK but was renamed to Java in 1995 when Sun Microsystems took ownership. Java applications can be standalone, enterprise, web-based, or mobile. The Java Development Kit includes tools for developing Java programs, while the Java Runtime Environment executes Java programs.

Uploaded by

Harshal Bordia
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 96

What is Java?

Java is a high-level, general-purpose, object-oriented, and secure programming language


developed by James Gosling at Sun Microsystems, Inc. in 1991. It is formally known as OAK. In
1995, Sun Microsystem changed the name to Java. In 2009, Sun Microsystem takeover by Oracle
Corporation.
Object Oriented Programming:
Object Oriented Programming is nothing but a programming methodology, it was simplify any
complex task using inheritance, encapsulation, message passing, polymorphism, etc (OOPs
Concepts)
University S/W
1. Students
2. Faculties
3. CSE, EC,IT etc
4. T&P
5. Library
6. Sport
7. Account
8. Admin
9. 100 departments

void student()
{
……..
…….
//500 line of code
}

class student
{
void fee()
{
}
void lib()
{
}
void cse()
{
}
10 functions

Editions of Java
Each edition of Java has different capabilities. There are three editions of Java:
Java Standard Editions (JSE): It is used to create programs for a desktop computer.
Java Enterprise Edition (JEE): It is used to create large programs that run on the server and
manages heavy traffic and complex transactions.
Java Micro Edition (JME): It is used to develop applications for small devices such as set-top
boxes, phone, and appliances.
Types of Java Applications
There are four types of Java applications that can be created using Java programming:
Standalone Applications: Java standalone applications uses GUI components such as AWT,
Swing, and JavaFX. These components contain buttons, list, menu, scroll panel, etc. It is also
known as desktop alienations.
Enterprise Applications: An application which is distributed in nature is called enterprise
applications.
Web Applications: An applications that run on the server is called web applications. We use JSP,
Servlet, Spring, and Hibernate technologies for creating web applications.
Mobile Applications: Java ME is a cross-platform to develop mobile applications which run
across smartphones. Java is a platform for App Development in Android.
Java Platform
Java Platform is a collection of programs. It helps to develop and run a program written in the Java
programming language. Java Platform includes an execution engine, a compiler and set of
libraries. Java is a platform-independent language.
Features of Java
Simple: Java is a simple language because its syntax is simple, clean, and easy to understand.
Complex and ambiguous concepts of C++ are either eliminated or re-implemented in Java. For
example, pointer and operator overloading are not used in Java.
Object-Oriented: In Java, everything is in the form of the object. It means it has some data and
behavior. A program must have at least one class and object.
Robust: Java makes an effort to check error at run time and compile time. It uses a strong memory
management system called garbage collector. Exception handling and garbage collection features
make it strong.
Secure: Java is a secure programming language because it has no explicit pointer and programs
runs in the virtual machine. Java contains a security manager that defines the access of Java
classes.
Platform-Independent: Java provides a guarantee that code writes once and run anywhere. This
byte code is platform-independent and can be run on any machine.
Portable: Java Byte code can be carried to any platform. No implementation-dependent features.
Everything related to storage is predefined, for example, the size of primitive data types.
High Performance: Java is an interpreted language. Java enables high performance with the use
of the Just-In-Time compiler.
Distributed: Java also has networking facilities. It is designed for the distributed environment of
the internet because it supports TCP/IP protocol. It can run over the internet. EJB and RMI are
used to create a distributed system.
Multi-threaded: Java also supports multi-threading. It means to handle more than one job a time.
Freeware: Java is a freeware programming language.
Evolution or Version of Java:

How to install Java for Windows


Following are the steps for JDK 8 free download for 32 bit or JDK 8 download 64 bit and
installation

Step 1) Go to link. Click on JDK Download for Java JDK 8 download.

Step 2) Next,

1. Accept License Agreement


2. Download Java 8 JDK for your version 32 bit or JDK 8 download for windows 10 64 bit.
Step 3) When you click on the Installation link the popup will be open. Click on I reviewed and
accept the Oracle Technology Network License Agreement for Oracle Java SE and you will be
redirected to the login page. If you don't have an oracle account you can easily sign up by adding
basics details of yours.

NOTE: You will be required to create an Oracle Account to start download of the file.

Step 4) Once the Java JDK 8 download is complete, run the exe for install JDK. Click Next

Step 5) Select the PATH to install Java in Windows… You can leave it Default. Click next.
NOTE: Follow the onscreen instructions in succeeding installation steps.

Step 6) Once you install Java in windows, click Close

First Program of Java

class first
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}

Save: C:\Program Files (x86)\Java\jdk1.8.0_171\bin—first.java

Compilation and Execution:

JAVA DEVELOPMENT KIT


The Java Development Kit (JDK) is a software development environment used for developing
Java applications and applets. It includes the Java Runtime Environment (JRE), an
interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator
(Javadoc) and other tools needed in Java development.
JAVA RUNTIME ENVIRONMENT
JRE stands for “Java Runtime Environment” and may also be written as “Java RTE.” The
Java Runtime Environment provides the minimum requirements for executing a Java
application; it consists of the Java Virtual Machine (JVM), core classes, and supporting files.
JAVA VIRTUAL MACHINE

It is:
 A specification where working of Java Virtual Machine is specified. But implementation
provider is independent to choose the algorithm. Its implementation has been provided by
Sun and other companies.
 An implementation is a computer program that meets the requirements of the JVM
specification
 Runtime Instance Whenever you write java command on the command prompt to run
the java class, an instance of JVM is created.

Difference betweem JDK, JRE and JVM


To understand the difference between these three, let us consider the following diagram.

 JDK – Java Development Kit (in short JDK) is Kit which provides the


environment to develop and execute(run) the Java program. JDK is a kit(or package)
which includes two things
1. Development Tools(to provide an environment to develop your java
programs)
2. JRE (to execute your java program).
Note : JDK is only used by Java Developers.
 JRE – Java Runtime Environment (to say JRE) is an installation package which
provides environment to only run(not develop) the java program(or application)onto
your machine. JRE is only used by them who only wants to run the Java Programs i.e.
end users of your system.
 JVM – Java Virtual machine(JVM) is a very important part of both JDK and
JRE because it is contained or inbuilt in both. Whatever Java program you run using
JRE or JDK goes into JVM and JVM is responsible for executing the java program
line by line hence it is also known as interpreter.

Platform Independency:
Escape sequences in Java

Escape Sequence Description

\t Inserts a tab in the text at this point.

\b Inserts a backspace in the text at this point.

\n Inserts a newline in the text at this point.

\r Inserts a carriage return in the text at this point.

\f Inserts a form feed in the text at this point.

\' Inserts a single quote character in the text at this point.

\" Inserts a double quote character in the text at this point.

\\ Inserts a backslash character in the text at this point.

What will be the output of following program


public class Main
{
public static void main(String[] args) {
int a=023;
System.out.println(a);
}
}
Output:

public class Main


{
public static void main(String[] args) {
int a=0x23;
System.out.println(a);
}
}
Output:

Keywords:

Identifiers:
An identifier is a sequence of one or more characters. The first character must be a valid first character
(letter, $, _) in an identifier of the Java programming language

Rules for defining Java Identifiers

There are certain rules for defining a valid java identifier. These rules must be followed, otherwise
we get compile-time error. These rules are also valid for other languages like C,C++.

 The only allowed characters for identifiers are all alphanumeric characters([A-Z],[a-z],[0-
9]), ‘$‘(dollar sign) and ‘_‘ (underscore).For example “geek@” is not a valid java
identifier as it contain ‘@’ special character.
 Identifiers should not start with digits([0-9]). For example “123geeks” is a not a valid java
identifier.
 Java identifiers are case-sensitive.
 There is no limit on the length of the identifier but it is advisable to use an optimum length
of 4 – 15 letters only.
 Reserved Words can’t be used as an identifier. For example “int while = 20;” is an invalid
statement as while is a reserved word. There are 53 reserved words in Java.

Examples of valid identifiers :


 MyVariable
 MYVARIABLE
 myvariable
 x
 i
 x1
 i1
 _myvariable
 $myvariable
 sum_of_array
 geeks123

Examples of invalid identifiers :


 My Variable // contains a space
 123geeks // Begins with a digit
 a+c // plus sign is not an alphanumeric character
 variable-2 // hyphen is not an alphanumeric character
 sum_&_difference // ampersand is not an alphanumeric character
Datatype:
Data type specifies the size and type of values that can be stored in an identifier. ... Data types in
Java are classified into two types: Primitive—which include Integer, Character, Boolean, and
Floating Point. Non-primitive—which include Classes, Interfaces, and Arrays.
Bank Software:
1. account number 12345
2. name ram
3. balance 1000.378
Task of byte, short, int, long, char, float, double and boolean:
1. To intimate compiler regarding types of data.
2. To allocate a memory space for data.

class Main
{
public static void main(String[] args)
{
byte b1;
b1=13;
System.out.println(b1);
}
}
Memory representation:
b1

0 1 2 3 4 5 6 7
0 0 0 0 1 1 0 1

remainder
2 13 1
2 6 0
2 3 1
1  ---1
(13)10 = (1101)2
6 5 4 3 2 1 0
0*2 + 0*2 + 0*2 + 1*2 + 1*2 + 0*2 +1*2

0+0+0+8+4+0+1
Sign Bit
1) +ive 0
2) –ive 1

Range Calculation
Byte: 8 bits
Total values: 28 = 256
To find out max +ive & -ive values
256/2= +-128
128 (-ive values)
128 (+ive values)
1 (zero value)
257

128 (-ive values)


127 (+ive values)
1 (zero value)
256
byte (-128 to 127)
Range of data types in Java

public class Main


{
public static void main(String[] args)
{
byte b1=13; //-128 to +127
short s1=b1; //-32768 to +32767
System.out.println(s1);
}
}

public class Main


{
public static void main(String[] args)
{
short s1=13; //-32768 to +32767
byte b1=(byte)s1; //-128 to +127
System.out.println(b1);
}
}

b s
13 13
8 bits 16 bits

s b
13
16 bits 8 bits

Implicit Type Casting

Smaller Size Data Bigger Size

Explicit Type Casting

Operator
Arithmetic Relational Logical Bitwise Assignment
+ < && & =
- > || | +=
* <= ! << -=
/ >= >> *=
% != >>> /=
++ == ^ %=
-- ~ &=
|=
<<=
>>=
^=

Arithmetic: execute on data and generate a data


2+3 =5
2.1-1.1=1.0
3*5=15
15/3=5
15%3=0
1.1%1.1=Error
5.0%1.0=error
20%30=20
30%20=10
++ Increment value by 1
Pre increment Post increment
X=10; X=10;
Y=++X; Y=X++
Y=11 Y=10;
X=11 X=11

-- Decrement value by 1
Pre decrement Post decrement
X=10; X=10;
Y=--X; Y=X--
Y=9 Y=10;
X=9 X=9

Relational Operator: execute with data and generate a Boolean value


<,>,<=,>=,!=,==
boolean b1=20<30;
SOP(b1); //true b1=true;
Expression Result
3>9 f
12<=12 t
-23>23 f
1!=2 t
2==2 t
5=!=-50 error
‘a’==’a’ t
‘a’==97 T
‘A’==’a’ F
2.3==3.2 F

Logical Operator: execute with Boolean value and generate a Boolean value
&&, ||, !
AND (&&)
boolean b1=true&&false; //false
boolean b1=true&&1; //error
Truth table
L R Result
T T T
T F F
F T F
F F F

OR (||)
boolean b1=true||false; //true
//boolean b1=true||11; //error
boolean b1=20<30||50>100; //true

L R Result
T T T
T F T
F T T
F F F

NOT (!)
true false
false true
boolean b1=!(30<40); //false
boolean b1=!(30>40); //true

Bitwise Operator: execute on binary (bits) of data and generate a data


&, |, <<,>>,>>>,^,~
int a= 5&9; //Ans: 1
8 4 2 1
5 0 1 0 1
9 1 0 0 1
ANS Bits 0 0 0 1
0*8=0 0*4=0 0*2=0 1*1=1

int a=121&71;
64 32 16 8 4 2 1
121 1 1 1 1 0 0 1
71 1 0 0 0 1 1 1
1 0 0 0 0 0 1
Answer-> 65 64 0 0 0 0 0 1

OR (|)
int a=2|3 //3
0010
0011

0011
<< left shift
int a=12<<2; //48

8 4 2 1
(12)10 1 1 0 0
1 1 0 0 0 0
32 16 8 4 2 1

Direct Method: add number of zero at right side with binary of data
1100 (<<2, add 00 with this binary data)  110000

Right
int a=12>>2; //answer 3
1100
int a=12>>>2; //answer 3

(12)10 1 1 0 0
>> 1 1
>>> 0 0 1 1

^ XOR
L R result
1 1 0
1 0 1
0 1 1
0 0 0

int a=5^6; //Answer 3


a=a+b //a=a^b
b=a-b; //b=a^b
a=a-b; //a=a^b

101
110

011
~ complement operator
int a=~12; //-13
Sign Bit 8 4 2 1
0 1 1 0 0
Inverse + 1
1 1 1 0 1
int a=~ -12; //11

Sign 8 4 2 1
Bit
1 1 1 0 0
1’s Comp 0 0 1 1
+ (1) (1) 1
2’s Comp 0 1 0 0
0 Inverse 1 0 1 1

int a=2+3*5-20/4%3;
=2+15-20/4%3;
=2+15-5%3
=2+15-2
= 17-2
=15
int a=20*2-40%30*2
=40-40%30*2
=40-10*2
=40-20
=20;
Wrong method
int a=20*2-40%30*2
=40-40%60
=40-40
=0

Java Operator Precedence Table

Precedence Operator Type Associativity


() Parentheses
15 [] Array subscript Left to Right
· Member selection
++ Unary post-increment
14 Right to left
-- Unary post-decrement

++ Unary pre-increment
-- Unary pre-decrement
+ Unary plus
13 - Unary minus Right to left
! Unary logical negation
~ Unary bitwise complement
( type ) Unary type cast

* Multiplication
12 / Division Left to right
% Modulus
+ Addition
11 Left to right
- Subtraction
<< Bitwise left shift
10 >> Bitwise right shift with sign extension Left to right
>>> Bitwise right shift with zero extension

< Relational less than


<= Relational less than or equal
9 > Relational greater than Left to right
>= Relational greater than or equal
instanceof Type comparison (objects only)
== Relational is equal to
8 Left to right
!= Relational is not equal to
7 & Bitwise AND Left to right
6 ^ Bitwise exclusive OR Left to right
5 | Bitwise inclusive OR Left to right
4 && Logical AND Left to right
3 || Logical OR Left to right
2 ?: Ternary conditional Right to left

= Assignment
+= Addition assignment
-= Subtraction assignment
1 Right to left
*= Multiplication assignment
/= Division assignment
%= Modulus assignment

Conditional Statement
1. If statement
2. If-else statement
3. Switch statement
Syntax of if statement
------
if(boolean)
{
-----
-----
}
-----
public class Main
{
public static void main(String[] args)
{
int a=10,b=20;
if(a>b)
{
System.out.println(a+" is largest number");
}
if(b>a)
{
System.out.println(b+" is largest number");
}
if(a==b)
{
System.out.println("Both numbers are equal");
}
}
}
Nested if statement
------
if(boolean)
{
-----
------
if(boolean)
{
-----
-----
}
-----
-----
}
-----
public class Main
{
public static void main(String[] args)
{
int a=10,b=20,c=30;
if(a>b)
{
if(a>c)
{
System.out.println(a+" is largest number");
}
}
if(b>a)
{
if(b>c)
{
System.out.println(b+" is largest number");
}
}
if(c>a)
{
if(c>b)
{
System.out.println(c+" is largest number");
}
}
if(a==b)
{
if(a==c)
{
System.out.println("All numbers are equal");
}
}
}
}
if-else statement
------
if(boolean)
{
-----
-----
}
else
{
-----
-----
}

public class Main


{
public static void main(String[] args)
{
int a=10;
if(a%2==0)
{
System.out.println(a+" is even number");
}
else
{
System.out.println(a+" is odd number");
}
}
}

Nested If-else statement


------
if(boolean)
{
-----
if(boolean)
{
-----
}
else
{
-----
}
}
else
{
-----
if(boolean)
{
-----
}
else
{
-----
}
}
public class Main
{
public static void main(String[] args)
{
int a=10,b=20,c=30;
if(a>b)
{
if(a>c)
{
System.out.println(a+" is largest number");
}
else
{
System.out.println(c+" is largest number");
}
}
else
{
if(b>c)
{
System.out.println(b+" is largest number");
}
else
{
System.out.println(c+" is largest number");
}
}
}
}
int a,b,c;
Scanner sc=new Scanner(System.in);
System.out.println("Enter first number");
a=sc.nextInt();
System.out.println("Enter second number");
b=sc.nextInt();
System.out.println("Enter third number");
c=sc.nextInt();
if(a>b)
{
if(a>c)
{
System.out.println("A is greatest Number");
}
}
if(b>a)
{
if(b>c)
{
System.out.println("B is greatest Number");
}
}
if(c>a)
{
if(c>b)
{
System.out.println("C is greatest Number");
}
}

Loop or control structure


1. For loop
2. While loop
3. Do-while loop

Syntax of for loop

for (initialization; condition/expression; update/incr/decr)


{
----
----
}
Nested for loop
for (initialization; condition/expression; update/incr/decr)
{
for (initialization; condition/expression; update/incr/decr cr)
{
----
}
}

1
22
333

While loop

Syntax of while loop

initialization;
while(Boolean)
{
-------
inc/dec;
}

Nested while loop

initialization;
while(Boolean)
{
-------
initialization;
while(Boolean)
{
-------
inc/dec;
}
inc/dec;
}

DO-While loop

Syntax of do-while loop

initialization;
do
{
-------
inc/dec;
}
while(boolean);

Program
class abc
{
PSVM(String ar[])
{
int a;
a=11;
do
{
System.out.println(“Hello”);
a++;
}
while(a<=3);
}
}

Output:

Hello

Hello

Hello

Nested do-while loop

initialization;
do
{
-------
initialization;
do
{
-------
inc/dec;
}
while(boolean);
inc/dec;
}
while(boolean);

class abc
{
PSVM(String ar[])
{
int a,b;
a=1;
do
{
b=1;
do
{
System.out.print(“*”);
a++;
}
while(b<=a);
a++;
System.out.println(“”);
}
while(a<=3);
}
}
*
**
***

for( ; ; )
{
System.out.println(“Hello”);
}
Break & Continue Keyword:
Break:
The break statement can also be used to jump out of a loop.

for (int i = 0; i < 10; i++) {


if (i == 4) {
break;
}
System.out.println(i);
}
0123

Continue:
The continue statement breaks one iteration (in the loop), if a specified condition occurs,
and continues with the next iteration in the loop.
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
}
012356789

Java Switch Statements


Use the switch statement to select one of many code blocks to be executed.

Syntax

switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

int day = 4;
switch (day)
{
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid choice");

}
// Outputs "Thursday" (day 4)

Array:
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
To declare an array, define the variable type with square brackets.

Types of array:

1. One dimensional array


2. Multi-dimensional array

One Dimensional Array:


Syntax
datatype arrayRefVar[] = new datatype[int arraySize];
Example
Following statement declares an array variable, myList, creates
an array of 10 elements of double type and assigns its reference
to myList −
double[] myList = new double[10];
Following picture represents array myList. Here, myList holds
ten double values and the indices are from 0 to 9.
myList[2]=1000.23;

Processing Arrays
When processing array elements, we often use either for loop or
foreach loop because all of the elements in an array are of the
same type and the size of the array is known.
Example
Here is a complete example showing how to create, initialize,
and process arrays −

public class TestArray {


public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0.0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
This will produce the following result −
Output
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter size of array");
int n=sc.nextInt();
int a[]=new int[n];
System.out.println("Enter array elements");
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
System.out.println("Array elements is");
for(int i=0;i<n;i++)
{
System.out.println(a[i]);
}
}
}
public class Main
{
public static void main(String[] args)
{
int a[]={11,22,33,44,55};
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
}
The foreach Loops
JDK 1.5 introduced a new for loop known as foreach loop or
enhanced for loop, which enables you to traverse the complete
array sequentially without using an index variable.
Example
The following code displays all the elements in the array myList
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (double element: myList) {
System.out.println(element);
}
}}
This will produce the following result −
Output
1.9
2.9
3.4
3.5
public class Main
{
public static void main(String[] args)
{
int a[]={11,22,33,44,55};
for(int i:a) //foreach loop
{
System.out.println(i);
}
}
}
public class Main
{
public static void main(String[] args)
{
int a[]={11,22,33,44,55};
int b[]={100,200,300};
a=b; //
for(int i:a) //foreach loop
{
System.out.println(i);
}
}
}
a
Inde Value b/a
x Inde Value
0 11 x
1 22 0 100
2 33 1 200
3 44 2 300
4 55

A multidimensional array is an array of arrays. Each element of a


multidimensional array is an array itself. For example,
datatype[][] myList = new datatype[int size] [int size];
int[][] a = new int[3][4];
Here, we have created a multidimensional array named a. It is a
2-dimensional array, that can hold a maximum of 12 elements,

How to initialize a 2d array in Java?


Here is how we can initialize a 2-dimensional array in Java.
int[][] a = { {1, 2, 3}, {4, 5, 6, 9}, {7}};
Example: Print all elements of 2d array Using Loop
class MultidimensionalArray
{
public static void main(String[] args)
{
int[][] a = { {1, -2, 3}, {-4, -5, 6, 9}, {7} };
for (int i = 0; i < a.length; ++i)
{
for(int j = 0; j < a[i].length; ++j)
{
System.out.print(a[i][j]+”\t”);
}
System.out.println();

}
}
}
Output:
1 -2 3
-4 -5 6 9
7

Command Line Argument


The java command-line argument is an argument i.e. passed at
the time of running the java program.
The arguments passed from the console can be received in the
java program and it can be used as an input.
Simple example of command-line argument in java
In this example, we are receiving only one argument and printing
it. To run this java program, you must pass at least one argument
from the command prompt.
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample Ram shyam 123
Output: Your first argument is: Ram
class abc
{
public static void main(String ar[])
{
String s1=ar[0];
String s2=ar[1];
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
System.out.println(a+b);
}
}
OOPs (Object-Oriented Programming System)
Object means a real-world entity such as a pen, chair, table,
computer, watch, etc. Object-Oriented Programming is a
methodology or paradigm to design a program using classes and
objects. It simplifies software development and maintenance by
providing some concepts:
a. Object
b. Class
c. Inheritance
d. Polymorphism
e. Abstraction
f. Encapsulation
Class
Class is a collection of data member and member function (method)
class classname
{
datatype datamembername;
……………………………
<return type> methodname(argument list)
{}
}
Example: -
class Employee
{
//code snippet
}
Method
Method is set of instructions
Or method is a block of code
Type
1. No-return type with no arguments
2. No-return type with arguments
3. Return type with no arguments
4. Return type with arguments
<return type> methodname(argument)
{}
Example:-
class Employee
{
//method
void draw()
{
//code snippet
}
void draw(int)
{
//code snippet
}
int draw()
{
//code snippet
}
int draw(int)
{
//code snippet
}
}

Arguments

Caller Program Collee Program


(Main Class) (abc class)

Return-Types

Object
Object Definitions:
An object is a real-world entity.
An object is a runtime entity.
The object is an entity which has state and behavior.
The object is an instance of a class.
The object a representative of a class
The object is a blue print of class
Object is nothing but a block of memory

Object Creation:
classname objectname=new classname()
Example of Class, Method & Object:
class demo
{ d1 d2 d3
void show()
{
show()
System.out.println("Hello User"); show() show()
}
}
class Main
{
public static void main(String ar[])
{
demo d1=new demo(); Output
demo d2=new demo();
Hello User
demo d3=new demo();
d1.show(); Hello User
d2.show(); Hello User
d3.show();
}
}

WAP to create a class arithmetic to perform arithmetic operations


import java.util.*;
class arith a1
{ a=10
int a,b,c; b=5
void input() c=15
{ input()
Scanner sc=new Scanner(System.in); sum()
SOP("Enter any two number");
a=sc.nextInt();
b=sc.nextInt(); Output
}
void sum()
{
c=a+b;
SOP("Sum is "+c);
}

}
class Main
{
public static void main(String ar[])
{
arith a1=new arith();
a1.input();
a1.sum();
A1.sub();
}
}

import java.util.*;
class arith
{
int a,b,c;
void input()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter any two number");
a=sc.nextInt();
b=sc.nextInt();
}
void sum()
{
c=a+b;
System.out.println("Sum is "+c);
}
void sub(int p,int q)
{
c=p-q;
System.out.println("Sub is "+c);
}
int multi()
{
c=a*b;
return c;
}
float div(int p,int q)
{
return (float)p/q;
}
}
class Main
{
public static void main(String ar[])
{
arith a1=new arith();
a1.input();
a1.sum();
a1.sub(12,34);
int r=a1.multi();
System.out.println("multi "+r);
float r1=a1.div(12,5);
System.out.println("div "+r1);
}
}
Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the
class is created. At the time of calling constructor, memory for the object is allocated in the
memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized constructor.
Rules for creating Java constructor
There are two rules defined for the constructor.
 Constructor name must be the same as its class name
 A Constructor must have no explicit return type
 A Java constructor cannot be abstract, static, final, and synchronized

Default Constructor:
class demo
{ d1 d2 d3
int a,b;
demo() a=10 a=10 a=10
{ b=20 b=20 b=20
a=10; show() show() show()
b=20;
}
void show()
{
System.out.println(a+" "+b);
} Output
}
10 20
class Main
10 20
{
public static void main(String ar[]) 10 20
{
demo d1=new demo();
demo d2=new demo();
demo d3=new demo();
d1.show();
d2.show();
d3.show();
d3.show();
}
}
Parametrized Constructor:
class demo
{ d1 d2 d3
int a,b;
demo(int p,int q) a=10 a=3 a=-1
{ b=20 b=8 b=-2
a=p; show() show() show()
b=q;
}
void show()
{
System.out.println(a+" "+b);
} Output
}
10 20
class Main
3 8
{
public static void main(String ar[]) -1 -2
{
demo d1=new demo(10,20);
demo d2=new demo(3,8);
demo d3=new demo(-1,-2);
d1.show();
d2.show();
d3.show();
}
}

Multiple Constructor/ Constructor overloading:


class demo
{ d1 d2 d3
int a,b;
demo() a=38
a=-11
a=10
{ b=38
b=-22
b=20
a=10; show()
b=20;
}
demo(int p)
{
a=p;
b=p; Output
}
demo(int p,int q) 10 20
{ 38 38
a=p; -11 -22
b=q;
}
void show()
{
System.out.println(a+" "+b);
}
}
class Main
{
public static void main(String ar[])
{
demo d1=new demo();
demo d2=new demo(38);
demo d3=new demo(-11,-22);
d1.show();
d2.show();
d3.show();
}
}

x
import java.util.*;
class arith
{
int sum(int p[])
{
int c=0;
for(int i:p)
{
c=c+i;
}
return c;
}
}
class Main
{
public static void main(String ar[])
{
arith a1=new arith();
int a[]={11,22,33,44,55};
int r1=a1.sum(a);
System.out.println("result "+r1);
}
}
import java.util.*;
class arith
{
int a[]={11,22,33,44,55};
int[] sum()
{
return a;
}
}
class Main
{
public static void main(String ar[])
{
arith a1=new arith();
int r1[]=a1.sum();
for(int i:r1)
System.out.println(i);
}
}
Note: we can define multiple constructor in a class but parameter
should be different.
Parameters are differentiated by:
1. Numbers of parameters:
demo()
demo(int)
demo(int,int)
2. Types of parameters:
demo(int)
demo(char)
3. Order of parameters:
demo(int char)
demo(char,int)

import java.util.*;
class arith
{
int a[]={11,22,33,44,55};
int[] sum()
{
return a;
}
}
class Main
{
public static void main(String ar[])
{
arith a1[]=new arith[10];
/*int r1[]=a1.sum();
for(int i:r1)
System.out.println(i);*/
}
}

Object referencing:
class one o1/op/ox(t2) t1 t2
{ ox ox
int a,b; a=10,1000
void show() b=20,2000 a=1000 set()
{ show() b=2000 get()
System.out.println(a+" "+b); Show()
}
} set()
class two get()
{
one ox; Output
two() 10 20
{ 1000 2000
ox=new one(); 10 20
} 1000 2000
two(one op)
{
ox=op; class Main{
} public static void main(String ar[]){
void set() one o1=new one();
{ o1.a=10;
ox.a=1000; o1.b=20;
ox.b=2000; o1.show();
} two t1=new two();
void get() t1.set();
{ t1.get();
ox.show(); two t2=new two(o1);
} t2.get();
} t2.set();
t2.get();}}
Java – Static Class, Block, Methods and Variables
Static keyword can be used with class, variable, method and block. Static members belong to the class
instead of a specific instance, this means if you make a member static, you can access it without object.
Let’s take an example to understand this:
Here we have a static method myMethod(), we can call this method without any object because when we
make a member static it becomes class level. If we remove the static keyword and make it non-static then
we must need to create an object of the class in order to call it.
Static members are common for all the instances(objects) of the class but non-static members are separate
for each instance of class.

o The static variable can be used to refer to the common property of all objects
(which is not unique for each object), for example, the company name of
employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time of class
loading.
o A static method belongs to the class rather than the object of a class.

o A static method can be invoked without the need for creating an instance of a
class.
o A static method can access static data member and can change the value of it.
o static block used to initialize the static data member.
o static block is executed before the main method at the time of classloading.

class demo
{ d1 d2 d3
int a,b; a=100
a=1000
a=10
static int c;
void show()
{
System.out.println(a+" "+b+"
demo
"+c);
} c=0,30,300,3000
static void display() display()
{
System.out.println(c); Output
}
} 10 20 3000
class Main 100 200 3000
{ 1000 2000 3000
public static void main(String ar[])
3000
{
3000
demo d1=new demo();
3000
demo d2=new demo();
demo d3=new demo();
d1.a=10;
d1.b=20;
d1.c=30;//demo.c=30;
d2.a=100;
d2.b=200;
d2.c=300;
d3.a=1000;
d3.b=2000;
d3.c=3000;
d1.show();
d2.show();
d3.show();
d1.display();//demo.display();
d2.display();
d3.display();
}
}
import java.util.*;
class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the details ");
int a=sc.nextInt();
if(a==11)
{
Main.main(args);
}
else
{
System.out.println("Input value is: "+a);
}
}
}

Example of static block


class A2{
static{
System.out.println("static block is invoked");
}
public static void main(String args[]){
System.out.println("Hello main");
}
}
Output:

static block is invoked


Hello main

Example:
class SimpleStaticExample
{
// This is a static method
static void myMethod()
{
System.out.println("myMethod");
}

public static void main(String[] args)


{
/* You can see that we are calling this
* method without creating any object.
*/
myMethod();
}
}
Output:
myMethod

import java.util.*;
class bank
{
int cid;
String cnm;
float cbal,wm,dm;
static float bbal;
Scanner sc=new Scanner(System.in);
void get()
{
System.out.println("Enter customer id, name & balance");
cid=sc.nextInt();
cnm=sc.nextLine();
cnm=sc.nextLine();
cbal=sc.nextFloat();
bbal=bbal+cbal;
}
void show()
{
System.out.println("Customer id is: "+cid);
System.out.println("Customer name is: "+cnm);
System.out.println("Customer balance is: "+cbal);
}
void deposit()
{
System.out.println("Enter amount to be deposit");
dm=sc.nextFloat();
cbal=cbal+dm;
bbal=bbal+dm;
}
void withdraw()
{
System.out.println("Enter amount to be withdraw");
wm=sc.nextFloat();
cbal=cbal-wm;
bbal=bbal-wm;
}
static void showbankbal()
{
System.out.println("Current Bank balance is: "+bbal);
}
}
public class Main
{
public static void main(String[] args)
{
bank.showbankbal();
bank b1=new bank();
b1.get();
b1.show();
bank.showbankbal();
b1.withdraw();
bank.showbankbal();
b1.deposit();
bank.showbankbal();
bank.showbankbal();
bank b2=new bank();
b2.get();
b2.show();
bank.showbankbal();

}
}

Inheritance
The process by which one class acquires the properties(data members) and functionalities(methods) of
another class is called inheritance. The aim of inheritance is to provide the reusability of code so that a
class has to write only the unique features and rest of the common properties and functionalities can be
extended from the another class.

Parent/Base/Super
Class

Child/Derived/Sub
Class

Child Class:
The class that extends the features of another class is known as child class, sub class or derived class.

Parent Class:
The class whose properties and functionalities are used(inherited) by another class is known as parent class,
super class or Base class.

Inheritance is a process of defining a new class based on an existing class by extending its common data
members and methods.

Inheritance allows us to reuse of code, it improves reusability in your java application.


Note: The biggest advantage of Inheritance is that the code that is already present in base class need not be
rewritten in the child class.
This means that the data members (instance variables) and methods of the parent class can be used in the
child class as.
Syntax: Inheritance in Java
To inherit a class we use extends keyword. Here class XYZ is child class and class ABC is parent class.
The class XYZ is inheriting the properties and methods of ABC class.

class XYZ extends ABC


{
}

Types of inheritance
Single Inheritance: refers to a child and parent class relationship where a class extends the another class.

Multilevel inheritance: refers to a child and parent class relationship where a class extends the child class.
For example class C extends class B and class B extends class A.

Hierarchical inheritance: refers to a child and parent class relationship where more than one classes
extends the same class. For example, classes B, C & D extends the same class A.

Multiple Inheritance: refers to the concept of one class extending more than one classes, which means a
child class has two parent classes. For example class C extends both classes A and B. Java doesn’t support
multiple inheritance, read more about it here.
Hybrid inheritance: Combination of more than one types of inheritance in a single program. For example
class A & B extends class C and another class D extends class A then this is a hybrid inheritance example
because it is a combination of single and hierarchical inheritance.

Single Inheritance Example: input


int a,b
void inputdata()

addition
int c
void sum()

import java.util.*; class Main


class input {
{ public static void main(String args[])
int a,b; {
void inputdata() addition a1=new addition();
{ a1.inputdata();
System.out.println("Enter any two number"); a1.sum();
a=sc.nextInt(); }
b=sc.nextInt(); }
}
}
class addition extends input
{
int c;
void sum()
{
c=a+b;
System.out.println("sum="+c);
}
}
Multilevel Inheritance Example:

input
int a,b
void inputdata()

addition
int c
void sum()

sqaure
int s
void srq()

import java.util.*; class Main


class input {
{ public static void main(String args[])
int a,b; {
void input() square a1=new sqaure();
{ a1.input();
System.out.println("Enter any two number"); a1.sum();
a=sc.nextInt(); a1.sqr();
b=sc.nextInt(); }
} }
}
class addition extends input
{
int c;
void sum()
{
c=a+b;
System.out.println("sum="+c);
}
}
class square extends addition
{
int s;
void sqr()
{
s=c*c;
System.out.println("Square= "+s);
}
}

Hierarchical Inheritance Example:


input
int a,b
void inputdata()

addition substract
int c int d
void sum() void sub()
import java.util.*; class Main
class input {
{ public static void main(String args[])
int a,b; {
void input() addition a1=new addition();
{ a1.input();
System.out.println("Enter any two number"); a1.sum();
a=sc.nextInt(); substract a2=new substract ();
b=sc.nextInt(); a2.input();
} a2.sum();
}
class addition extends input }
{ }
int c;
void sum()
{
c=a+b;
System.out.println("sum="+c);
}
}
class substract extends input
{
int d;
void sum()
{
d=a-b;
System.out.println("sub="+d);
}
}

Constructors and Inheritance


constructor of sub class is invoked when we create the object of subclass, it by default invokes the default
constructor of super class. Hence, in inheritance the objects are constructed top-down. The superclass
constructor can be called explicitly using the super keyword, but it should be first statement in a
constructor. The super keyword refers to the superclass, immediately above of the calling class in the
hierarchy. The use of multiple super keywords to access an ancestor class other than the direct parent is not
permitted.

class one class two extends one class Main


{ { {
int a,b; int c,d; public static void main(String
one() two() args[])
{ { {
a=10; c=30; two t1=new two();
b=20; d=40; two t2=new two(5);
} } two t3=new two(25,15);
one(int p) two(int p) t1.show();//10 20
{ { t2.show();// 10 20
a=p; c=p; t3.show();//10 20
b=p; d=p; t1.sum();//100
} } t2.sum();//40
one(int p,int q) two(int p,int q) t3.sum();//70
{ { }
a=p; c=p; }
b=q; d=q;
} }
void show() void sum()
{ {
System.out.println(a+" "+b); int s=a+b+c+d;
} System.out.println("Sum "+s);
} }
}
class ParentClass{
//Parent class constructor
ParentClass(){
System.out.println("Constructor of Parent");
}
}
class JavaExample extends ParentClass{
JavaExample(){
/* It by default invokes the constructor of parent class
* You can use super() to call the constructor of parent.
* It should be the first statement in the child class
* constructor, you can also call the parameterized constructor
* of parent class by using super like this: super(10), now
* this will invoke the parameterized constructor of int arg
*/
System.out.println("Constructor of Child");
}
public static void main(String args[]){
//Creating the object of child class
new JavaExample();
}
}
Output:

Constructor of Parent
Constructor of Child

Super keyword in java with example


The super keyword refers to the objects of immediate parent class. Before learning super keyword you
must have the knowledge of inheritance in Java so that you can understand the examples given in this
guide.

The use of super keyword


1) To access the data members of parent class when both parent and child class have member with same
name
2) To explicitly call the no-arg and parameterized constructor of parent class
3) To access the method of parent class when child class has overridden that method.

Now lets discuss them in detail with the help of examples:

1) How to use super keyword to access the variables of parent class


When you have a variable in child class which is already present in the parent class then in order to access
the variable of parent class, you need to use the super keyword.
Lets take an example to understand this: In the following program, we have a data member num declared in
the child class, the member with the same n ame is already present in the parent class. There is no way you
can access the num variable of parent class without using super keyword. .
class one class two extends one class Main
{ { {
int a,b; int c,d; public static void main(String
one() two() args[])
{ { {
a=10; c=30; two t1=new two();
b=20; d=40; two t2=new two(5);
} } two t3=new two(25,15);
one(int p) two(int p) t1.show();//10 20
{ { t2.show();//5 5
a=p; super(p); t3.show();//25 15
b=p; c=p; t1.sum();//100
} d=p; t2.sum();//20
one(int p,int q) } t3.sum();//80
{ two(int p,int q) }
a=p; { }
b=q; super(p,q);
} c=p;
void show() d=q;
{ }
System.out.println(a+" "+b); void sum()
} {
} int s=a+b+c+d;
System.out.println("Sum "+s);
}
}

//Parent class or Superclass or base class


class Superclass
{
int num = 100;
}
//Child class or subclass or derived class
class Subclass extends Superclass
{
/* The same variable num is declared in the Subclass
* which is already present in the Superclass
*/
int num = 110;
void printNumber(){
System.out.println(num);
}
public static void main(String args[]){
Subclass obj= new Subclass();
obj.printNumber();
}
}
Output:
110

Accessing the num variable of parent class:


By calling a variable like this, we can access the variable of parent class if both the classes (parent and
child) have same variable.
super.variable_name
Let’s take the same example that we have seen above, this time in print statement we are passing super.num
instead of num.
class Superclass
{
int num = 100;
}
class Subclass extends Superclass
{
int num = 110;
void printNumber(){
/* Note that instead of writing num we are
* writing super.num in the print statement
* this refers to the num variable of Superclass
*/
System.out.println(super.num);
}
public static void main(String args[]){
Subclass obj= new Subclass();
obj.printNumber();
}
}
Output:
100
As you can see by using super.num we accessed the num variable of parent class.

2) Use of super keyword to invoke constructor of parent class


When we create the object of sub class, the new keyword invokes the constructor of child class, which
implicitly invokes the constructor of parent class. So the order to execution when we create the object of
child class is: parent class constructor is executed first and then the child class constructor is executed. It
happens because compiler itself adds super()(this invokes the no-arg constructor of parent class) as the first
statement in the constructor of child class.

Let’s see an example to understand what I have explained above:

class Parentclass
{
Parentclass(){
System.out.println("Constructor of parent class");
}
}
class Subclass extends Parentclass
{
Subclass(){
/* Compile implicitly adds super() here as the
* first statement of this constructor.
*/
System.out.println("Constructor of child class");
}
Subclass(int num){
/* Even though it is a parameterized constructor.
* The compiler still adds the no-arg super() here
*/
System.out.println("arg constructor of child class");
}
void display(){
System.out.println("Hello!");
}
public static void main(String args[]){
/* Creating object using default constructor. This
* will invoke child class constructor, which will
* invoke parent class constructor
*/
Subclass obj= new Subclass();
//Calling sub class method
obj.display();
/* Creating second object using arg constructor
* it will invoke arg constructor of child class which will
* invoke no-arg constructor of parent class automatically
*/
Subclass obj2= new Subclass(10);
obj2.display();
}
}
Output:
Constructor of parent class
Constructor of child class
Hello!
Constructor of parent class
arg constructor of child class
Hello!

Parameterized super() call to invoke parameterized constructor of parent class


We can call super() explicitly in the constructor of child class, but it would not make any sense because it
would be redundant. It’s like explicitly doing something which would be implicitly done otherwise.
However when we have a constructor in parent class that takes arguments then we can use parameterized
super, like super(100); to invoke parameterized constructor of parent class from the constructor of child
class.
Let’s see an example to understand this:

class Parentclass
{
//no-arg constructor
Parentclass(){
System.out.println("no-arg constructor of parent class");
}
//arg or parameterized constructor
Parentclass(String str){
System.out.println("parameterized constructor of parent class");
}
}
class Subclass extends Parentclass
{
Subclass(){
/* super() must be added to the first statement of constructor
* otherwise you will get a compilation error. Another important
* point to note is that when we explicitly use super in constructor
* the compiler doesn't invoke the parent constructor automatically.
*/
super("Hahaha");
System.out.println("Constructor of child class");

}
void display(){
System.out.println("Hello");
}
public static void main(String args[]){
Subclass obj= new Subclass();
obj.display();
}
}
Output:

parameterized constructor of parent class


Constructor of child class
Hello
This Keyword:
class demo
{
int a,b;//globle variable
demo()
{
a=10;
b=20;
}
void show(int a,int b) //local variable
{
//this.a=a;
//this.b=b;
System.out.println(a+" "+b);
System.out.println(this.a+" "+this.b);
}
}
public class Main
{
public static void main(String[] args)
{
demo d1=new demo();
d1.show(5,7);
}
}

Polymorphism:
Polymorphism is one of the OOPs feature that allows us to perform a single action in different
ways. For example, lets say we have a class Animal that has a method sound(). Since this is a
generic class so we can’t give it a implementation like: Roar, Meow, Oink etc. We had to give a
generic message.

Compile time/Early binding/Static binding:


Method Overloading:
Method Overloading is a feature that allows a class to have more than one method having the
same name, if their argument lists are different. It is similar to constructor overloading in Java,
that allows a class to have more than one constructor having different argument lists.

let’s get back to the point, when I say argument list it means the parameters that a method has: For
example the argument list of a method add(int a, int b) having two parameters is different from the
argument list of the method add(int a, int b, int c) having three parameters.
Three ways to overload a method

In order to overload a method, the argument lists of the methods must differ in either of these:
1. Number of parameters.
For example: This is a valid case of overloading
add(int, int)
add(int, int, int)

2. Data type of parameters.


For example:
add(int, int)
add(int, float)

3. Sequence of Data type of parameters.


For example:
add(int, float)
add(float, int)

Program:

class DisplayOverloading
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(char c, int num)
{
System.out.println(c + " "+num);
}
}
class Sample
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}
}
Output:

a
a 10
class demo
{
void show(int a)
{
System.out.println("int: "+a);
}
void show(float a)
{
System.out.println("flloat: "+a);
}

}
public class Main
{
public static void main(String[] args)
{
demo d1=new demo();
d1.show(57);
d1.show(23.5f);
}
}
class demo
{
void show(int a)
{
System.out.println("int: "+a);
}
int show(int a)
{
System.out.println("flloat: "+a);
}
}
public class Main
{
public static void main(String[] args)
{
demo d1=new demo();
d1.show(57);
d1.show(23.5f);
}
}

Method Overriding
Declaring a method in sub class which is already present in parent class is known as method
overriding. Overriding is done so that a child class can give its own implementation to a method
which is already provided by the parent class. In this case the method in parent class is called
overridden method and the method in child class is called overriding method. In this guide, we
will see what is method overriding in Java and why we use it.

Method Overriding Example


Lets take a simple example to understand this. We have two classes: A child class Boy and a
parent class Human. The Boy class extends Human class. Both the classes have a common method
void eat(). Boy class is giving its own implementation to the eat() method or in other words it is
overriding the eat() method.

The purpose of Method Overriding is clear here. Child class wants to give its own implementation
so that when it calls this method, it prints Boy is eating instead of Human is eating.

class Human{
//Overridden method
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}
}
Output:
Boy is eating
class parent
{
void show()
{
System.out.println("Parent class method called...");
}
}
class child extends parent
{
void show()
{
System.out.println("Child class method called...");
}
}

public class Main


{
public static void main(String[] args)
{
child c1=new child();
c1.show();
c1.show();
}
}

class parent
{
void show()
{
System.out.println("Parent class method called...");
}
}
class child extends parent
{
void show()
{
super.show();
System.out.println("Child class method called...");
}
}

public class Main


{
public static void main(String[] args)
{
child c1=new child();
c1.show();
c1.show();
}
}

Method Overriding and Dynamic Method Dispatch


Method Overriding is an example of runtime polymorphism. When a parent class reference points
to the child class object then the call to the overridden method is determined at runtime, because
during method call which method(parent class or child class) is to be executed is determined by
the type of object. This process in which call to the overridden method is resolved at runtime is
known as dynamic method dispatch. Lets see an example to understand this:

class ABC{
//Overridden method
public void disp()
{
System.out.println("disp() method of parent class");
}
}
class Demo extends ABC{
//Overriding method
public void disp(){
System.out.println("disp() method of Child class");
}
public void newMethod(){
System.out.println("new method of child class");
}
public static void main( String args[]) {
/* When Parent class reference refers to the parent class object
* then in this case overridden method (the method of parent class)
* is called.
*/
ABC obj = new ABC();
obj.disp();

/* When parent class reference refers to the child class object


* then the overriding method (method of child class) is called.
* This is called dynamic method dispatch and runtime polymorphism
*/
ABC obj2 = new Demo();
obj2.disp();
}
}
Output:

disp() method of parent class


disp() method of Child class

class parent
{
void show()
{
System.out.println("Parent class method called...");
}
}
class child extends parent
{
void show()
{
System.out.println("Child class method called...");
}
}

public class Main


{
public static void main(String[] args)
{
parent p1;
child c1=new child();
p1=c1;
p1.show();
}
}

Final Keyword In Java


The final keyword in java is used to restrict the user. The java final keyword can be used in many
context. Final can be:
1. Variable: Can’t change
2. Method: Can’t override
3. Class: Can’t inherit
The final keyword can be applied with the variables, a final variable that have no value it is called
blank final variable or uninitialized final variable. It can be initialized in the constructor only. The
blank final variable can be static also which will be initialized in the static block only. We will
have detailed learning of these. Let's first learn the basics of final keyword.
Program
final class abc
{
final int a=10;
final void show()
{
System.out.println("Value is: "+a);
}
}
class Main
{
public static void main(String ar[])
{
abc a1=new abc();
a1.show();
}
}

class demo
{
int a;
void show()
{
System.out.println(a);
}
}
class Main
{
public static void main (String[] args)
{
demo d1=new demo();
d1.show();
d1.a=1000;
d1.show();
}
}
final class demo
{
final int a=10;
final void show()
{
System.out.println(a);
}
}
class Main
{
public static void main (String[] args)
{
demo1 d1=new demo1();
d1.show();
d1.show();
}
}
Abstract Class:
class that is declared using “abstract” keyword is known as abstract class. It can have abstract
methods(methods without body) as well as concrete methods (regular methods with body). A
normal class(non-abstract class) cannot have abstract methods. In this guide we will learn what is
a abstract class, why we use it and what are the rules that we must remember while working with
it in Java.

An abstract class can not be instantiated, which means you are not allowed to create an object of
it.
Abstract can be:
1. Class: can’t be instantiated
2. Method: methods without body, must be override
Program
abstract class abc
{
int a=10;
abstract void show();
}
class xyz extends abc
{
void show()
{
System.out.println("Value is: "+a);
}
}
class Main
{
public static void main(String ar[])
{
xyz x1=new xyz();
x1.show();
}
}

What is an interface in Java?


Interface looks like a class but it is not a class. An interface can have methods and variables
just like the class but the methods declared in interface are by default abstract (only method
signature, no body, see: Java abstract method). Also, the variables declared in an interface are
public, static & final by default

Interface can be:


1. Data member: final
2. Member method: abstract

Program:
interface abc
{
int a=10;
void show();
}
interface xyz
{
int b=20;
void sum();
}
class pqr implements abc,xyz
{
public void show()
{
System.out.println(a+" "+b);
}
public void sum()
{
System.out.println(a+b);
}
}
class Main
{
public static void main(String ar[])
{
pqr p1=new pqr();
p1.show();
p1.sum();
}
}
interface xyz
{
int a=10;
void show();
}
interface pqr
{
int b=20;
void add();
}
class demo1 implements xyz,pqr
{
public void show()
{
System.out.println(a+" "+b);
}
public void add()
{
System.out.println("Sum is: "+(a+b));
}
}
class Main
{
public static void main (String[] args)
{
demo1 d1=new demo1();
xyz x1;
x1=d1;
x1.show();//dynamic method dispatching
pqr p1;
p1=d1;
p1.add();
}
}
Packages:
package as the name suggests is a pack(group) of classes, interfaces and other packages. In
java we use packages to or`ganize our classes and interfaces. We have two types of
packages in Java: built-in packages and the packages we can create (also known as user
defined package).
package mypackage; // package folder file
public class raj
{
public void show()
{
System.out.println("Package demo");
}
}

import mypackage.raj; // bin folder file


class DDLJ
{
public static void main(String ar[])
{
raj r1=new raj();
r1.show();
}
}
Example 1: Java packages
I have created a class Calculator inside a package name letmecalculate. To create a class
inside a package, declare the package name in the first statement in your program. A class
can have only one package declaration.
Calculator.java file created inside a package letmecalculate

package letmecalculate;
public class Calculator {
public int add(int a, int b){
return a+b;
}
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(10, 20));
}
}
Now lets see how to use this package in another program.
import letmecalculate.Calculator;
public class Demo{
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(100, 200));
}
}
To use the class Calculator, I have imported the package letmecalculate. In the above
program I have imported the package as letmecalculate.Calculator, this only imports the
Calculator class. However if you have several classes inside package letmecalculate then
you can import the package like this, to use all the classes of this package.
import letmecalculate.*;
Example 2: Creating a class inside package while importing another package
As we have seen that both package declaration and package import should be the first
statement in your java program. Lets see what should be the order when we are creating a
class inside a package while importing another package.

//Declaring a package
package anotherpackage;
//importing a package
import letmecalculate.Calculator;
public class Example{
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(100, 200));
}
}

Java Access Modifiers:


You must have seen public, private and protected keywords while practising java
programs, these are called access modifiers. An access modifier restricts the access of a
class, constructor, data member and method in another class. In java we have four access
modifiers:
1. default
2. private
3. protected
4. public
Garbage Collection
When JVM starts up, it creates a heap area which is known as runtime data area. This is
where all the objects (instances of class) are stored. Since this area is limited, it is required
to manage this area efficiently by removing the objects that are no longer in use. The
process of removing unused objects from heap memory is known as Garbage collection
and this is a part of memory management in Java.

When does java perform garbage collection?


1. When the object is no longer reachable:
BeginnersBook obj = new BeginnersBook();
obj = null;
Here the reference obj was pointing to the object of class BeginnersBook but since we
have assigned a null value to it, this is no longer pointing to that object, which makes the
BeginnersBook object unreachable and thus unusable. Such objects are automatically
available for garbage collection in Java.

Another example is:


char[] sayhello = { 'h', 'e', 'l', 'l', 'o'};
String str = new String(sayhello);
str = null;
Here the reference str of String class was pointing to a string “hello” in the heap memory
but since we have assigned the null value to str, the object “hello” present in the heap
memory is unusable.

2. When one reference is copied to another reference:


BeginnersBook obj1 = new BeginnersBook();
BeginnersBook obj2 = new BeginnersBook();
obj2 = obj1;
Here we have assigned the reference obj1 to obj2, which means the instance (object)
pointed by (referenced by) obj2 is not reachable and available for garbage collection.

How to request JVM for garbage collection


We now know that the unreachable and unusable objects are available for garbage
collection but the garbage collection process doesn’t happen instantly. Which means once
the objects are ready for garbage collection they must to have to wait for JVM to run the
memory cleanup program that performs garbage collection. However you can request to
JVM for garbage collection by calling System.gc() method (see the example below).

Garbage Collection Example in Java


In this example we are demonstrating the garbage collection by calling System.gc(). In this
code we have overridden a finalize() method. This method is invoked just before a object
is destroyed by java garbage collection process. This is the reason you would see in the
output that this method has been invoked twice.

public class JavaExample{


public static void main(String args[]){
/* Here we are intentionally assigning a null
* value to a reference so that the object becomes
* non reachable
*/
JavaExample obj=new JavaExample();
obj=null;

/* Here we are intentionally assigning reference a


* to the another reference b to make the object referenced
* by b unusable.
*/
JavaExample a = new JavaExample();
JavaExample b = new JavaExample();
b = a;
System.gc();
}
protected void finalize() throws Throwable
{
System.out.println("Garbage collection is performed by JVM");
}
}
Output:

Garbage collection is performed by JVM


Garbage collection is performed by JVM

String:
String is a sequence of characters, for e.g. “Hello” is a string of 5 characters. In java, string
is an immutable object which means it is constant and can cannot be changed once it has
been created. In this tutorial we will learn about String class and String methods in detail
along with many other Java String tutorials.

Creating a String
There are two ways to create a String in Java
1. String literal
2. Using new keyword
String literal
In java, Strings can be created like this: Assigning a String literal to a String instance:
String str1 = "Welcome";
String str2 = "Welcome";
The problem with this approach: As I stated in the beginning that String is an object in
Java. However we have not created any string object using new keyword above. The
compiler does that task for us it creates a string object having the string literal (that we
have provided , in this case it is “Welcome”) and assigns it to the provided string instances.
But if the object already exist in the memory it does not create a new Object rather it
assigns the same old object to the new instance, that means even though we have two
string instances above(str1 and str2) compiler only created on string object (having the
value “Welcome”) and assigned the same to both the instances. For example there are 10
string instances that have same value, it means that in memory there is only one object
having the value and all the 10 string instances would be pointing to the same object.

What if we want to have two different object with the same string? For that we would need
to create strings using new keyword.

Using New Keyword


As we saw above that when we tried to assign the same string object to two different
literals, compiler only created one object and made both of the literals to point the same
object. To overcome that approach we can create strings like this:

String str1 = new String("Welcome");


String str2 = new String("Welcome");
In this case compiler would create two different object in memory having the same string.

Java String class methods


The java.lang.String class provides many useful methods to perform operations on
sequence of char values.
import java.lang.*;
class Main
{
public static void main(String ar[])
{
String s1=new String();
s1="ram sharma";
System.out.println(s1);
}
}

Length
import java.lang.*;
class Main
{
public static void main(String ar[])
{
String s1=new String("Ram Shrama");
int a=s1.length(); //int length()
System.out.println(a);
}
}
charAt
import java.lang.*;
class Main
{
public static void main(String ar[])
{
String s1=new String("Ram Shrama");
char a=s1.charAt(4);
System.out.println(a);
}
}
import java.lang.*;
class Main
{
public static void main(String ar[])
{
String s1=new String("Ram Shrama 123");
String a=s1.toUpperCase();
System.out.println(a);

String s2=new String("Amit 123");


String b=s2.toLowerCase();
System.out.println(b);

String s=" ajay abc ";


System.out.println(s);
String sb=s.trim();
System.out.println(sb);
}
}

import java.lang.*;
class Main
{
public static void main(String ar[])
{
String s1="ram";
String s2="Ram";
boolean b1=s1.equals(s2);
System.out.println(b1);
boolean b2=s1.equalsIgnoreCase(s2);
System.out.println(b2);
}
}
import java.lang.*;
class Main
{
public static void main(String ar[])
{
String s1="ram sharma";
String s2=s1.substring(4);
System.out.println(s2);
String s3=s1.substring(0,3);
System.out.println(s3);

}
}

import java.lang.*;
class Main
{
public static void main(String ar[])
{

String s1="ram mohan";


String s2=s1.replace('m','j');
System.out.println(s2);
}
}

import java.util.*;
class Main
{
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter any arithmetic expression");
String s=sc.next();
char op=s.charAt(2);
String s1=s.substring(0,2);
String s2=s.substring(3);
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
if(op=='+')
{
System.out.println("Sum is:"+(a+b));
}
if(op=='-')
{
System.out.println("Sub is:"+(a-b));
}
if(op=='*')
{
System.out.println("Multi is:"+(a*b));
}
if(op=='/')
{
System.out.println("Div is:"+(a/b));
}
if(op=='%')
{
System.out.println("Mod is:"+(a%b));
}

}
}
import java.util.*;
class Main
{
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter any arithmetic expression");
String s=sc.next();//234+3
int j=0;
char op=' ';
for(int i=1;i<s.length()-1;i++)
{
op=s.charAt(i);
if(op=='+'||op=='-'||op=='*'||op=='/'||op=='%')
{
j=i;
break;
}
}
String s1=s.substring(0,j);
String s2=s.substring(j+1);
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
if(op=='+')
{
System.out.println("Sum is:"+(a+b));
}
if(op=='-')
{
System.out.println("Sub is:"+(a-b));
}
if(op=='*')
{
System.out.println("Multi is:"+(a*b));
}
if(op=='/')
{
System.out.println("Div is:"+(a/b));
}
if(op=='%')
{
System.out.println("Mod is:"+(a%b));
}

}
}
import java.util.*;
class Main
{
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter any string");
String s1=sc.next();
System.out.println("enter any string");
String s2=sc.next();
int a=s1.length();
int b=s2.length();
if(a>b)
{
System.out.println(s1+" is greater length as compare to "+s2);
}
else if(b>a)
{
System.out.println(s1+" is greater length as compare to "+s2);
}
else
{
System.out.println("Both strings are equal");
}

}
}
import java.util.*;
class Main
{
public static void main (String[] args)
{
int i,j,l1,l2;
String s[]=new String[10];
Scanner sc=new Scanner(System.in);
System.out.println("enter any ten strings");
for(i=0;i<s.length;i++)
s[i]=sc.next();
for(i=0;i<s.length;i++)
{
for(j=i+1;j<s.length;j++)
{
l1=s[i].length();
l2=s[j].length();
if(l1>l2)
{
String t=s[i];
s[i]=s[j];
s[j]=t;
}
}
}
System.out.println("Sorted string according to length");
for(i=0;i<s.length;i++)
System.out.println(s[i]);
}
}

String Methods
Here is the list of methods supported by String class −

Sr.No Method & Description


.

1. char charAt(int index)

Returns the character at the specified index.

2. int compareTo(Object o)
Compares this String to another Object.

3. int compareTo(String anotherString)


Compares two strings lexicographically.

4. int compareToIgnoreCase(String str)


Compares two strings lexicographically, ignoring case differences.

5. String concat(String str)


Concatenates the specified string to the end of this string.

6. boolean contentEquals(StringBuffer sb)


Returns true if and only if this String represents the same sequence of characters as the
specified StringBuffer.

7. static String copyValueOf(char[] data)


Returns a String that represents the character sequence in the array specified.

8. static String copyValueOf(char[] data, int offset, int count)


Returns a String that represents the character sequence in the array specified.

9. boolean endsWith(String suffix)


Tests if this string ends with the specified suffix.

10. boolean equals(Object anObject)


Compares this string to the specified object.

11. boolean equalsIgnoreCase(String anotherString)


Compares this String to another String, ignoring case considerations.

12. byte getBytes()


Encodes this String into a sequence of bytes using the platform's default charset, storing
the result into a new byte array.

13. byte[] getBytes(String charsetName)


Encodes this String into a sequence of bytes using the named charset, storing the result
into a new byte array.

14. void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.

15. int hashCode()


Returns a hash code for this string.

16. int indexOf(int ch)


Returns the index within this string of the first occurrence of the specified character.

17. int indexOf(int ch, int fromIndex)


Returns the index within this string of the first occurrence of the specified character,
starting the search at the specified index.

18. int indexOf(String str)


Returns the index within this string of the first occurrence of the specified substring.

19. int indexOf(String str, int fromIndex)


Returns the index within this string of the first occurrence of the specified substring,
starting at the specified index.

20. int lastIndexOf(int ch)


Returns the index within this string of the last occurrence of the specified character.

21. int lastIndexOf(int ch, int fromIndex)


Returns the index within this string of the last occurrence of the specified character,
searching backward starting at the specified index.
22. int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.

23. int lastIndexOf(String str, int fromIndex)


Returns the index within this string of the last occurrence of the specified substring,
searching backward starting at the specified index.

24. int length()


Returns the length of this string.

25. boolean matches(String regex)


Tells whether or not this string matches the given regular expression.

26. boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.

27. boolean regionMatches(int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.

28. String replace(char oldChar, char newChar)


Returns a new string resulting from replacing all occurrences of oldChar in this string
with newChar.

29. String replaceAll(String regex, String replacement


Replaces each substring of this string that matches the given regular expression with the
given replacement.

30. String replaceFirst(String regex, String replacement)


Replaces the first substring of this string that matches the given regular expression with
the given replacement.

31. String[] split(String regex)


Splits this string around matches of the given regular expression.

32. String[] split(String regex, int limit)


Splits this string around matches of the given regular expression.

33. boolean startsWith(String prefix)


Tests if this string starts with the specified prefix.

34. boolean startsWith(String prefix, int toffset)


Tests if this string starts with the specified prefix beginning a specified index.

35. String substring(int beginIndex)


Returns a new string that is a substring of this string.
36. String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string.

37. char[] toCharArray()


Converts this string to a new character array.

38. String toLowerCase()


Converts all of the characters in this String to lower case using the rules of the default
locale.

39. String toString()


This object (which is already a string!) is itself returned.

40. String toUpperCase()


Converts all of the characters in this String to upper case using the rules of the default
locale.

41. String trim()


Returns a copy of the string, with leading and trailing whitespace omitted.

42. static String valueOf(primitive data type x)


Returns the string representation of the passed data type argument.

import java.util.*;
class Main
{
public static void main (String[] args)
{
String s="Rama sharma Indore wale";
char x[]=s.toCharArray();
for(char i:x)
System.out.println(i);
boolean b=s.endsWith("Am");
System.out.println(b);
boolean b1=s.startsWith("1r");
System.out.println(b1);
int a=10;
String s1=String.valueOf(a);
System.out.println(s1);
float t=102.36f;
String s2=String.valueOf(t);
System.out.println(s2);
int a=s.indexOf('a');
System.out.println(a);
a=s.lastIndexOf('a');
System.out.println(a);
String x[]=s.split("ma");
for(String p:x)
System.out.println(p);
}
}
import java.util.*;
class Main
{
public static void main (String[] args)
{
String s1="ram";
String s2="Ram";
int a=s1.compareTo(s2);
System.out.println(a);
a=s1.compareToIgnoreCase(s2);
System.out.println(a);

}
}
/*
s1>s2 +ve
s1<s2 -ve
s1==s2 zero */

Immutable String in Java


In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is created.

Let's try to understand the immutability concept by the example given below:

class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}
}
Output:Sachin
Now it can be understood by the diagram given below. Here Sachin is not changed but a new
object is created with sachintendulkar. That is why string is known as immutable.

As you can see in the above figure that two objects are created but s reference variable still refers
to "Sachin" not to "Sachin Tendulkar".
But if we explicitely assign it to the reference variable, it will refer to "Sachin Tendulkar"
object.For example:

class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
Test it Now
Output:Sachin Tendulkar
In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object is not
modified.
Why string objects are immutable in java?
Because java uses the concept of string literal.Suppose there are 5 reference variables,all referes to
one object "sachin".If one reference variable changes the value of the object, it will be affected to
all the reference variables. That is why string objects are immutable in java.

Java StringBuffer class


Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in
java is same as String class except it is mutable i.e. it can be changed.

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.

Important methods of StringBuffer class

Modifier and Method Description


Type

public append(String s) is used to append the specified string with this


synchronized string. The append() method is overloaded like
StringBuffer append(char), append(boolean), append(int),
append(float), append(double) etc.

public insert(int offset, String is used to insert the specified string with this string
synchronized s) at the specified position. The insert() method is
StringBuffer overloaded like insert(int, char), insert(int, boolean),
insert(int, int), insert(int, float), insert(int, double)
etc.

public replace(int startIndex, is used to replace the string from specified


synchronized int endIndex, String str) startIndex and endIndex.
StringBuffer

public delete(int startIndex, int is used to delete the string from specified startIndex
synchronized endIndex) and endIndex.
StringBuffer

public reverse() is used to reverse the string.


synchronized
StringBuffer

public int capacity() is used to return the current capacity.

public void ensureCapacity(int is used to ensure the capacity at least equal to the
minimumCapacity) given minimum.

public char charAt(int index) is used to return the character at the specified
position.

public int length() is used to return the length of the string i.e. total
number of characters.

public String substring(int is used to return the substring from the specified
beginIndex) beginIndex.

public String substring(int is used to return the substring from the specified
beginIndex, int beginIndex and endIndex.
endIndex)

import java.util.*;

class Main

public static void main (String[] args)

Scanner sc=new Scanner(System.in);

System.out.println("Enter any string");

String s=sc.next();

StringBuffer sb1=new StringBuffer(s);

sb1.reverse();
String s1=sb1.toString();

if(s.equalsIgnoreCase(s1))

System.out.println("Palindrome string");

else

System.out.println("Not palindrome string");

import java.util.*;

class Main

public static void main (String[] args)

Scanner sc=new Scanner(System.in);

System.out.println("Enter any string");

String s=sc.nextLine();

StringBuffer sb1=new StringBuffer(s);

/* int a=sb1.capacity();

System.out.println(a);*/

System.out.println(sb1.deleteCharAt(3));

System.out.println(sb1.delete(0,3));

System.out.println(sb1.append("3"));

}
}

StringBuilder class
Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder class is same as
StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.

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

Method Description

public StringBuilder is used to append the specified string with this string. The append()
append(String s) method is overloaded like append(char), append(boolean), append(int),
append(float), append(double) etc.

public StringBuilder insert(int is used to insert the specified string with this string at the specified
offset, String s) position. The insert() method is overloaded like insert(int, char),
insert(int, boolean), insert(int, int), insert(int, float), insert(int, double)
etc.

public StringBuilder replace(int is used to replace the string from specified startIndex and endIndex.
startIndex, int endIndex, String
str)

public StringBuilder delete(int is used to delete the string from specified startIndex and endIndex.
startIndex, int endIndex)

public StringBuilder reverse() is used to reverse the string.

public int capacity() is used to return the current capacity.

public void ensureCapacity(int is used to ensure the capacity at least equal to the given minimum.
minimumCapacity)

public char charAt(int index) is used to return the character at the specified position.
public int length() is used to return the length of the string i.e. total number of characters.

public String substring(int is used to return the substring from the specified beginIndex.
beginIndex)

public String substring(int is used to return the substring from the specified beginIndex and
beginIndex, int endIndex) endIndex.

THREADING
Multi-threading
Def. concurrent running of multiple tasks within a program
 A program may consist of many tasks that can run concurrently
 A thread is a flow of execution from beginning to end of a task
 Multiple threads run multiple CPUS
 Multiple threads can share a single CPU--- known as time sharing
o The operating system is responsible for scheduling and allocating resources for
threads
 Threading is an example of asynchronous programming
 Multithreading can make your program more responsive and interactive, as well as
enhance performance
 In java, each task is an instance of the Runnable interface, also called a runnable object
 a thread is essentially an object that facilitates the execution of a task

creating tasks and threads


 Tasks are objects
 To create a task you must first define a class for tasks
 A task class must implement the runnable interface
 The runnable interface contains a run method
 You need to implement the method run to tell the system how you thread is going to run

a template for developing a class Task


public class TaskClass implements Runnable
{
public TaskClass(…) // constructors
{…}

//implement the method run


public void run()
{
//tell the system how to run the custom thread
}

} //end the TaskClass

 A task must be executed in the thread.


 The thread class contains the constructors for creating threads and many useful methods
& controlling threads
 To create a task object:
o TaskClass task = new TaskClass();
 To create a thread for a task
o Thread thread = new Thread(task);
 You can then invoke the start method to tell the Java Virtual Machine that thread is ready
to run
class one extends Thread
{
public void run()
{
System.out.println("Ram");
}
}
class two extends Thread
{
public void run()
{
System.out.println("Shyam");
}
}
class three extends Thread
{
public void run()
{
System.out.println("Mohan");
}
}
class Main
{
public static void main (String[] args)
{
one o1=new one();
two t1=new two();
three th=new three();
o1.start();
t1.start();
th.start();
/*o1.run();
t1.run();
th.run();*/
}
}
class one extends Thread
{
public void run()
{
for(int i=1;i<=2;i++)
System.out.println("Ram");
}
}
class two extends Thread
{
public void run()
{
for(int i=1;i<=4;i++)
System.out.println("Shyam");
}
}
class three extends Thread
{
public void run()
{
for(int i=1;i<=6;i++)
System.out.println("Mohan");
}
}
class Main
{
public static void main (String[] args)
{
one o1=new one();
two t1=new two();
three th=new three();
o1.start();
t1.start();
th.start();
/*o1.run();
t1.run();
th.run();*/
}
}
class one extends Thread
{
int l;
String s;
one(int n,String p)
{
l=n;
s=p;
}
public void run()
{
for(int i=1;i<=l;i++)
System.out.println(s);
}
}
class Main
{
public static void main (String[] args)
{
one o1=new one(2,"ram");
one o2=new one(4,"shyam");
one o3=new one(5,"mohan");
o1.start();
o2.start();
o3.start();
}
}

major steps for creating a task, a thread, and starting the thread
public class Client
{
public void someMethod()
{
//create an instance of TaskClass
TaskClass task = new TaskClass(…);
//create a thread
Thread thread = new Thread(task);
//start the thread
thread.start(); //JVM will execute the task by invoking the task’s run method

} //end someMethod
} //end class Client

Example
Create a console program that has three tasks and three threads to run them.
 The first task prints the letter a 100 times
 The second task prints the letter b 100 times
 The third task prints the integers 1 to 100

Example implementation
//create a TaskClass called PrintChar
public char PrintChar implements Runnable
{
private char charToPrint;
private int times;
//constructors
public PrintChar(char c, int t) {
charToPrint =c;
times =t; }

//overriding the run method to tell the system what task to perform
public void run()
{
for (int i = 1; i <= times; i++)
{
System.out.print(charToPrint + “ ”);
}
} //end class

//Create a TaskClass called PrintNum for printing numbers from 1 to n for a given n
public class PrintNum() implements Runnable
{
private int lastNum;
public printNum(int n) { lastNum = n;}

//tell thread to how to run


public void run()
{
for (int ii = 1; ii <= lastNum; ii++)
{System.out.print(ii + “ “);
} //end method run
} //end class

//create a class to run the tasks in the main() method


public class Test
{
_________ main()
{
//create tasks
Runnable printA = new PrintChar(‘a’, 100);
Runnable printB = new PrintChar(‘b’, 100);
Runnable print100 = new PrintNum(100);
//create threads run tasks
Thread t1 = new Thread(printA);
Thread t2 = new Thread(printB);
Thread t3 = new Thread(print100);
//start threads
t1.start();
t2.start();
t3.start();
}
}
Sample output:
aaa1b2baaa34…
The thread class
 The thread class contains the constructors for creating threads for tasks, and methods for
controlling threads.
 Import java.lang.Runnable to use the Thread class.

Thread class
public class Thread
{
//constructors
public Thread(){…} //creates an empty thread
public Thread(Runnable task) {…} //creates a task for a specific task

//methods
public void start(){…} /*starts the thread that causes the run method to be invoked by the
JVM*/
public Boolean isAlive() {…} //test whether the thread is currently running
public void setPriority(int i) {…} /*sets priority p (ranging from 1(lowest)j to 10 (highest)) for
the thread*/
public void join() {…} //waits for this thread to finish
public void sleep(long milliseconds) {…} /*puts a thread to sleep for a specified time in
milliseconds*/
public void yield() {…} /*causes the thread to pause temporarily and allow other threads to
execute*/
public void interrupt() {…} //interrupts this thread (will be discussed in upper div. classes)
}

Note these methods are unstable and should be avoided:


 stop()
 suspend()
 resume()

There’s is another way to implement multithreading using the class thread instead of the runnable
interface (not recommended)
implementation of multiThreading using THREAD CLASs (Not recommended)
//CustomThread class
public class CustomThread extend Thread
{

Public CustomThread(…) {…}

//overriding the abstract method run


public void run() {…}
}

//Client class
public class Client
{

public void doSomething()
{

CustomThread th = new CustomThread(…);
th.start();

}
}
Using yield()
public void run()
{
For (int i = 0; i< lastNum; i++)
{
System.out.print(“ “ + i);
Thread.yield();
}
}

Every time a number is printed, the thread of the print100 task is yielded. So each number is
followed by
some characters.

Using sleep( int milliseconds)


 puts the thread to sleep for a specified time in milliseconds to allow other threads to
execute
 sleep method might throw an interruptexception
public void run()
{
try
{
for (int i = 0; i < lastNum; i++)
{
System.out.print(“ “ + i);
If (i >= 50)
{Thread.sleep(1);}
}
} //end try block
Catch(InterruptedException e)
{
}
} //end method

Using join()
 forces one thread to wait for another to finish
public void run()
{
Thread t4 = new Thread(new PrintChar(‘c’, 40));
t4.start();
Try
{
for(int i = 0; i < lastNum; i++)
{
System.out.print(“ “ + i);
if( i==50)
{t4.join();}
}
} //end try
Catch (InterruptedException e) {
}
A new thread4 is created. It prints character c 40 times. The numbers from 50 to 100 are printed
after
thread thread4 is finished.

Thread Priority
 If all runnable threads have the same priority, each is assigned an equal portion of CPU in
a circular queue. This is called a round-robin scheduling.
 You can increase and decrease thread priority using the setPriority(int) method.
o 1 (lowest) – 10 (highest)
o You can also use int constants
 MIN_PRIORITY = 1
 NORM_PRIORITY = 5
 MAX_PRIORITY = 10
o setPriority(5) and setPriority(NORM_PRIORITY) are equivalent
o The JVM always picks up the current runnable thread with the highest priority. A
lower priority thread can run only when no higher priority thread are running

Thread Pool
 Creating tasks and threads we learned are not efficient
Runnable task1 = new Task(task);
Thread t = new Thread (task1);
t.start();
 This approach is convenient for a single task execution but it isn’t efficient for a large
number of tasks because you have to create a thread for each task
o Starting a new thread for each task could limit the throughput and cause poor
performance
 A thread pool is ideal to manage the tasks
o Java provides:
 Executor interface- executing tasks in a thread pool
 To create an executor object use the static methods in the
Executors class
 ExecutorService interface- managing and controlling tasks

Executors Class
Methods
1. ExecutorService newFixedThreadPool (int numOfThreads)
2. ExecutorService newCachedThreadPool()

newFixedThreadPool

Creates a thread pool with a fixed number of threads executing concurrently. A thread might
be reused to execute another task after its current task is finished

newcachedthreadpool

Creates a thread pool that creates new threads as needed, but will reuse previously
constructed threads when they’re available
using a thread pool
Main
//create a fixed thread pool with a maximum of three threads
ExecutorService executor = Executors.newFixedThreadPool(3);
//submit runnable tasks to executor
executor.execute(new PrintChar(‘c’, 100));
executor.execute(new PrintChar(‘a’, 100));
executor.execute(new PrintNum(100));

Notes:
 the executor creates three threads to execute three tasks concurrently
 if we change the executor to create only one thread in the thread pool

ExecutorService executor = Executors.newFixedThreadPool(1);


 Then the three runnable tasks will be executed sequentially

if we use newCachedThreadPool
ExecutorService executor = Executors.newCachedThreadPool();
 New threads will be created for each waiting task, so all the tasks will execute
concurrently
 To shut down the executor uses the method shutdown
executor.shutdown();
class exp
{
public static void main(String ar[])
{
int a=0,b=0,c=0,d=0,e=0,f=0;
try
{
a=Integer.parseInt(ar[0]);
b=Integer.parseInt(ar[1]);
}
catch(ArrayIndexOutOfBoundsException ee)
{
System.out.println("Enter atleast two arguments");
}
catch(NumberFormatException ee)
{
System.out.println("String can't convert into integer");
}

c=a+b;
System.out.println("Sum= "+c);
d=a-b;
System.out.println("Sub= "+d);
try
{
e=a/b;
}
catch(ArithmeticException ee)
{
System.out.println("Zero can't divide any number");
}
System.out.println("Div= "+e);
f=a*b;
System.out.println("Multi= "+f);
}
}
class exp1
{
public static void main(String ar[])
{
int a=0,b=0,c=0,d=0,e=0,f=0;
try
{
a=Integer.parseInt(ar[0]);
b=Integer.parseInt(ar[1]);
e=a/b;
}
catch(Exception ee)
{
System.out.println("Wrong input value "+ee);
}
c=a+b;
System.out.println("Sum= "+c);
d=a-b;
System.out.println("Sub= "+d);
System.out.println("Div= "+e);
f=a*b;
System.out.println("Multi= "+f);
}
}
public class Main
{
public static void main(String[] args)throws Exception {
System.out.println("Hello World");
System.out.println(10/0);
Thread.sleep(1000);
System.out.println("Bye bye");

}
}
/*
1. reported/unchecked
2. unreported/checked
*/
import java.util.*;
public class Main
{
public static void main(String[] args)throws Exception {
Scanner sc=new Scanner(System.in);
System.out.println("Enter any number");
int a=sc.nextInt();
if(a==35)
{
ArithmeticException a1=new ArithmeticException();
throw a1;
}
else
{
System.out.println("Input value "+a);
}

}
}
import java.util.*;
class myexp extends Exception
{
public String toString()
{
String s1="This is user created & generated exception";
return s1;
}
}
public class Main
{
public static void main(String[] args)throws Exception {
Scanner sc=new Scanner(System.in);
System.out.println("Enter any number");
int a=sc.nextInt();
if(a==35)
{
try{
myexp a1=new myexp();
throw a1;
}catch(Exception ee)
{
System.out.println(ee);
}
}
else
{
System.out.println("Input value "+a);
}

}
}

You might also like