0% found this document useful (0 votes)
24 views240 pages

Ilovepdf Merged (1)

The document provides an introduction to Java programming, covering its history, advantages, features, and differences from C++. It explains the Java Development Kit (JDK), Java Runtime Environment (JRE), and Java Virtual Machine (JVM), as well as the concept of garbage collection and the structure of a simple Java program. Additionally, it outlines the types of Java programs (applications and applets) and the Java Standard Library (API) with its various packages.

Uploaded by

Siddhesh Rasane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views240 pages

Ilovepdf Merged (1)

The document provides an introduction to Java programming, covering its history, advantages, features, and differences from C++. It explains the Java Development Kit (JDK), Java Runtime Environment (JRE), and Java Virtual Machine (JVM), as well as the concept of garbage collection and the structure of a simple Java program. Additionally, it outlines the types of Java programs (applications and applets) and the Java Standard Library (API) with its various packages.

Uploaded by

Siddhesh Rasane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 240

Course: Java Programming Prepared By: Atul Kabra, 9422279260

Java Lecture-1
Topic: Chapter-1 Introduction

JAVA History:
 Java is certainly a good programming language. There is no doubt that it is
one of the better language available to serious programmers.

 Java is a general-purpose, object-oriented programming language


developed by Sun Microsystems of USA in 1991.

 Originally called Oak by James Gosling, one of the inventors of the


language, Java was designed for the development of software for consumer
electronics devices like TVs, VCRs, toasters and such other electronic
machines.

 This goal had a strong impact on the development team to make the
language simple, portable and highly reliable. The Java team, which
included Patrick Naughton, discovered that the existing languages like C
and C++ had limitations in terms of both reliability and portability.

 However, they modeled the new language Java on C and C++ but removed
a number of features of C and C++ that were considered as sources of
problems and thus made Java a really simple, reliable, portable, powerful
language.

 

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260


Advantage of JAVA:
 One obvious advantage is a runtime environment that provides platform
indepen-dence: you can use the same code on Windows, Solaris, Linux,
Macintosh, and so on.

 This is certainly necessary when programs are downloaded over the


Internet to run on a variety of platforms.

 Another programming advantage is that Java has a syntax similar to that of


C++, making it easy for C and C++ programmers to learn.

 Java is also fully object oriented — even more so than C++. Everything in
Java, except for a few basic types like numbers, is an object.

 The key point is this: It is far easier to turn out bug-free code using Java
than using C++.

 The Java designers eliminated manual memory allocation and deallocation.

 Memory in Java is automatically garbage collected. You never have to worry


about memory corruption.

 They introduced true arrays and eliminated pointer arithmetic.

 They eliminated multiple inheritance, replacing it with a new notation of


interface.

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

Java Lecture-2
Topic: Features of Java

Features of JAVA:
The inventors of Java wanted to design a language which could offer solutions to
some of the problems encountered in modern programming. They wanted the
language to be not only reliable, portable and distributed but also simple,
compact and interactive. Sun Microsystems officially describes Java with the
following features:

1. Simple, Small and Familiar


Java is simple language because there is no need for header files,
pointer arithmetic, structures, unions, operator overloading, virtual base
class etc.
Java Code is small as compared to any another programming language.
Familiarity is another striking feature of Java. To make the language look
familiar to the existing programmers, it was modeled on C and C++
languages. Java uses many constructs of C and C++ and therefore, Java
code "looks like a C+ + " code. In fact, Java is a simplified version of C+ +.

2. Object Oriented Programming


Almost everything in Java is in the form of Object. All program codes and
data reside within objects and classes.
Similar to other OOP languages, Java also has basic OOP properties such
as Encapsulation, Inheritance, Abstraction, Polymorphism, Data Hiding
etc.

3. Platform Independent
Java is platform independent because it is different from other
languages like C, C++, etc. which are compiled into platform specific
machines while Java is a write once, run anywhere language. A platform
is the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based.
Java provides a software-based platform.

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

The Java platform differs from most other platforms in the sense that it
is a software-based platform that runs on the top of other hardware-
based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming
Interface)
Java code can be run on multiple
platforms, for example, Windows,
Linux, Sun Solaris, Mac/OS, etc.
Java code is compiled by the compiler
and converted into bytecode. This
bytecode is a platform-independent
code because it can be run on
multiple platforms, i.e., Write Once and Run Anywhere(WORA).

4. Compiled and Interpreted


Usually a computer language is either compiled or interpreted. Java
combines both these approaches thus making Java a two-stage system.
First, Java compiler translates source code into what is known as
bytecode instructions.
Bytecodes are not machine instructions and therefore, in the second
stage, Java interpreter generates machine code, that can be directly
executed by the machine that is running the Java program.
We can thus say that Java is both a compiled and an interpreted
language.

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

5. Robust and Secure


Java uses strong memory management. The lack of pointers avoids
security problem. There is automatic garbage collection in Java. There is
exception handling and type-checking mechanism in Java.
It does not use pointer by which you can gain access to make memory
locations without proper authorization. In this sense, Java is Robust and
Secure.

6. Distributed
It is design as a distributed language for creating applications on
network. It has ability to share both data and program.
Java application can open and access remote objects on internet as
easily as they can do in local system.

7. Multithreaded
A thread is an independent path of execution within a program,
executing concurrently. Multithreaded means handling multiple tasks
simultaneously or executing multiple portions (functions) of the same
program in parallel.
This means that we need not wait for the application to finish one task
before beginning others.

8. Dynamic and Extensible


Java is a dynamic language. Java is capable of dynamically linking in new
class libraries, methods and objects.
Java programs support functions written in other languages such as C
and C++. These functions are known as native methods. This facility
enables the programmers to use the efficient functions available in
these languages. Native methods are linked dynamically at runtime.

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

Types of Java Programs


Java can be used to create two types of program.
1. Application
2. Applet

1. Application:
An application is a program that runs on your computer under the
operating system of that computer. That is, an application created by
Java is same as an application created in C and C++.
When java is used to create application, it is not much different from
any other computer language.

2. Applet
An applet is a java program designed to be transmitted over the internet
and executed by a java comp[atatible web browser.
Applets are program that requires a browser to run. Applet always
embedded in web page.

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

Java Lecture-3
Topic: Difference between C++ and Java
Types of Java Programs
Java can be used to create two types of program.
1. Application
2. Applet

1. Application:
An application is a program that runs on your computer under the
operating system of that computer. That is, an application created by
Java is same as an application created in C and C++.
When java is used to create application, it is not much different from
any other computer language.

2. Applet
An applet is a java program designed to be transmitted over the internet
and executed by a java comp[atatible web browser.
Applets are program that requires a browser to run. Applet always
embedded in web page.

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

Difference between Java and C++

C++ Java

C++ is platform Dependent Java is platform Independent.

C++ uses complier only Java uses Compiler and Interperter

It supports preprocessors. Like It does not supports preprocessors. Like


#include, #define etc #include, #define etc
It supports pointers. It does not support pointers.

It support multiple inheritance of It dose not supports multiple inheritance


classes. of classes.
It does not support structures and
It support structures and unions.
unions.

It support operator overloading. It dose not support operator overloading.

It does not have built in support for


It has built in support for thread.
thread.
It supports friend function and friend It does not support friend function and
classes. friend classes.
It support global variable. It does not support global variable.

It support destructor. It does not support destructors.

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

Java Environment : (JDK)


Java environment includes a large number of development tools and
hundreds of classes and methods. The development tools are part of the
system known as Java Development Kit (JDK) and the classes and methods
are part of the Java Standard Library, also known as the Application
Programming Interface (API).

Java Development Kit


The Java Development Kit comes with a collection of tools that are used for
developing and running Java programs. They include

 javac (Java compiler)


 java (Java Interpreter)
 appletviewer (for viewing Java applets)
 javadoc (for creating HTML documents)
 jdb ( Java debugger)
The way these tools are applied to build and run application program is
illustrated in following figure. To create a Java program, we need to create
a source code file using a text editor. The source code then compiled using
the Java Compiler javac and executed using the Java Interpreter java. The
java debugger jdb is used to find errors, if any, in the source code.

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

Text Editor

Java Source Code javadoc HTML Files

Javac Compiler

Java Header
Class javah
Files
File

java Interpreter

Java
Program
Output

Application Programming Interface


The Java Standard Library (or API) includes hundreds of classes and
methods grouped into several functional packages. Most commonly used
packages are
1. Language Support Package (java.lang) :
A collection of classes and methods required for implementing basic
feature of Java.

2. Utilities Package (java.util) :


A collection of classes to provide utility functions such as Date and Time,
Collection Classes such as Stack, Queue, LinkedList etc.

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

3. InputOut Package (java.io) :


A collection of classes required for input and output manipulation.

4. Networking Package (java.net) :


A collection of classes for communicating with other computers via
Internet.

5. AWT Package (java.awt):


The abstract window toolkit package contains classes that implements
platform independent graphical user interface.

6. Applet Package(java.applet) :
This includes a set of classes that allows us to create Java applets.

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

Java Lecture-4
Topic: JDK, JRE, JVM, GC, Bytecode

JDK (Java Development Kit) :


 It is a software development environment which is used to develop
Java application and applets.
 It contains JRE + JDK tools.

JRE (Java Runtime Environment) :


 It is a set of software Tools which are used for executing Java
Application. It is used to provide Runtime environment.
 It is the implementation of JVM.
 It contains set of libraries plus other files that JVM uses at run-time.

JVM (Java Virtual Machin) :


 It is a specification that provides run-time environment in which Java
byte code can be executed.
 JVM's are available for many hardware and software platform.
 The JVM performs following operations.
(1) Loads the Java Code
(2) Verifies code
(3) Executes code

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

Following Figure Shows structure of JDK, JRE and JVM

JDK = JRE + Development Tools


JRE = JVM + Libraries

Byte Code :
 In Java Byte Code is an intermediate code generated by the Java
compiler.
 It is executed by JVM.
 Byte code is a compiled format of Java Program and it has (.class)
extension.

Java compiler translates source code into byte code instruction.

Java Source Byte Code


Code (Class file)
Compiler
Hello.java Hello.class

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

Garbage Collector (GC) :


 Garbage collection is a process in which the memory allocated to objects,
which are no longer in use can be freed for further use.
 Garbage collector runs automatically when the system is out of memory or
ideal. In Java, it is performed automatically, so it provides better

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

Java Lecture-5
Topic: Chapter-2 Beginning With Java

Java First Program:


Let's look more closely at about the simplest Java program you can have—one :
simply prints a message to the console window:

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

 First and foremost, Java is case sensitive. If you made any mistakes in
capitalization (such as typing Main instead of main), the program will not
run.

 The keyword class is there to remind you that everything in a Java program
lives inside a class.

 You need to make the file name for the source code the same as the name
of the class, with the extension .java appended. Thus, we must store this
code in a file called First.java

 System.out.println() is java’s console output statement.

Compiling the Program:


To compile the program, we must run the java compiler, with the name of
the source file on the command line as shown below
javac First.java

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

If everything is Ok, the javac compiler creates a file called First.class


containing the byte code of the program. Note that the compiler
automatically names the bytecode file as
<classname>.class

Running the Program:


We need to use the Java interpreter to run the program. At the command
prompt, type
java First
Now, the interpreter looks for the main method in the program and begins
execution from there. When the program executes, it simply displays the
string Hello Java World on the console.
In this case, we are calling the println method and passing it a string
parameter. The method displays the string parameter on the console. It
then terminates the output line so that each call to println displays its
output on a new line.

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

Setting Java Path:


Following are the steps to set Java Path
1) Right click on bin folder and copy the address

2) Right Click on My Computer and select Properties

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

3) Select Advanced System Settings

4) Select Environment Variables

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

5) Click on New Button

6) Type variable name as Path and Paste the bin folder address by
clicking right click and selecting paste menu.

7) Click on ok - ok - ok

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

Java Lecture- 6
Topic: Primitive Data Types in Java And Operators

Variable:
 Variables are nothing but reserved memory locations to store values.
 This means that when you create a variable you reserve some space in the
memory.
 Based on the data type of a variable, the operating system allocates
memory and decides what can be stored in the reserved memory.
Therefore, by assigning different data types to variables, you can store
integers, decimals, or characters in these variables.

Primitive Data Type in Java:


 There are eight primitive datatypes supported by Java.
 Primitive datatypes are predefined by the language and named by a
keyword.
 Primitive Data type of Java are given in the following Table
Data Type Memory Range
A Integers
byte 1 byte -128 to + 127 (27)
short 2 bytes - 32768 to + 32767 (215)
int 4 bytes -2147483648 to + 2147483648 (231)
long 8 bytes (263)
B Real Nos.
float 4 bytes 3.34 e -38 to 3.34 e +38
double 8 bytes 1.7 e -308 to 1.7 e +308
C Character
char 2 bytes Unicode (216)
D Boolean
boolean 1 bit true, false

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

Operators:
 Operators are special symbol which represents particular operation in
program.
 Java provides a rich set of operators to manipulate variables. We can divide
all the Java operators into the following groups.

Arithmetic Operators:
In Java there are five arithmetic operators they are as follows
+ Addition
- Substraction
* Multiplication
/ Division (Gives Quotient)
% Modulus (Gives Remainder)

Relational Operator:
In Java there are six relational operators. Relational operators always
evaluate either true or false. Following are the relational operators
< Less than
> Greater than
<= Less than or equals to
>= Greater than or equals to
== Equals to
!= Not Equal to

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

Logical Operators:
Logical operators are use to take a decision from more than one condition.
Or They are use combine multiple condition. There are three logical
operators in Java. They are as follows
Operator Name Description
&& Logical Returns true if both statements are
and true
|| Logical or Returns true if one of the statements
is true
! Logical Reverse the result, returns false if the
not result is true

Increment And Decrement Operator:


++ Increment Operator , It increments the value of variable by one.
-- Decrement Operator, It decrements the value of variable by one.

Bit wise Operator:


There are seven bitwise operators in java.
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise NOT
<< Left shift
>> Right shift
>>> Right shift with zero fill.

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

Conditional Operator:
 The conditional operator is also known as the ternary operator.
 This operator consists of three operands and is used to evaluate Boolean
expressions.
 The goal of the operator is to decide; which value should be assigned to
the variable. The operator is written as:
 Syntax:
Variable = (Boolean expression) ? value if true : value if false;
 For example following program finds maximum between two numbers
using ternary operator
class Test
{
public static void main(String [] args)
{
int x=10,y=20,max;
max = (x>y) ? x : y;
System.out.println(“Max=”+max);
}
}

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

Java Lecture-7
Topic: Type Casting Operator

Type casting is nothing but assigning a value of one primitive data type to
another.
The cast is performed by placing the desired type in parenthesis to the left of
the value to be converted.
For Ex :
int n = (int) 23.135; // converts double (23.135) to an integer
Destina Source
tion
Rules in type casting
(a) If source and destination of the same type. No casting is required.
(b) If source is of smaller size than destination then no casting is
required.
e.g. int to long or float to double
(c) If destination is of smaller size than source then casting is
required.
e.g. long to int or double to float

There are two types of casting in Java as follows:


 Widening Casting (automatically) – This involves the conversion of a
smaller data type to the larger type size.

byte -> short -> char -> int -> long -> float -> double

 Narrowing Casting (manually) – This involves converting a larger


data type to a smaller size type.

double -> float -> long -> int -> char -> short -> byte

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

Widening Casting:
This type of casting takes place when two data types are automatically
converted. It is also known as Implicit Conversion.
This happens when the two data types are compatible and also when we
assign the value of a smaller data type to a larger data type.
For Example int type to long type or float type to double type.

Narrowing Casting:
In this case, if you want to assign a value of larger data type to a smaller
data type, you can perform Explicit type casting or narrowing.

For Example long type to int type or double type to float type.

This is useful for incompatible data types where automatic conversion


cannot be done.

Following program demonstrate type casting. It converts character type


to an integer type.
class Test
{
public static void main(String []args)
{
int x=65;
char ch;

ch= (char)x; //narrowing requires casting

System.out.println(ch);
}
}

Output: A

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

Java Lecture- 8
Topic: Reading Input from Console

Reading Input using Scanner class:


The Scanner class is used to get user input, and it is found in
the java.util package.
To use Scanner inside your program then you have to import
java.util package.
To use the Scanner class, create an object of the class and
use any of the following method to read primitive type of
input like int ,float etc.

Methods of Scanner Class


Method Description
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the
user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the
user

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

1. In the following program, we use different methods to read


data of various types:
import java.util.Scanner;

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

System.out.println("Enter name, age and salary:");

// String input
String name = myObj.nextLine();

// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();

// Output input by user


System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
Output

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

2. Program to read a number and then find its square


import java.util.*;

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

int n,s;

System.out.println("Enter the number ");


n= in.nextInt();

s=n*n;

System.out.println("Sqaure = "+s);
}
}

Output

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

3. Program to read two numbers and then print their addition.

import java.util.*;
class Addition
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);

int x,y,add;

System.out.println("Enter two numbers ");


x = in.nextInt();
y = in.nextInt();

add=x+y;

System.out.println("Addition="+add);
System.out.println("Addition of "+x+" and "+ y +" is "+add);
System.out.println(x + "+" + y +" = "+add);
}
}

Output:

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming Prepared By: Atul Kabra, 9422279260

Java Lecture-9 Notes


Topic: Control Structures in Java (Part-A)

Control Structures are just a way to specify flow of control in programs.

Control Structures

Decision Control Loop Control


Structure Structure

 If  for
 If..else  while
 Nested If else  do..while
 Switch case  for..each

Using decision control statements we can control the flow of program in


such a way so that it executes certain statements based on the outcome of
a condition (i.e. true or false).

In Java Programming language we have following decision control


statements.
Course: Java Programming Prepared By: Atul Kabra, 9422279260

if
 if statement is the most simple decision making statement.
 It is used to decide whether a certain statement or block of
statements will be executed or not
 i.e if a certain condition is true then a block of statement is executed
otherwise not.
 Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}

Program to find out number is +ve or –ve


import java.util.*;
class PN
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the number ");
int n = in.nextInt();

if(n>0)
System.out.println(n+" is +ve number ");

if(n<0)
System.out.println(n+ " is -ve number ");
}
}
OUTPUT
Course: Java Programming Prepared By: Atul Kabra, 9422279260

if-else:
 In if else, if the condition is true then if part is executed and if
condition is false then else part is executed.
 We can use the else statement with if statement to execute a block
of code when the condition is false.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}

Program to find out number is +ve or –ve using if..else


import java.util.*;

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

System.out.println("Enter the number ");


int n = in.nextInt();

if(n>0)
System.out.println(n+" is +ve number ");
else
System.out.println(n+ " is -ve number ");

}
}
Course: Java Programming Prepared By: Atul Kabra, 9422279260

nested-if:
 A nested if is an if statement that is the target of another if or else.
 Nested if statements means an if statement inside an if statement.
 Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}

Program to find out number maximum between three numbers.

import java.util.*;
class MaxThree
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);

System.out.println("Enter three numbers ");


int x = in.nextInt();
int y = in.nextInt();
int z = in.nextInt();

if(x>y)
{
if(x>z)
System.out.println("Max = "+x);
else
System.out.println("Max = "+z);
}
else
{
Course: Java Programming Prepared By: Atul Kabra, 9422279260

if(y>z)
System.out.println("Max = "+y);
else
System.out.println("Max = "+z);
}
}
}

OUTPUT:

if-else-if ladder:
 Here, a user can decide among multiple options.
 The if statements are executed from the top down.
 As soon as one of the conditions controlling the if is true, the
statement associated with that if is executed, and the rest of the
ladder is bypassed.
 If none of the conditions is true, then the final else statement will be
executed.
 Syntax

if (condition)
Course: Java Programming Prepared By: Atul Kabra, 9422279260

statement;
else if (condition)
statement;
.
.
else
statement;
Course: Java Programming Prepared By: Atul Kabra, 9422279260

switch-case

 The switch statement is a multiway branch statement.


 It provides an easy way to dispatch execution to different parts of
code based on the value of the expression.
 Syntax:

switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}

Points About Switch case:

 Dulplicate case values are not allowed.


 The default statement is optional.
 The break statement is used inside the switch to terminate a statement
sequence.
 The break statement is optional. If omitted, execution will continue on into
the next case.
Course: Java Programming , Prepared By: Atul Kabra, 9422279260

Java Lecture-10 Notes


Topic: Control Structure Part B

Loop Control Structure


 In programming languages, loops are used to execute a set of
instructions/functions repeatedly when some conditions become true.

 There are types of loops in Java.


 for loop
 while loop
 do-while loop

 The java for loop is used to iterate a part of the program several times. If
the number of iteration is fixed, it is recommended to use for loop.

 The java while loop is used to iterate a part of the program several
times. If the number of iteration is not fixed, it is recommended to use
while loop.

 The java do-while loop is used to iterate a part of the program several
times. Use it if the number of iteration is not fixed and you must have to
execute the loop at least once.
Course: Java Programming , Prepared By: Atul Kabra, 9422279260

For Loop:

Syntax:
for(initialization; condition; incr/decr)
{
//statement or code to be executed
}

 for loop is the same as C/C++. We can initialize the variable, check
condition and increment/decrement value.

 It consists of four parts:


o Initialization: It is the initial condition which is executed once
when the loop starts.
o Condition: It is the second condition which is executed each
time to test the condition of the loop.
It continues execution until the condition is false.
o Statement: The statement of the loop is executed each time
until the condition is false.
o Increment/Decrement: It increments or decrements the
variable value.
Course: Java Programming , Prepared By: Atul Kabra, 9422279260

Programs on For Loop:

1) Write a program to print Multiplication Table of 2.


class Table2
{
public static void main(String [] args)
{
for(int i=2;i<=20;i=i+2)
{
System.out.println(i);
}
}
}
Output:
Course: Java Programming , Prepared By: Atul Kabra, 9422279260

2) Write a program to print Multiplication Table of number (n).


import java.util.*;

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

int n,i;
System.out.println("Enter the number ");
n= in.nextInt();
System.out.println("Multiplication Table of "+ n);

for(i=1;i<=10;i++)
{
System.out.println(n*i);
}
}
}
Output:
Course: Java Programming , Prepared By: Atul Kabra, 9422279260

3) Write a program to print all numbers divisible by 7 between 100 to 200


class Div7
{
public static void main(String [] args)
{
int i;

System.out.println("Nos divisible by 7 between 100 to 200


are as follows");

for(i=100;i<=200;i++)
{
if(i%7==0)
System.out.println(i);
}
}
}
Output:
Course: Java Programming , Prepared By: Atul Kabra, 9422279260

4) Write a program to find sum of 1 to n numbers. Read value of n from


user.
import java.util.*;

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

int n,i,sum=0;
System.out.println("Enter the number ");
n= in.nextInt();

for(i=1;i<=n;i++)
{
sum=sum+i;
}

System.out.println("Sum="+sum);
}
}
Output:
Course: Java Programming , Prepared By: Atul Kabra, 9422279260

5) Write a program to find the factorial of number n.


import java.util.*;

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

int n,i,fact=1;
System.out.println("Enter the number ");
n= in.nextInt();

for(i=1;i<=n;i++)
{
fact=fact*i;
}

System.out.println("Factorial="+fact);
}
}
Output:
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-11
Topic: break statement , while loop

break Statement:
 The break statement has the following two usages

 When a break statement is encountered inside a loop, the loop is


immediately terminated and the program control resumes at the next
statement following the loop.

 It can be used to terminate a case in the switch statement.

 If you are using nested loops, the break statement will stop the
execution of the innermost loop and start executing the next line of
code after the block.

 Syntax The syntax for a break statement is as follows

break;

 Example Output:
class Test
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
System.out.println(i);

if(i==5)
break;
}
}

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Write a Program to read a number and then find whether it is


prime or not prime.
import java.util.*;

class Prime
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
int n,i;
System.out.println("Enter the number ");
n = in.nextInt();

for(i=2; i<n; i++)


{
if(n%i==0)
{
System.out.println(n +" is not a prime number ");
break;
}
}
if(i==n)
System.out.println(n+" is a prime number ");
}
}
Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

While Loop :
 Loops are used to execute a set of statements repeatedly until a
particular condition is satisfied.

 Syntax of while loop

while(condition)
{
statement(s);
}

 In while loop, condition is evaluated first and if it returns true then the
statements inside while loop execute.

 When condition returns false, the control comes out of loop and jumps
to the next statement after while loop.

 If the number of iteration is not fixed, it is recommended to use while


loop.

 Example: Following Program will print “Info Planet” 5 times.

class Test
{
public static void main(String[] args)
{
int i=1;
while(i<=5)
{
System.out.println("Info Planet");
i++;
}
}
}

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Programs on while loop.


1) Write a program to find sum of digits of number.
import java.util.*;

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

int n, r, sum=0;

System.out.println("Enter the number ");


n = in.nextInt();

while(n!=0)
{
r=n%10;
sum=sum+r;
n=n/10;
}
System.out.println("Sum of Digits = "+sum);
}
}
Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

2) Write a program to read a number and then find out whether it is


palindrome number or not.
import java.util.*;

class PalindromeNumber
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
int n, r, rev=0,temp;
System.out.println("Enter the number ");
n = in.nextInt();

temp=n;

while(n!=0)
{
r=n%10;
rev = rev*10+r;
n=n/10;
}

if(temp==rev)
System.out.println(temp+" is Palindrome Number");
else
System.out.println(temp+" is not a Palindrome Number");
}
}
Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-12 Notes


Topic: do-while loop and Nested loop

do-while :
 Unlike for and while loops, which test the loop condition at the top of
the loop, the do...while loop checks its condition at the bottom of the
loop.

 A do...while loop is similar to a while loop, except the fact that it is


guaranteed to execute at least one time.

 Syntax

do {
statement(s);
} while( condition );

 Notice that the Boolean expression appears at the end of the loop, so
the statements in the loop execute once before the Boolean is
tested.

 If the Boolean expression is true, the control jumps back up to do


statement, and the statements in the loop execute again. This
process repeats until the Boolean expression is false.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Following program which prints “Info Planet” using do-while loop.

class DoWhile
{
public static void main(String args[])
{
int i=1;

do{
System.out.println(i + " Info Planet");
i++;
}while(i<=10);
}
}
Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Difference Between while and do-while loop

while do-while
While loop is executed only when given Whereas, do-while loop is executed
condition is true. for first time irrespective of the
condition. After executing while
loop for first time, then condition is
checked.
While is entry controlled loop. do-while is exit controlled loop.
In while loop condition is checked at In do-while condition is checked at
top of loop. bottom of loop.
Syntax : Syntax:
while(condition){ do{
Statement(s); Statement(s);
} }while(condition);

For Each loop:


 The For each loop is introduced in Java 1.5 version.

 It is mainly used to traverse array or collection of elements.

 The advantage of each loop is that its elements the possibility of error
and makes the code more readable.

 Syntax

for( data_type variable : array (collection)


{
//process variable
}

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

 Example : Following program prints array elements using for-each loop.

class ForEach
{
public static void main(String args[])
{
int [] a = {10,20,30,40,50};

for(int x : a)
{
System.out.println(x);
}
}
}
Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Nested Loop:
 Nesting of loops is the feature in Java that allows the looping of
statements inside another loop.

 Any number of loops can be defined inside another loop, i.e., there is no
restriction for defining any number of loops.

 The nesting level can be defined at n times. You can define any type of loop
inside another loop; for example, you can define 'while' loop inside a 'for'
loop.

 Syntax

for (initialization; condition; update)


{
for(initialization; condition; update)
{
// inner loop statements.
}
// outer loop statements.
}

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Write a program to print following output up to n lines. Read


value of n from user.
import java.util.*;

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

System.out.println("Enter the number ");


int n = in.nextInt();

for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print("*");
} // end of inner for
System.out.println();
}// end of outer for
}
}
Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-13
Topic: String class

String:
 Strings are sequence of characters or collection of characters.
 Java does not have a built-in string type instead the standard java library
contains a pre-defined class called "String"
 "String" class is declared in "java.lang" package.
 Java string is immutable (not changeable).
 Each quoted string is an object of the String class:
String e = ""; // an empty string
String greeting = "Hello" ;

String Concatenation :
Java allows you to use '+' sign to concatenate two strings together.
For Ex.:
(a) We can concatenate two strings using +
e.g. String s1 = "Info Planet", s2 = "Jalgaon",s3;
String s3=s1+s2;

(b) We can also concatenate any other type value to String.


e.g. int x = 10, y = 20, S;
s = x + y;
(i) System.out.prinln ("Addition = " + s);
Output: Addition = 30

(ii) System.out.println ("Sum of " + x + " and "+y+" is " + s);


Output: Sum of 10 and 20 is 30.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-14
Topic: Constructor and Methods of String Class

Constructor of String class :


1. String()
Initializes a newly created String object so that it represents an empty
character sequence.

2. String(byte[] bytes)
Constructs a new String by decoding the specified array of bytes using the
platform's default charset.

3. String(char[] value)
Allocates a new String so that it represents the sequence of characters
currently contained in the character array argument.

4. String(StringBuffer buffer)
Allocates a new string that contains the sequence of characters currently
contained in the string buffer argument.

Methods of String class :


1. length ( )
This method is used to find the length of the string
Syntax : int length ( );
Example: String s = "Hellow world";
int x = s.length ( );
System.out.println ("Length of string = "+x);
Output: Length of string = 11

2. charAt ( )
This method returns the character from specified index of the string
Syntax : char charAt (int index)

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Example: String s = "Hello World";


char ch = s.charAt(6);
System.out.println ("ch="+ch);
Output: ch = W

3. indexOf()
This method is used to find the index of character in the String. It is
overloaded.
(a) indexOf ( )
This method returns an index of first occurrences of character in
the string. If character is not present in the string, then it returns -1.
Syntax : int indexOf (char ch)
For ex : String s = "Hello World";
int x = s.indexOf ('o');
System.out.prinln ("x=" +x);
Output: x=4

(b) indexOf (string str)


Returns the index within the string of the first occurrence of
specified string, otherwise returns -1.
Syntax : int indexOf(String str)
Example: String s="Info Planet Jalgaon";
int x = s.indexOf("Planet");
System.out.println("x="+x);
Output: x=5

4. lastIndexOf ( )
Returns the index within the string of the last occurrence of the
specified character.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Syntax : int lastIndexOf (char ch)


Example: String s=”Hello World”;
Int x = S.lastIndexOf(‘l’);
System.out.println(“x=”+x);
Output: x=9

5. equals ( )
This method compares two strings for equality. Returns True, if strings
are equal, otherwise returns false.
Syntax : boolean equals (String other)
For ex : String s1 = "Hello", s2 = "Info";
If (s1.equals (s2))
System.out.println ("strings are equal");
else
System.out.println ("strings are not equal");
Output: Strings are not equal.

6. equalsIgnoreCase ( )
This method compares two strings for equality, ignoring case consideration.
Syntax : boolean equalIgnoreCase (String other)
For ex : String s1 = "Hello", s2 = "HELLO";
if (s1.equalsIgnoreCase (s2))
System.out.println ("Strings are equal");
else
System.out.println ("Strings are not equal");
Output: Strings are equal

7. compareTo ( )

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

This method compares two strings lexicographically (character by


character) the comparison is based on the Unicode value of each
character in the string.
(i) This method returns < 0, if first string is smaller than second.
(ii) It returns > 0, if first string is greater than second string.
(iii) It returns 0 , if both strings are equal.
Syntax: int compareTo (String other)
For Ex: String s1=”abc”,s2=”info”;
int x = s1.compareTo (s2);
if (x <0)
System.out.println ("s1 is smaller");
if(x>0)
System.out.println ("s2 is smaller");
If(x==0)
System.out.println(“ Both strings are equal”);
Output: s1 is smaller

8. endsWith ( )
Test if the string ends with specified string.
Syntax : boolean endsWith (String str)
For Ex. : String s = "[email protected]";
if (s.endsWith ("gmail.com"))
System.out.println(“Gmail Account”);
else
System.out.println(“Not a Gmail Account”);
Output: Gmail Account

9. startsWith ( )

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

This method test if the string starts with specified string


Syntax : boolean startsWith (String str)
For Ex. : String s = "[email protected]";
if(s.startsWith ("gmail.com"))
…………
else
………..

10. getBytes ( )
Rerutns the string into a sequence of bytes using platforms default
character set.
Syntax : byte[] getBytes()
For Ex: String str = "Hello";
byte [ ] b = str.getBytes ( ) ;

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

11. toLowerCase ( )
Converts all the Upper Case letters of the string in to lower case
Syntax : String toLowerCase ( )

12. toUpperCase( )
Converts all the lowerCase letters of the string into Uppercase.
Syntax : String toUpperCase ( )

13. trim( )
Removes any leading and trailing spaces from String.
Syntax: String trim()

14. substring ( )
This method returns a string that is a substring of this string.
substring ( ) method has two forms :
(a) Syntax: String substring (int beginindex)
This method returns a substring from begin index up to
end of string.
(b) Syntax: String substring (int beginindex, int endindex)
This method returns substring from begin index up to end
index-1 because End index is exclusive.
For ex. : String s ="Info Planet";
String t = s.substring (5);
String p = s.substring(5,9);
System.out.println(t);
System.out.println (p);
Output: Planet
Plan

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-15 Notes


Topic: Programs On String

1) Write a program to find length of String.


import java.util.*;

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

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


String str = in.nextLine();

int x = str.length();

System.out.println("Length of String = "+x);


}
}

Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9579460114
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

2) Write a program to count vowel of the string.


import java.util.*;

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

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


String str = in.nextLine();

int c=0;
for(int i=0;i<str.length();i++)
{
char ch = str.charAt(i);
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
c++;
}

System.out.println("Vowels in String = "+c);


}
}

Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9579460114
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

3) Write a program to find out String is palindrome or not palindrome.


import java.util.*;

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

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


String str = in.nextLine();

String rev="";

for(int i=str.length()-1;i>=0;i--)
{
char ch = str.charAt(i);
rev=rev+ch;
}

if(str.equals(rev))
System.out.println(str+ " is Palindrome String");
else
System.out.println(str+ " is not a Palindrome String");
}
}

Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9579460114
Course: Java Programming,Prepared By: Atul Kabra, 9422279260

Java Lecture- 16
Topic: StringBuffer Class

 Java provides the String and StringBuffer classes to handle String.

 The String class is used to manipulate character strings that cannot be


changed. The string which cannot be changed is called as immutable string.

 The StringBuffer class is used to represent character String that can be


changed after it is created. The string which can be changed is called as
mutable string.

 StringBuffer represents growable and writable character sequence.

 The significant performance difference between these two classes is


that StringBuffer is faster than String when performing simple
concatenations.

Constructors of StringBuffer class


StringBuffer defines 4 constructors.

1. StringBuffer(): It creates an empty string buffer and reserves space for 16


characters.

2. StringBuffer(int size): It creates an empty string and takes an integer


argument to set capacity of the buffer.

3. StringBuffer(String str): It creates a stringbuffer object from the specified


string.

4. StringBuffer(char []ch): It creates a stringbuffer object from the


charsequence array.

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming,Prepared By: Atul Kabra, 9422279260

Methods of StringBuffer class:


1. append()
This method will concatenate the string representation of any type of data
to the end of the StringBuffer object. append() method has several
overloaded forms.
Syntax: StringBuffer append(T value)
Here T can be any type like String, int , float, char etc.
Example: StringBuffer sb = new StringBuffer(“HelloWorld”);
sb.append(“Java”);
System.out.println(sb);
Ouput: HelloWorldJava

2. insert()
This method inserts one string into another.
Syntax: StringBuffer insert(int index, T value)
Here the first parameter gives the index at which position the
string will be inserted and T representation of second
parameter is inserted into StringBuffer object.
Here T can be any type like String, int , float, char etc.
Example: StringBuffer sb = new StringBuffer(“HelloWorld”);
sb.insert(5, “Java”);
System.out.println(sb);
Ouput: HelloJavaWorld

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming,Prepared By: Atul Kabra, 9422279260

3. delete ()
This method removes the characters from the string.
Syntax: StringBuffer delete (int start, int end)
This method is used to delete the string from specified
startIndex and endIndex. Here endindex is exclusive.
Example: StringBuffer sb = new StringBuffer(“HelloJavaWorld”);
sb.delete(5,9);
System.out.println(sb);
Ouput: HelloWorld

4. deleteCharAt()
This method removes the character at the specified index character from
the string.
Syntax: StringBuffer deleteCharAt (int index)
Example: StringBuffer sb = new StringBuffer(“HelloWorld”);
sb.deleteCharAt(4);
System.out.println(sb);
Ouput: HellWorld

5. replace ()
This method replaces the specified string from specified start index to the
end index.
Syntax: StringBuffer replace (int start, int end, String newString)
Example: StringBuffer sb = new StringBuffer(“HelloJavaWorld”);
sb.replace(5,9,”InfoPlanet”);
System.out.println(sb);
Ouput: HellInfoPlanetWorld

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming,Prepared By: Atul Kabra, 9422279260

6. reverse()
This method reverses the characters within a StringBuffer object.
Syntax: StringBuffer reverse ()
Example: StringBuffer sb = new StringBuffer(“HelloWorld”);
sb.reverse();
System.out.println(sb);
Ouput: dlroWolleH

Note: Refer Java API documentation for more methods.

Difference between String and StringBuffer.

Sr. String StringBuffer


No.
1 Characters of String cannot be Characters of StringBuffer can be
changed. changed.
2 String is immutable. StringBuffer is mutable.
3 Processing of String is slow. Processing of StringBuffer is fast.
4 At the time of String concatenation, At the time of String
String consumes more memory concatenation, StringBuffer
space. consumes less memory space.

Course: Java Programming Prepared By: Atul Kabra, 9422279260


Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-18
Topic: Array

 An array is a data structure that stores a collection of values of the same type.
 You can access each individual vale through an integer index.
 The first element of array is at 0th index, second is at 1st index and so on…
 In Java, array is manipulated by reference variable of appropriate type.
 Syntax to create an Array:

datatype [ ] ref_name = new datatype [size];

e.g. int [ ] a = new int [5]; float [ ] b = new float [3];

a 0 0 0 0 0 b 0.0 0.0 0.0


0 1 2 3 4 0 1 2

length Field :
In Java, we can use "length" field with array reference to find the length
(number of elements of an array)
For Example :
int [ ] a = new int [5];
int [ ] b = new int [3];
System.out.println(a.length);
System.out.println(b.length);
Output: 5
3

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Array Initialization :
 Implicit Initialization :
In Java, the default values for any numeric array is zero.
For character array, default value is null ('\0').
For boolean array, default value is false.
 Explicit Initialization :

 You can initialize elements of an array explicitly.


 The initial values for elements are separated by a comma and
enclosed in braces {}.

 // Initialize the array at the time of declaration


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

 The code above creates an array of int of length 5, and


initializes its elements to 1, 2, 3, 4, and 5.
 The length of an array is the same as the number of values
specified in the array initialization list.

Bounds Checking :
 When your program is running and it tries to access an element of an
array, the Java virtual machine checks that the array element actually
exists. This is called bounds checking.

 If your program tries to access an array element that does not exist, the
Java virtual machine will generate an: ArrayIndexOutOfBoundsException

 For Example:
int [] a ={10,20,30,40,50};
System.out.println(a[8]);
Output: ArrayIndexOutOfBoundsException

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-19
Topic: Programs on Array
1) Write a program to create an array of size 5 and then read and print the
numbers of an array.
import java.util.*;

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

int [] a = new int[5]; //create an array


int i;

System.out.println("Enter "+ a.length+" numbers ");

for(i=0;i<a.length;i++) //read the numbers in array


a[i]=in.nextInt();

System.out.println("\nArray Elements are...");


for( int x : a) //printing array number using for-each loop
System.out.println(x);
}
}
Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

2. Write a program to find the sum and average of 10 integers.

import java.util.*;
class ArraySum
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);

int [] a = new int[10];


int sum=0,i;
float avg;

System.out.println("Enter "+a.length+" numbers ");


for(i=0;i<a.length;i++)
{
a[i]=in.nextInt();
sum=sum+a[i];
}
avg=(float)sum/a.length;

System.out.println("Sum = "+sum);
System.out.println("Average = "+avg);
}
}
Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-20
Topic: Programs on Array of Strings
1) Write a program to read five strings and then print the length of each
string.
import java.util.*;
class Sample
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String [] s = new String[5]; //Array of String
System.out.println("Enter "+s.length+" Strings");
for(int i=0;i<s.length;i++)
s[i] = in.nextLine();

System.out.println("Length of all strings are ");


for(String t : s)
System.out.println("Length of "+t + " is "+t.length());
}
}
Output

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

2. Write a program to read five names (Strings) and then print only those
names which are starts with A or a.

import java.util.*;
class Sample
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String [] s = new String[5]; //Array of String
System.out.println("Enter "+s.length+" Names");
for(int i=0;i<s.length;i++)
s[i] = in.nextLine();

System.out.println("Names Starts with A or a are as follows ");


for(String t : s)
{
if(t.charAt(0)=='A' || t.charAt(0)=='a')
System.out.println(t);
}
}
}
Output

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-21
Topic: Arrays Class

Arrays class :
This class contain various methods for manipulating arrays such as sorting
and searching. This class declared in java.util package.
Methods of Arrays class.
i) binarySearch ():
Syntax :
static int binarySearch (int [ ] a, int key)
This method searches the specified array of integers for the specified
value using binary search algorithm.
It returns an index of the key value if it returns an index of the key value
if it present, otherwise it returns negative number. This method is
overloaded for all numeric types.
For Example
import java.util.*;
class Sample
{
public static void main(String [] args)
{
int[] a = {10,20,30,40,50,60,70,80,90,100};
int n=60;

int x = Arrays.binarySearch(a,n);
if(x>=0)
System.out.println(n+" is found at "+x +" index");
else
System.out.println(n+" is not found in the array");
}
}

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Output

ii) equals ( )
Syntax :
static boolean equals (int [ ] a1, int [ ]a2)
This method returns true if the two specified arrays of integers are
equal to one another.
For Example
import java.util.*;
class Sample
{
public static void main(String[] args)
{
int [] a1 = {10,20,30,40,50};
int [] a2 = {10,20,30,40,50};
if( Arrays.equals(a1,a2))
System.out.println("Both Array are equal");
else
System.out.println("Both Array are not equal");
}
}
Output

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

iii) fill ( )
Syntax :
static void fill (int [ ], int val)
This method assigns the specified int value to each element of the
specified array of integers.

iv) sort ( )
Syntax :
static void sort (int [ ] a)
This method sorts the specified array into ascending numerical order.
It uses quick sort algorithm.

v) toString ( )
Syntax :
static String toString (int [ ] a)
This method returns a string representation of the contents of the
specified array.

Following program demonstrate the sort() and toString() method.


import java.util.*;
class Sample
{
public static void main(String [] args)
{
int [] a = new int[10];
Scanner in = new Scanner(System.in);

System.out.println("Enter " + a.length+ " numbers");


for(int i=0;i<a.length;i++)
a[i]=in.nextInt();

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

System.out.println("Before sorting ");


System.out.println(Arrays.toString(a));

Arrays.sort(a);

System.out.println("After sorting ");


System.out.println(Arrays.toString(a));

}
}
Output

Note: All above methods are overloaded for all data types
like float, double, char etc.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-22
Topic: Command Line Arguments

Command line arguments :


 Every Java program has a main method with String [ ] args parameter.

 This parameter indicates that the main method receives an array of


strings specified on the command line.

 Command line arguments are parameters that are supplied to the


program at the time of involving it for execution.

 Any argument provided on command line passed to the array args as its
element.

 We can write the program that can receive and use the arguments
provided on the command line.

 For Example, Consider the command line.

Java Test Hello 10 World 34.6


Command line arguments
Interpreter Class name args [0] args [1] args [2] args [3]

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Programs on Command Line Arguments:


1) Write a program to print number of command line argument
and their values.

class CmdLine
{
public static void main(String [] args)
{
System.out.println("Number of command line arguments =
"+args.length);

System.out.println("Command Line argument values are...");

for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
Output:

Cmd Line Arguments

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

2) Write a program to read two strings from command line and


then print theirs string concatenation..

class CmdConcat
{
public static void main(String [] args)
{
String s1=args[0];
String s2=args[1];
String s3=s1+s2;

System.out.println("String Concatenation is :"+s3);


}
}
Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

3) Write a program to read two numbers from command line and


then print their addition.

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

int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
int add=x+y;

System.out.println("Addition = "+add);

}
}
Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-23
Topic: Math Class

Math class:
 The class "Math" contains methods for performing basic numeric
operations such as exponential logarithm, square root and trigonometric
functions.
 The math class is declared in java.lang package.
 This class has two constants E(Eural) and PI.

Methods of Math Class :


1) abs () method :
Syntax :
static T abs (T value)
This method returns the absolute value of a specified value.
Here, T can be int, long, float or double.
For Example
class Test
{
public static void main (string args [ ])
{
int x = -15, y = 15;
System.out.println("Abs. value of "+x+" is "+Math.abs(x));
System.out.println ("Abs. value of "+y+" is "+Math.abs(y));
}
}
Output: Abs value of -15 is 15
Abs value of 15 is 15.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

2) exp () method :
Syntax :
static double exp (double a)
This method returns number e raised to the power of a specified value,
where e is the Euler constant.
For Example
class Test
{
public static void main (string args [ ])
{
System.out.println (Math.exp(5));
}
}
Output: 148.413159

3) log ( ) method
Syntax :
static double log (double a)
This method returns the natural logarithm (base e) of a specified value.
For Example
class Test
{
public static void main (String args [ ])
{
System.out.println (Math.log(50));
}
}
Output: 3.912

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

4) log 10 ( ) method
Syntax :
static double log10 (double a)
This method returns the base 10 logarithm of a specified value.
ForExample
class Sample
{
public static void main (String args [ ])
{
System.out.println (Math.log10(50));
}
}
Output

5) max ( )
Syntax :
static T max (T a, T b)
This method returns the greater between the specified value a & b.
Here T can be any number type like int, float etc.

6) min ( )
Syntax :
static T min (T a, T b)

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

This method returns the smallest between specified value a & b.


Note : Here, T can be int, long, float, double
For Example
class Test
{
public static void main (string args [ ])
{
System.out.println ("Max between 10 & 20 is" + Math.max (10,20));
System.out.println ("Min between 10 & 20 is" + Math.min (10, 20));
}
}
Output: Max between 10 & 20 is 20
Min between 10 & 20 is 10

7) pow ( ) method
Syntax :
static double pow (double a, double b)
This method returns the value of the first arg raised to the power of the
second argument i.e. a^b.
For Exmaple
class Sample{
public static void main (String args [ ])
{
System.out.println ("2 ^ 5 ="+ Math.pow(2,5));
}
}
Output: 2^5 = 32.0

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

8) sqrt ( ) method
Syntax :
static double sqrt (double a)
This method returns the square root of a specified value.
For Example
import java.util.*;
class Sample
{
public static void main (String args [ ])
{
Scanner in = new Scanner (System.in);
System.out.println ("Enter the no");
int n = in.nextInt();
System.out.println ("Square root of "+n+" is "+Math.sqrt (n));
}
}
Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

9) floor ( ) method
Syntax :
static double floor (double a)
This method returns the double value that is less than or equal to
the argument and is equal to the nearest mathematical integer.

10) ceil ( ) method


Syntax :
static double ceil (double a)
This method returns the double value that is greater than or equal to
the argument and is equal to the nearest mathematical integer.
For Example
import java.util.*;
class Sample
{
public static void main (String args [ ])
{
System.out.println (Math.ceil(23.5));
System.out.println(Math.floor(23.5));
}
}
Output

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

 Trignometric Methods
11) cos ()
Syntax:
static double cos(double a)
This method returns the trigonometric cosine of an angle.
12) sin ( )
Syntax:
static double sin (double a)
This method returns the trigonometric sin of an angle.

13) tan ( )
Syntax:
static double tan (double a)
This method returns the tan of an angle.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-24
Topic: Chapter-3 Classes And Objects

Encapsulation :
 Encapsulation is nothing more than combining data and functions in one unit
and hiding the implementation of the data from the user of the object.

 We can perform encapsulation in program by using the concept of


classes and objects.

 In object-oriented programming technique, we design a program using


objects and classes.

Class :
 A class is a user defined blueprint or prototype from which objects are
created. It represents the set of properties or methods that are
common to all objects of one type.
 It is a logical entity. It can't be physical.
 A class in Java can contain: Fields, Constructors, Methods
 Syntax for class declaration :

class <Class_name>
{
Fields;

Constructors();

Methods();
}

 The data in an object are called its instance fields, and the functions and
procedures that operate on the data are called its methods.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Object:

 An object in Java is the physical as well as a logical entity, whereas, a


class in Java is a logical entity only.

 An entity that has state and behavior is known as an object e.g., chair,
bike, marker, pen, table, car, etc.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Following program demonstrate class and objects. In this


program we are declaring Employee class and then creating two
objects of employee class.
import java.util.*;
class Employee
{
//fields declaration
private int emp_no;
private String name;
private double salary;

//methods declaration
public void getData()
{
Scanner in = new Scanner(System.in);

System.out.println("Enter emp_number ");


emp_no=in.nextInt();

System.out.println("Enter emp_name ");


name=in.next();

System.out.println("Enter emp_salary ");


salary = in.nextDouble();
}

public void putData()


{
System.out.println("Emp_no="+emp_no);
System.out.println("Emp_Name="+name);
System.out.println("Emp_Salary="+salary);
System.out.println("------------------------------------------");
}
public static void main(String [] args)
{
//creating two objects of Employee class
Employee e1 = new Employee();
Employee e2 = new Employee();
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

System.out.println("Enter first employee details");


e1.getData();
System.out.println("Enter second employee details");
e2.getData();

System.out.println("\nFirst employee is ");


e1.putData();
System.out.println("Second employee is ");
e2.putData();
}
}
Output:
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-25
Topic: Array of Objects, Constructor

Array of Objects:
 If you want to store a single object in your program, then you can do so
with the help of a variable of type object. But when you are dealing with
numerous objects, then it is advisable to use an array of objects.

 Actually it is not the object itself that is stored in the array but the
references of the object.

 The following statement creates an Array of Objects.


Class_name [] objArray;

 In the case of an array of objects, each element of array i.e. an object


needs to be initialized.

 The following program shows the initialization of array objects using the
constructor.

import java.util.*;
class Emp
{
int emp_no;
String name;
double salary;

void getData()
{
Scanner in = new Scanner(System.in);

System.out.println("Enter emp_number,name and salary ");


emp_no=in.nextInt();
name=in.next();
salary = in.nextDouble();
}

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

void putData()
{
System.out.println("\t"+emp_no+"\t\t"+name+"\t\t"+salary);
}

public static void main(String [] args)


{
Emp [] e = new Emp[5]; //Array of References
System.out.println("Enter information of 5 employees");
for(int i=0;i<e.length;i++)
{
e[i]=new Emp(); //Create Emp Object
e[i].getData();
}

System.out.println("Employees information is as follows");


System.out.println("=================================");
System.out.println("\tEMP_NO\t\tNAME\t\tSALARY");
System.out.println("=================================");
`
for(Emp obj : e) //display all emp using for-each loop
obj.putData();
System.out.println("=================================");
}
}

Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Field Intialization :
1) Default Field Initialization :
 If we don't set a field explicitly, then it is automatically initialize
to default value,
 Numeric field is initialize with 0,
 Character field is initialize with '\0',
 Boolean field is initialize with false and
 Object reference field is initialize with null.

2) Explicit field initialization :


 In Java, we can initialize a field with an explicit value at the
time of declaring a field. For Example

class MyDate
{
int day=25; //Explicit field initialization
String month="January";
int year=2020;

void display()
{
System.out.println("Date is : "+day+" "+month+" "+year);
}
public static void main(String [] args)
{
MyDate d = new MyDate();
d.display();
}
}

Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Constructor :
Constructor which construct the object in the memory of the computer it is
also used to initialize the fields of an object.

Properties of Constructor
 Name of constructor is as same that of class name.
 It does not have any return data type.
 It may take '0' or more argument.
 It can be overloaded.
 Constructor is invoked, whenever an object is created.

Types of Constructor :
There are two types of constructor in Java.
1) Default constructor :
A constructor which does not take any parameter is referred as default
Constructor.

2) Parametorized Constructor :
A constructor which takes one or more parameter, is referred as
parameterize constructor.

Note :
i) Java does not support copy constructor.
ii) Default constructor is automatically added when we does not define
any constructor in a class.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Following program demonstrate default and parameterized


constructor.
class MyTime
{
int hours;
int minutes;
int seconds;

MyTime() //default constructor


{
hours=0;
minutes=0;
seconds=0;
}

MyTime(int h, int m, int s) //parameterised constructor


{
hours=h;
minutes=m;
seconds=s;
}

void show()
{
System.out.println("Time is : "+hours+":"+minutes+":"+seconds);
}

public static void main(String [] args)


{
MyTime t1 = new MyTime(); //uses default constructor
MyTime t2 = new MyTime(5,30,10); //uses parameterized constructor

t1.show();
t2.show();
}
}

Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-26
Topic: Static Field And Static Method, Final Field And Finalize method.

Static field :
 Sometimes there may be a situation when objects of a particular class
may share some common item of data. In such situation static field is
use.

 A field of class which share common value among all objects, then it
declared as static field.

 Keyword "static" is used to declare static field.

Syntax :
static <datatype> <field>;

 Only one copy of static field is created in memory, irrespective of


number of objects.

 All objects of a class share static field.

Static method :
 A method of class can be declared as static method by preceding it’s
declaration with keyword "static".
 Syntax to declare static method:

static <return_type> <method> (parameters)


{
//set of instructions
}
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

 Static method can access only other static members of class.

 Static method always called through class name.

 Syntax to call static method:

classname.<method> (actual parameter)

Following program demonstrate static field and static method


class Sample
{
int x;
static int y; //static field
Sample(int a, int b)
{
x=a;
y=b;
}
static void display() //static method
{
System.out.println("y="+y);
}
}
class StaticTest
{
public static void main(String [] args)
{
Sample.display();
Sample s1 = new Sample(10,20);
Sample s2 = new Sample(30,40);
Sample s3 = new Sample(50,60);
Sample.display();
}
}
Output: y=0
y=60
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Final field :
 We can define a field as final. Such a field must be initialize when the
object is constructed.

 Final field, promising that we won't change the value of it during program
execution.

 To declare a field as final, precede the keyword "final" in its declaration.

 Syntax to declared final field:

final data_type fieldname = initialvalue;

 Note : Normally, final fields are declared with capital letters.


For Example Math.PI

finalize ( ) method
 Java does automatic garbage collection. So, manual memory de-allocation
is not needed and therefore, java does not support destructors.

 Of course, some object utilize a resource other than memory, such as file
or a graphic resource, network connection, database connection.

 In this case, it is important that the resource must be recycled when it is


no longer needed. For this purpose, we can add finalize ( ) method to any
class.

 The finalize method will be called before the garbage collector, destroy
the object from the memory.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-27
Topic: Packages

Package
 In small projects, all the java files have unique names. So, it is not difficult
to put them in a single folder.

 But, in the case of huge projects where the number of java files is large, it is
very difficult to put files in a single folder because the manner of storing
files would be disorganized.

 Moreover, if different java files in various modules of the project have the
same name, it is not possible to store two java files with the same name in
the same folder because it may occur naming conflict.

 This problem of naming conflict can be overcome by using the concept of


packages.

 In Java, APIs consist of one or more packages where packages consist of


many classes, classes contain several methods and fields.

Package in Java
 A package is nothing but a physical folder structure (directories) that
contains a group of related classes, interfaces, and sub-packages according
to their functionality.

 It provides a convenient way to organize your work. The Java language has
various in-built packages.

 For example, java.lang, java.util, java.io, and java.net. All these packages
are defined as a very clear and systematic packaging mechanism for
categorizing and managing.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Advantage of using packages in Java


1. Maintenance: Java packages are used for proper maintenance. If any
developer newly joined a company, he can easily reach to files needed.

2. Reusability: We can place the common code in a common folder so that


everybody can check that folder and use it whenever needed.

3. Name conflict: Packages help to resolve the naming conflict between


the two classes with the same name. Assume that there are two classes
with the same name Student.java. Each class will be stored in its own
packages such as stdPack1 and stdPack2 without having any conflict of
names.

4. Organized: It also helps in organizing the files within our project.

5. Access Protection: A package provides access protection. It can be used


to provide visibility control. The members of the class can be defined in
such a manner that they will be visible only to elements of that package.

Types of Packages in Java


There are two different types of packages in Java. They are:
1. Predefined Packages in Java (Built-in Packages)
Predefined packages in java are those which are developed by Sun
Microsystem. They are also called built-in packages in java. These
packages consist of a large number of predefined classes, interfaces, and
methods that are used by the programmer to perform any task in his
programs.

2. User-defined Package
The package which is defined by the user is called a User-defined
package. It contains user-defined classes and interfaces.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-28
Topic: Creating Our Own Package

Creating our own package :


Following are the steps to create our own package-
i) Declare the package at the beginning of file using the following form
package <packagename>;

ii) Define the class that is to be put in the package and declare it public.

iii) Create a subdirectory under the directory where the main source file is
stored.

iv) Store the Java file in the sub-directory created.

v) Compile the file. This create (.class) file in the sub-directory.

vi) Provide the import statement in the main program to import the
classes of our package.

Program to create our own package


In the following program we will create “info” package with two classes
“Emp” and “Student” and one nested package “planet” with one class
“Teacher”. Finally we import these classes in application class called “Test”.
The directory structure of this program is as follows.
C:\JavaPrograms (folder)
Test.java (Main class)
info (folder)
Emp.java
Student.java
planet (folder)
Teacher.java

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Lets declare these classes one by one


1) FileName: Emp.java
File Path : C:\JavaPrograms\info
package info;
public class Emp
{
private int emp_no;
private string name;
private double salary;
public Emp (int a, string b, double c)
{
emp_no = a;
name = b;
salary = c;
}
public void show ()
{
System.out.println("Emp No:" + emp_no + ",Name :"
+name+",Salary : " +salary);
}
}

2) File Name : Student.java


File Path : C:\JavaPrograms\info
package info;
public class Student
{
public void show ()
{
System.out.println("From student show method");
}
}

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

3) File Name : Teacher.java


File Path : C:\JavaPrograms\info\planet
package info.planet;
public class Teacher
{
public void display ()
{
System.out.println ("From Teacher display Method");
}
}

4) File Name : Test.java


File Path : C:\JavaPrograms
import info.*;
import info.planet.*;
{
public static void main (string args [ ])
{
Emp e = new Emp (10, "xyz",50000.0);
Student s = new Student ();
Teacher t = new Teacher ();
e.show ();
s.show ();
t.display ();
}
}

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

import Statements :
There are two methods to create an object of class declared in other
package.
1) By using full qualified Name :
In this method, we have to add the full package name in front of every
classname. For Example
class test
{
public static void main (String [] args)
{
java.util.Date d = new java.util.date();
System.out.println(d);
}
}

2) By Using import statement :


This method is simpler and more common. Once we use import, we no
longer have to give classes with their full qualified name.
We can import a specific class from package on the whole package.
Syntax :
import package.classname; //to import specific class
or
import package.*; //whole package.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-29
Topic: Inheritance
Inheritance :
 Creating a new class from existing class is referred as Inheritance. OR

 When one class acquires the properties of another class then it is referred
as inheritance.

 New class which is created from existing class is referred as subclass.

 Existing class from which new class is created is referred as super class.

 In OOP, concept of inheritance provides the idea of Reusability of code.

 "extends" keyword is used to perform the inheritance in Java.

 Syntax of Inheritance :

class <subclass> extends <superclass>


{
// Body of sub class
}

Base Class
Super class

Derived Class
Sub Class

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Types of Inheritance
There are three types of Inheritance in Java
(1) Single Inheritance
(2) Multi-level Inheritance
(3) Hierarchical Inheritance

Note : Java does not support multiple and hybrid inheritance. But this
concept is implemented by using an interface.

1) Single Inheritance :
If there is only one subclass and only one super class then it is referred
as single inheritance

Super class

Sub Class

Following Program demonstrate Single Inheritance


class A
{
int x;

void setX(int a)
{
x=a;
}
}

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

class B extends A
{
int y;

void setY(int a)
{
y=a;
}
void display()
{
System.out.println("x="+x);
System.out.println("y="+y);
}
public static void main(String [] args)
{
B b = new B();
b.setX(10);
b.setY(20);
b.display();
}
}
Output: x=10
y=20

2) Multi-level Inheritance
When a class extends a class, which extends another class then this is
called multilevel inheritance. For example class C extends class B and
class B extends class A then this type of inheritance is known as
multilevel inheritance.
A

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Following Program demonstrate Multilevel Inheritance


class A
{
int x;
void setX(int a)
{
x=a;
}
}
class B extends A
{
int y;
void setY(int a)
{
y=a;
}
}
class C extends B
{
int z;
void setZ(int a)
{
z=a;
}
void display()
{
System.out.println("x="+x);
System.out.println("y="+y);
System.out.println("z="+z);
}
public static void main(String [] args)
{
C c = new C();
c.setX(10);
c.setY(20);
c.setZ(30);
c.display();
}
}

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

3) Hierarchical Inheritance :
It two or more classes are derived from same base class, then it is referred as
hierarchical inheritance.

B C
class B extends A class C extends A

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-30
Topic: ‘super’ keyword

Use of Super :
Whenever a subclass needs to refer to its immediate super class, it can do so
by use of the keyword "super".
There are two uses of super
1) Using super() method to call a super class constructor.
2) Using super keyword to access the hidden member of super class in
subclass.

1) Using super to call super class constructor :


The subclass constructor uses the keyword super to invoke the constructor
method of the super class.
A subclass can call a constructor method define by its super class by use of
the following form of super.
super(parameter_list);
Here, parameter_list specifies any parameter needed by the constructor of
the super class.

The keyword super is used under following conditions


 The call to super class constructor must appear as the first statement
within the subclass constructor.
 The parameters in the super call must match the order and type of the
variable declared in the super class constructor.

Following program demonstrate use of super method


class Person
{
String name;

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

int age;

Person(String s, int a)
{
name=s;
age=a;
}
}
class Employee extends Person
{
double salary;
Employee(String s, int a, double sal)
{
super(s,a); // calls super class constructor
salary=sal;
}

void display()
{
System.out.println("Emp_Name : "+name);
System.out.println("Emp_Age : "+age);
System.out.println("Emp_Salary: "+salary);
}
}
class SuperTest
{
public static void main(String [] args)
{
Employee e = new Employee("Atul",45,50000.0);
e.display();
}
}
Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

2) Using super to access hidden member of super class in subclass.


“super” keyword always refers to the super class of the subclass in which it
is used. This usage has the following general form.
super.member;
Here, member can be either a field or a method. This form of super is most
applicable to situation where member names of a subclass hide the
members by the same name in the super class.
Example:
class A //superclass
{
int i;
}
class B extends A
{
int i; //this i , hides the i member of superclass
B(int a, int b)
{
super.i = a; //it access superclass i
i = b;
}
void display ( )
{
System.out.println("i in superclass=" + super.i); //print super i
System.out.println("i in subclass=" + i);
}
public static void main(String [] args)
{
B b = new B(10,20);
b.display();
}
}
Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-31
Topic: Method Overloading and Method Overriding

Method Overloading :
 Overloading occurs if several methods have the same name but different
parameters.
 The compiler call the correct method by matching the parameter types of
the various methods with the types of values used in the specific method
call.
 A Compile Time error occurs if the compiler cannot match the parameter.
Example:
class sample
{
int max (int a, int b)
{
if (a > b)
return (a);
else
return (b);
}
double max (double a, double b)
{
if (a>b)
return (a);
else
return (b);
}
public static void main(String [] args)
{
Sample s = new Sample ( );
System.out.println (“Maximum between 10 & 20 is” + s.max (10, 20));
System.out.println (“Maximum between 3.4 and 1.7 is” + s.Max (3.4, 1.7));
}
}
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Output: Maximum between 10 and 20 is 20


Maximum between 3.4 and 1.7 is 3.4

Method Overriding :
 In Inheritance, when a method in a subclass has the same name and
same parameters list as a method in it super class, then the method in
the subclass is said to override the method in the super class.

 When an overridden method is called from subclass, it will always refer


to the version of that method defined by the subclass.

Example :
class A
{
void display ( )
{
System.out.println(“From A class display”) ;
}
}
class B extends A
{
void display ( )
{
System.out.println (“From B class display”);
}
public static void main(String [] args)
{
B b = new B ( );
b.display ( ) ;
}
}
Output: From B class display.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Difference between method overloading & Method overriding

Method Overloading Method Overriding


1) Method overloading is 1) Method overriding is
performed within class. performed within subclass.
2) In case of method 2) In case of method overriding,
overloading, parameter list parameter list must be same.
must be different
3) Method overloading is 3) Method overriding is the
example of compile-time example of run-time
polymorphism. polymorphism.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-32
Topic: Dynamic Method Dispatch

Dynamic Method Dispatch (DMD) :


 DMD is the mechanism by which a call to an overridden method is
resolved at runtime rather than compile time.

 DMD is important because this is how JAVA implements runtime


polymorphism.

 In Java, a super class reference variable can refer to a subclass object,


but it can access only those members of subclass which are inherited
form super class.

 Upcasting in Java: When Parent class reference variable refers


to Child class object, it is known as Upcasting.
Note: View versa of upcasting is referred as downcasting, but it is not allowed in java

 When an overridden method is called through a super class reference,


Java determines which version of that method to execute, based upon
the type of object being referred by the super class reference.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

 This determination is made at runtime. Therefore, if a super class


contains a method, that is overridden by a subclass then different types
of object are referred through a super class reference, different versions
of the subclass are executed.

Following program demonstrates DMD mechanism


class A
{
void display ()
{
System.out.println("From A class display method");
}
}
class B extends A
{
void display ()
{
System.out.println("From B class display method");
}
}
class C extends A
{
void display ()
{
System.out.println("From C class display method");
}
}

class DMDTest
{
public static void main(String [] args)
{
A ref ; //super class reference
ref = new A(); //refers to A class Object
ref. display (); //calls A class display()

ref = new B(); //referes to B class Object


ref. display (); //calls B class display()

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

ref = new C (); //referes to C class Object


ref.display (); //calls C class display()
}
}

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-33
Topic: Abstract Method And Abstract Class

Abstract Method :
 In Inheritance, we have some methods which must be overridden by the
subclass.

 In this case, we want some way to ensure that a subclass must override all
necessary methods.

 Java's solution to this problem is an Abstract method.

 We can require that certain methods must be override in subclass by


specifying the abstract method in the super class.

 To declare an abstract method, the syntax is :-


abstract <returntype> method name (parameter list);

Properties of abstract method:


(i) Abstract method doesn't have method body ({ })

(ii) It is also called as unimplemented method.

(iii) It must be override in subclass.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Abstract Class :
(i) Any class that contains one or more abstract method must also be
declared as an abstract.

(ii) To declare abstract class use keyword "abstract" in front of class


declaration.

(iii) We can't create an object of an abstract class but we can create the
reference.

(iv) Abstract class is also referred as "partially unimplemented class".

Program to demonstrate abstract method and abstract class:


abstract class Shape
{
double dim1, dim2;

Shape(double a, double b)
{
dim1=a;
dim2=b;
}
abstract void area();
}

class Rect extends Shape


{
Rect(double a, double b)
{
super(a,b);
}
void area()
{
System.out.println("Area of Rectangle = "+(dim1*dim2));
}

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

class Triangle extends Shape


{
Triangle(double a, double b)
{
super(a,b);
}
void area()
{
System.out.println("Area of Triangle="+(dim1*dim2/2));
}
}

class AbstractTest
{
public static void main(String [] args)
{
Shape s; //s is reference
//s=new Shape(10,10); Error, can't create object of abstract class

s=new Rect(10,9); // s referes to Ract object


s.area(); // calls Rect area()

s=new Triangle(10,8); //s referes to Triangle object


s.area(); // calss Triangle area()
}
}
Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-34
Topic: final keyword

There are three uses of final keyword :


1) To create constant field :
If the field is declared with final modifier, then it must be initialize at the
time of declaration and we can't change the value of final field.
class math
{
final static double PI = 3.14;
}

2) To prevent method overriding :


There may be a situation, when we want to prevent method overriding
in subclass. To disallow a method from being overridden in subclass,
specify final keyword as a modifier in front of the method declaration, in
super class. Methods declared as final cannot be overridden in subclass.
For example
class A
{
final void display ()
{
System.out.println ("This is final method")
}
}
class B extends A
{
void display () //error can't override
{

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

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

3) To prevent Inheritance :
Sometimes we want to prevent a class from being inherited. To do this
precedes the class declaration with keyword final. Declaring a class as
final, implicitly declares all of its method as final too.
For example :
final class A
{ ----
----
----
}
class B extends A // error can't subclass A
{ ----
----
----
}

Difference between Abstract method and Final Method :


Abstract Method Final Method
i) It does not have method body i) It always have method body
ii) It is also called unimplemented ii) It is always implemented.
method.
iii) It must override in subclass. iii) It can't override within subclass.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Difference between Final class and Abstract class :


Final class Abstract class
i) Final class cannot be inherited i) Abstract class is mean to be
inherited.
ii) Final class can be instantiated ii) Abstract class can't be instantiated.
iii) Final class cannot contain iii) Abstract class may contain final
abstract method. method.
iv) Final class is fully implemented iv) Abstract class is partially
class. unimplemented class.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-35
Topic: Access Specifiers in Java

There are four types of Java access specifier


1) Private
2) Default
3) Protected
4) Public

1) Private Access Specifier


The private members are accessible only with a class.
2) Default Access Specifier
If you don’t use any access specifier, it is treated as default, by default.
The default members are accessible only within class and package.
3) Protected access specifier :
The protected members are accessible within package and outside the
package but through inheritance only.
4) Public access specifier :
The public members are accessible everywhere, it has the widest scope
among all other modifiers.
Let’s understand access specifier by simple table.
Access Within Within Outside Package Outside
Specifier class Package through Package
inheritance
private Yes No No No
default Yes Yes No No
protected Yes Yes Yes NO
public Yes Yes Yes Yes

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-36
Topic: Object class

 The object class is the parent class of all the classes in Java by default.

 In other words, it is the topmost class of Java.

 Every class of Java is either directly or indirectly inherited from object class.

 The object class is beneficial, if you want to refer any object whose type you
don’t know at run-time.

Method of object class :


1. clone()
Creates and return a copy of this object.

2. equals()
This method checks whether two objects are equal or not.

3. finalize()
This method is called by the garbage collector when object is destroyed
form the memory.

4. getClass ()
Returns the run-time class of an object.

5. toString ()
Returns a string representation of an object.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Program to demonstrate How to override toString() method to print object


data.
import java.util.*;

class Employee
{
int emp_no;
String name;
double salary;

Employee(int a, String b, double c)


{
emp_no=a;
name=b;
salary=c;
}
public String toString()
{
String str = "Emp["+emp_no+","+name+","+salary+"]";
return (str);
}
public static void main(String [] args)
{
Employee e1 = new Employee(10,"Atul",50000.0);
Employee e2 = new Employee(20,"Vinay",60000.0);
System.out.println(e1);
System.out.println(e2);
}
}
Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-37
Topic: Chapter-5 Interface And Inner Classes

Interface
 An interface is just same as abstract class.

 The main difference between an interface and abstract class is, interface
is fully unimplemented, whereas abstract class is partially
unimplemented.

 It means by default all the methods in an interface are abstract.

 Syntax to declare an interface:

interface interface_name
{
void method1 ();
void method2 ();
……….
}

 Properties of an interface
1. By default all the methods in an interface are abstract.
2. The default access specifier for an interface is public.
3. Object of an interface cannot be created.
4. Reference of an interface can be created.
5. Inside interface the field is static by default.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Implementing an Interface :
 Implementing on interface is similar to deriving from class except that
you are required to implement all methods defined in the interface.

 To implement on interface Java provide "implements" keyword.

 A class can implement multiple interfaces.

 Syntax to implement an interface

class <classname> implements <interface 1>, <interface 2>, ….


<interface n>
{
….
….
…. //body of class
}
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

All syntaxes of class delaration in Java :


1) class <classname>
{
}

2) class <subclass> extends <super class>


{
}

3) class <classname> implements <inter 1>, <inter 2>,…. <inter n>


{
}

4) class <subclass> extends <superclass> implements <i1>, <i2>,…. <in>


{
}
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Program to Demonstrate Interface :

Area Shape
<<interface>> <<class>>

extends
implements

Rectangle Triangle
<<class>> <<class>>

interface Area
{
void compute();
}

class Shape
{
double dim1, dim2;
Shape(double a, double b)
{
dim1=a;
dim2=b;
}
}

class Rectangle extends Shape implements Area


{
Rectangle(double a, double b)
{
super(a,b);
}
public void compute()
{
System.out.println("Area of Rectangle="+(dim1*dim2));
}
}
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

class Triangle extends Shape implements Area


{
Triangle(double a, double b)
{
super(a,b);
}
public void compute()
{
System.out.println("Area of Triangle="+(dim1*dim2/2));
}
}

class InterfaceTest
{
public static void main(String [] args)
{
Area ref;
ref = new Rectangle(10,10);
ref.compute();

ref = new Triangle(10,9);


ref.compute();
}
}
Output:
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Difference between Abstract class and Interface

Abstract Class Interface


i) Abstract class can have i) Interface can have only abstract
abstract and non-abstract methods.
methods.
ii) It is partially unimplemented ii) It is fully un-implemented.
iii) It may contain instance field. iii) It may contain only static field.
iv) It contains constructor. iv) It does not contain constructor.
v) Default access specifier is v) Default access specifier is
default public.
vi) Abstract class can be extended vi) Interface is always implemented
to subclass. by the class.

Extending An Interface
 Like classes interfaces can also be extended.
 That is an interface can be sub interfaced from other interfaces.
 The new interface will inherit all the member of the super interface in
the manner similar to subclass. This is achieved using the keyword
extends.
 Syntax

interface subinterface extends superinterface


{
// body of subinterface
}

Points to Remember:
 One class can extends another class.
 One interface can extends another interface.
 Class can implements other interfaces.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-38
Topic: Inner Classes

Inner class
 If the class is declared inside another class, then it is referred as inner
class.
OR
Inner class means one class which is a member of another class.

 Syntax of Inner class:

class Outer
{
class Inner
{
………..
}
}

 Properties of Inner class:


1. The object of inner class can be created only in its outer class.
2. It can access all the members of outer class.
3. Inner classes are scope to the class used to declare them.
4. Inner classes are very convenient to write event driven programs.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Local Inner class :


 If the class is declared insider the method of outer class, then it referred
as local inner class.

 Syntax of Local Inner class

class Outer
{
void method ()
{
class LocalInnerClass
{
………………………..
}
}
}

Properties of Local Inner Class


1. The object of local inner class can be created in the method in which it is
declared.
2. The scope of local inner class is restricted to the block.
3. A local class has access to the members of its outer class.
4. It can also access parameter and local variable of the method in which it
is declared.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Anonymous Inner Class :


 The class which does not have any name is referred as anonymous class.

 Syntax of Anonymous class

Interface/Superclass ref = new interface/Superclass ()


{
…… //body of anonymous class
……
};

 Properties of Anonymous class


1. It is an Inner class without a name.
2. Only a single object can be created of anonymous class.
3. Constructors are not allowed in anonymous class
4. It always created by either implementing or interface or by extending
a super class.
5. Anonymous Inner classes are useful in Windows programming.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Write a program to demonstrate Anonymous Inner class


interface A
{
void display();
void info();
}

class Test
{
public static void main(String[] args)
{
A a = new A()
{ //Anonymous class
public void display()
{
System.out.println("Display Method");
}
public void info()
{
System.out.println("Info Method");
}
};
a.display();
a.info();
}
}

Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-39
Topic: Chapter-6 Wrapper Classes And Vector

Wrapper Class :
 A wrapper class is a class whose object wraps or contains primitive data
type.

 In other words we can wrap a primitive data type into a wrapper class
object.

 All the wrapper classes are declared in java-lang package.

 Data structures in the collection framework of Java such as Vector or


ArrayList stores only objects and not primitive types. So to convert
primitive types into objects or vice versa Wrapper classes are used.

 There are 8 wrapper classes for the corresponding primitive type of


Java. They are as follows
Primitive Types Wrapper class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

1) Converting primitive type to Wrapper object using constructor method.


Calling Constructor Conversion Action
1) Integer intObj = new Integer (i); Primitive int to Integer object.
2) Float floatObj = new Float (f); Primitive float to Float object.
3) Double doubleObj = new Double(d); Primitive double to Double object.

2) Converting wrapper object to primitive type using typeValue() method.


Calling Method Conversion Action
1) int i = intObj.intValue (); Integer object to primitive int.
2) float f = floatObj.floatValue(); Float object to primitive float
3) double d=doubleObj.doubleValue(); Double object to primitive double.

3) Converting primitive type to String object using static toString().


Calling Method Conversion Action
1) String str = Integer.toString(i); Primitive int to String
2) String str = Float.toString(f); Primitive float to String
3) String str = Doible.toString(d); Primitive double to String

4) Converting String to primitive type using static parse method


Calling Method Conversion Action
1) int i = Integer.parseInt(str); String to Primitive int
2) float f = Float.parseFloat(str); String to Primitive float
3) double d = Double.parseDouble (str); String to Primitive double

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

5) Converting string to wrapper object using static valueOf()


Calling Method Conversion Action
1) Integer intObj = Integer.valueOf (str); String to Integer object.
2) Float floatObj = Float.valueOf (str); String to Float object.
3) Double doubleObj = Double.valueOf (s); String to Double obj.

Character Wrapper Class :


Character is a wrapper around char data type. Various methods defines by the
character class are as follows

1. static char toLowerCase(char ch)


Returns the lower case equivalent of ch

2. static char toUpperCase(char ch)


Returns the Upper case equivalent of ch
Example:
char ch = 'a';
char x = Character. toUpperCase (ch);
System.out.println (x);
Output: A

3. static boolean isLowerCase(char ch)


Returns True if ch is in lower case.

4. static boolean isUpperCase (char ch)


Returns True if ch is in Upper case.

5. static boolean isDigit (char ch)


Returns true if 'ch' is digit.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-40
Topic: Vector

Vector
 The vector class implements a growable array of objects or Vector
implements a dynamic array that means, it can grow during program
execution.

 The elements of vector can be accessed using an index. Vector is a class


and it is defined in java.util package.

 Vector class is similar to ArrayList class but vector is synchronized.

 Vector cannot store primitive types but using wrapper classes, we can
convert primitive type to object and then store in the vector.

Constructors of Vector
1) Vector()
Construct an empty vector with default size of 10 and capacity
increment is double.

2) Vector (int initialCapacity)


Constructs an empty vector with the specified initial array size.

3) Vector (int initialCapacity, int CapacityIncrement)


Construct an empty vector with the specified initial capacity and
capacity increment)

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Methods of Vector class:


1) boolean add (E e)
Appends the specified element to the end of vector.

2) void add (int index, E element)


Insert the specified element at the specified position.

3) void addElement (E obj)


Adds the specified object to the end of vector.

4) int capacity ()
Returns the current array size of the vector.

5) int size ()
Returns the current number of elements in the vector.

6) boolean contains (Object Obj)


Returns true if vector contains the specified element.

7) int indexOf (Object Obj)


Returns the index of the specified element, otherwise returns -1 if
element does not found in the vector.

8) E remove (int index)


Removes the element from the specified position in vector.

9) boolean remove (Object Obj)


Removes the specified element from vector.
Returns true, if element is removed successfully.
Returns false, if vector does not contain specified element.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

10) void removeAllElements ()


Removes all elements from the vector.

11) boolean isEmpty ()


Returns true, if vector is empty. Otherwise returns false.

12) E get(int index)


Returns the element from the specified index from the vector.

13) E set (int index, E element)


Replace the element at the specified index with the specified element.

Difference between Array and Vector :

Array Vector
1) Size of Array need to be 1) No need to declare the size of
declared in advanced. vector.
2) Once declared array can't grow 2) Vector can always grow in size.
in size.
3) Array can store primitive types 3) Vector can store only objects.
like int, float etc.
4) No built-in methods are 4) Vector class has numbers of
provided to add, remove, and methods to add, remove, and
search the element in array. search the element which saves
the development time.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

WAP program to create a vector with seven elements as [10, 30, 50, 20, 40, 80,
60]. Remove element at 3rd position. Insert 100 at 3rd position. Display the
current size of the vector.
import java.util.*;

class Test {
public static void main(String[] args)
{
Vector<Integer> v = new Vector<Integer>(); //create an empty vector

v.add(10); //add 10,30,50,20,40,80,60 into Vector


v.add(30);
v.add(50);
v.add(20);
v.add(40);
v.add(80);
v.add(60);

System.out.println(v); //print Vector

v.remove(3); //remove an element at 3rd index

System.out.println("After removing element from 3rd index ");

System.out.println(v); //print Vector

System.out.println("Size of Vector = "+v.size());


}
}
Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-41
Topic: Colletion Framework Part-A

 The Collection in Java is a framework that provides an architecture to store


and manipulate the group of objects.

 Java Collections can achieve all the operations that you perform on a data
such as searching, sorting, insertion, manipulation, and deletion.

 Java Collection means a single unit of objects. Java Collection framework


provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
Next →← Prev
What is Collection in Java
A Collection represents a single unit of objects, i.e., a group.

What is a framework in Java


o It provides readymade architecture.
o It represents a set of classes and interfaces.

What is Collection framework


The Collection framework represents a unified architecture for storing and
manipulating a group of objects. It has:
1. Interfaces and its implementations, i.e., classes
2. Algorithm

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Collection Hierarchy

List Interface
 List interface is the child interface of Collection interface.
 It inhibits a list type data structure in which we can store the ordered
collection of objects. It can have duplicate values.
 List interface is implemented by the classes ArrayList, LinkedList, Vector,
and Stack.
Set Interface
 Set Interface in Java is present in java.util package.
 It extends the Collection interface.
 It represents the unordered set of elements which doesn't allow us to store
the duplicate items.
 Set is implemented by HashSet, LinkedHashSet, and TreeSet.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

S.No List Set


1. The list implementation allows us The set implementation doesn't
to add the duplicate elements. allow us to add the duplicate
elements.
2. The insertion order is maintained It doesn't maintain the insertion
by the List. order of elements.
3. The List implementation classes are The Set implementation classes are
Vector,LinkedList and ArrayList. HashSet, LinkedHashSet and
TreeSet.
4. We can get the element of a We cannot find the element from
specified index from the list using the Set based on the index because
the get() method. it doesn't provide any get
method().
5. It is used when we want to It is used when we want to design
frequently access the elements by a collection of distinct elements.
using the index.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Methods of List and Set Interface

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-42
Topic: Colletion Framework Part-B

List interface is implemented by the classes ArrayList, LinkedList,


Vector, and Stack.

ArrayList
 The ArrayList class implements the List interface.
 It uses a dynamic array to store the duplicate element of different data
types.
 The ArrayList class maintains the insertion order and is non-synchronized.
 The elements stored in the ArrayList class can be randomly accessed.

Vector
 Vector uses a dynamic array to store the data elements.
 It is similar to ArrayList.
 However, It is synchronized and contains many methods that are not the
part of Collection framework.

Difference between ArrayList and Vector


ArrayList Vector
1) ArrayList is not synchronized. 1) Vector is synchronized.
2) ArrayList increments 50% of current 2) Vector increments 100% means
array size if the number of elements doubles the array size if the total
exceeds from its capacity. number of elements exceeds than
its capacity.
3) ArrayList is not a legacy class. It is 3) Vector is a legacy class.
introduced in JDK 1.2.
4) ArrayList is fast because it is non- 4) Vector is slow because it is
synchronized. synchronized,

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

5) ArrayList uses the Iterator 5)A Vector can use the Iterator
interface to traverse the elements. interface or Enumeration
interface to traverse the elements

LinkedList
 LinkedList implements the Collection interface.
 It uses a doubly linked list internally to store the elements.
 It can store the duplicate elements.
 It maintains the insertion order and is not synchronized.
 In LinkedList, the manipulation is fast because no shifting is required.
 For Example
import java.util.*;
class Test
{
public static void main(String [] args)
{
LinkedList <String> list = new LinkedList<String>();

System.out.println(list);
list.add("Atul");
list.add("Ajay");
list.add("Kedar");
list.add("Nilesh");

System.out.println(list);

list.add(1,"Info");

System.out.println(list);
System.out.println("Deleted item from index 1 is
:"+list.remove(1));
System.out.println(list);
}
}

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Difference between ArrayList and LinkedList

ArrayList LinkedList
1) ArrayList internally uses a dynamic LinkedList internally uses a doubly
array to store the elements. linked list to store the elements.
2) Manipulation with ArrayList Manipulation with LinkedList
is slow because it internally uses an is faster than ArrayList because it
array. If any element is removed from uses a doubly linked list, so no
the array, all the elements are shifted shifting is required in memory.
in memory.
3) An ArrayList class can act as a LinkedList class can act as a list and
list only because it implements List queue both because it implements
only. List and Deque interfaces.
4) ArrayList is better for storing and LinkedList is better for
accessing data. manipulating data.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Stack
 The stack is the subclass of Vector.
 It implements the last-in-first-out data structure, i.e., Stack.
 The stack contains all of the methods of Vector class and also provides its
methods like boolean push(), boolean peek(), boolean push(object o),
which defines its properties.
For Example:

Stack <Integer> stk = new Stack<Integer>();


System.out.println(stk);

stk.push(10);
stk.push(20);
stk.push(30);
stk.push(40);
System.out.println(stk);
System.out.println("Popped item is :"+stk.pop());
System.out.println(stk);

Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Set is implemented by HashSet, LinkedHashSet, and TreeSet.

HashSet
 HashSet class implements Set Interface.
 It represents the collection that uses a hash table for storage.
 Hashing is used to store the elements in the HashSet.
 It contains unique items.

LinkedHashSet
 LinkedHashSet class represents the LinkedList implementation of Set
Interface.
 It extends the HashSet class and implements Set interface.
 Like HashSet, It also contains unique elements.
 It maintains the insertion order.

TreeSet
 Java TreeSet class implements the Set interface that uses a tree for storage.
 Like HashSet, TreeSet also contains unique elements.
 However, the access and retrieval time of TreeSet is quite fast.
 The elements in TreeSet stored in ascending order.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-43
Topic: Chapter-7 Exception Handling

 An error may produce an incorrect output or may terminate the execution


of the program or even may cause the application to crash.

 It is therefore important to detect and manage properly all the possible


error conditions in the program so that the program will not terminate or
crash during execution.

 Errors may broadly classify into two types.

1) Compile Time Errors:-


 All syntax errors will be detected and displayed by the Java compiler and
therefore these errors are known as compile time errors.

 Whenever the compiler displays an error, it will not create the .class file. It
is therefore necessary that we fix all the errors before we can successfully
compile and run the program.

 Most of the compile time errors are due to typing mistakes. The most
common problems are
a. Missing semicolons
b. Missing (or mismatch) brackets in classes and methods.
c. Misspelling of identifiers and keywords.
d. Missing double quotes in string.
e. Use of undeclared variable.
f. Bad reference to object.
g. And many more

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

2) Run Time Erros:-


 Sometimes, a program may compile successfully creating the .class file but
may not run properly. Such programs may produce wrong results due to
wrong logic or may terminate in between.
 Error which occurs at run time is called as Exception.
 Most common run time errors are

a) ArithmeticException
It occurs due to dividing number by zero.
Example:
class Test
{
public static void main(String[] args)
{
int a=10,b=5,c=5;

int x = a/(b-c);
System.out.println("x="+x);

int y = a/(b+c);
System.out.println("y="+y);
}
}
Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

b) ArrayIndexOutOfBoundsException
It occurs when we access an array element which is out of the bounds of an
array.
Example:
class Test
{
public static void main(String[] args)
{
int [] a = {10,20,30,40,50};
System.out.println(a[7]);
}
}
Output:

c) NegativeArraySizeException
It occurs when we use to create an array of negative size.
Example
class Test
{
public static void main(String [] args)
{
int [] a = new int[-5];
System.out.println("Array is created");
}
}
Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

d) NullPointerException
It occurs by referencing null object.
Example
class Test
{
public static void main(String [] args)
{
String str=null; //referencing null object
System.out.println("Length of string is :"+str.length());
}
}
Output:

e) NumberFormatException
It occurs when conversion between string and number fails.
Example
class Test{
public static void main(String [] args) {
String str="ABCD";
int x = Integer.parseInt(str);
System.out.println("x="+x);
}
}
Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

f) StringIndexOutOfBoundsException
It occurs when a program attempts to access a nonexistent character
position in a string.

g) IOException
It occurs due to general input and output failure.

h) FileNotFoundException
It occurs due to opening a non existing file.

i) OutOfMemoryError
It occurs when there’s not enough memory to allocate for an array or
object.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-44
Topic: Exception handling using try-catch block.

Exception Handling
 When the java interpreter encounters an Exception, it creates an
exception object and throws.

 If the exception object is not caught and handled properly, the


interpreter will display an error message and terminate the program.

 If we want the program to continue with the execution of the remaining


code, then we should try to catch the exception object, this task is
known as Exception Handling.

try-catch block
The Basic concept of Exception Handling is throwing and catching it. This is
illustrated in the following figure.

try block
Statement that Exception object Creator
causes an exception

Throws exception
object
catch block
Catch block Exception handler
statement that
handles an
exception.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Syntax of try-catch

try
{
Statement(s);
………. // generate an exception
}
catch (Exeptiontype e)
{
Statement(s); // process the exception
}

If any one statement within try block generates an exception, the remaining
statements in the try block are skipped and execution jumps to the catch
block. The catch block can have one or more statements that are necessary
to process the exception.
Following program demonstrate exception handling:
class Test
{
public static void main(String[] args)
{
int a=10,b=5,c=5;
try
{
int x = a/(b-c);
System.out.println("x="+x);
}
catch(ArithmeticException e)
{
System.out.println("Caught an exception");
System.out.println("Divide by zero");
}
int y = a/(b+c);
System.out.println("y="+y);
}
}

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Output:

Write a program to find sum of integers provided on command line using


exception handling.
class Test
{
public static void main(String[] args)
{
int sum=0;

for(int i=0;i<args.length;i++)
{
try
{
int n = Integer.parseInt(args[i]);
sum=sum+n;
}
catch(NumberFormatException e)
{
System.out.println("Invalid Integer: "+args[i]);
}
}
System.out.println("Sum="+sum);
}
}
Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-45
Topic: Multiple catch block And finally Block

Multiple Catch Block


 We can catch multiple exception type in a try block and handles each type
separately.

 Syntax :

try
{
statement(s);
}
catch (ExceptionType 1 e1)
{
………
}
catch (ExceptionType 2 e2)
{
………
}
.
.
catch (ExceptionTypeN eN)
{
………
}
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

 When an exception in a try block is generated java consider multiple catch


statement like cases in switch statement.

 The first statement, whose parameter matches with the exception object,
will be executed and the remaining catch statement will skip.

 If exception object is not caught, then program is terminated.

Finally block :
Java supports another statement known as "finally".
It is guaranteed to be executed regardless of whether or not an exception is
occurred.
Finally block can be added after the last catch block or immediately after the
try block.

try try
{ {
Statement(s); Statement(s);
} }
catch (ExceptionType 1 e1) finally
{ {
……… ……………
} }
catch (ExceptionType 2 e2)
{
………
}
finally
{
………
}
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Execution Flow of finally :


Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-46
Topic: Exception Hierarchy And Custom Exception

All exception and errors are the subclasses of class Throwable class, which is
base class in exception Hierarchy.

One branch is headed by Exception this class is used for Exceptional


condition, that user program should catch.

Another branch Error is used by the Java run-time system (JVM) to indicate
error to generate within JVM. We can't handle errors.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Creating And Throwing Our Own Exception (Custom Exception)


We can also create our own exception from the Exception class.
To do this, create the subclass of Exception and then using the "throw”
keyword, we can throw our own exception.
Write a program to demonstrate custom exception
import java.util.*;
class InvalidAgeException extends Exception
{
InvalidAgeException(String msg)
{
super(msg);
}
}
class Test
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
try
{
System.out.println("Enter your age ");
int age = in.nextInt();

if(age<18)
throw new InvalidAgeException("Not eligibal for voting");
else
System.out.println("Eligibal for voting");
}
catch(InvalidAgeException e)
{
System.out.println(e);
}
catch(InputMismatchException e)
{
System.out.println("Invalid Age");
}
}
}
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Output:
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-47
Topic: throw and throws keyword
In Java, there are two types of exception.
1) Checked Exception :
 All exceptions other than Runtime Exceptions are known as Checked
exceptions as the compiler checks them during compilation to see
whether the programmer has handled them or not.

 If some code within a method throws a checked exception, then the


method must either handle an exception or it must specify the
exception using "throws" keyword.

 Otherwise compile-time error "Unreported Exception" will be


generated.

 For example, SQLException, IOException, ClassNotFoundException etc.

1) Unchecked Exception :
 Runtime Exceptions are also known as Unchecked Exceptions.

 These exceptions are not checked at compile-time so compiler does not


check whether the programmer has handled them or not but it’s the
responsibility of the programmer to handle these exceptions and
provide a safe exit.

 Compiler will never force you to catch such exception or force you to
declare it in the method using throws keyword.

 For example, ArithmeticException, NullPointerException,


ArrayIndexOutOfBoundsException etc.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

"throw" And "throws" keyword:


 The "throw" keyword is used to explicitly throw an exception from a
method. We can throw, checked or unchecked exception.

 The "throw" keyword is mainly used to throw, custom exceptions.

 Syntax :
throw new MyException ("Message");

 "throws" is keyword in java, which is used in the declaration of method to


indicate that this method might throw the listed exception.

 The caller to this method has to handle the exception using try and catch
block, otherwise will get compile-time error we can handle the exception
by two ways.

1) Using tray-catch block


Example:
import java.net, *;
class Test{
public static void main (String [] args) {
try {
InetAddress add = InetAddress.getByName (“www.facebook.com”)
System.out.println(add);
}
catch(UnknownHostException e) {
System.out.println(e);
}
}
}
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

2) Using throws keyword.


Example:
import java.net, *;
class Test
{
public static void main (String [] args) throws UnknownHostException
{
InetAddress add = InetAddress.getByName (“www.facebook.com”)
System.out.println(add);
}
}
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-48
Topic: Chapter-8 Multithreading

 Multithreaded program extend the idea of multi-tasking, where individual


program appears to do multiple task at the same time. Each task is usually
called a thread.

 Programs that can run more than one thread at once are said to be multi-
threaded program.

 In most of our computer we have only a single processor and therefore in


reality the program is doing only one thing at a time but the processor
switches between the thread so fast that it appear to human beings that
all of them are being done simultaneously.

 A thread is similar to a program that has a single flow of control. It has a


beginning, ending and executes command sequentially.

 The structure of multi-threaded program is shown in the following figure.

Main
Thread

Thread Thread Thread


Switching Switching
A B C

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Creating Thread
Thread can be created by following two ways
1. By extending Thread class.
2. By implementing Runnable Interface

1. Creating a thread by extending Thread class :


It includes following steps
a) Declare the subclass of Thread class.

b) Override the run() method, which is responsible for executing the


sequence of code that the thread will execute.

c) Create a Thread object and call the start() method to initiate thread
execution.

Write a program to create thread by extending Thread class.


class A extends Thread
{
public void run()
{
for(int i=1;i<=30;i++)
System.out.println("A Thread : i = "+i);

System.out.println("Exiting A Thread");
}
}
class B extends Thread
{
public void run()
{
for(int j=1;j<=30;j++)
System.out.println("B Thread : j = "+j);

System.out.println("Exiting B Thread");
}

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

class C extends Thread


{
public void run()
{
for(int k=1;k<=30;k++)
System.out.println("C Thread : k = "+k);

System.out.println("Exiting C Thread");
}
}

class ThreadTest
{
public static void main(String [] args)
{
A a = new A();
B b = new B();
C c = new C();

a.start();
b.start();
c.start();
}
}
Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

2. Creating thread by Implementing Runnable Interface :


 It is the easiest way to create the thread as you know that, the interface
always contains abstract method.

 The Runnable interface contains only one method which is


public void run ();

 So, a class which implements Runnable interface must define run()


method.

 After you create a class that implements Runnable create the object of
this class and then create the object of Thread class by using the
following constructor.
Thread (Runnable r)

 Pass the object of the class which implements Runnable and then call
start() method, to initiate the execution of the thread.

Write a program to create thread implementing Runnable interface.

class A implements Runnable


{
public void run()
{
for(int i=1;i<=30;i++){
System.out.println("A Thread : i = "+i);
}
System.out.println("Exiting From A Thread");
}
}

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

class B implements Runnable


{
public void run()
{
for(int j=1;j<=30;j++){
System.out.println("B Thread : j = "+j);
}
System.out.println("Exiting From B Thread");
}
}

class C implements Runnable


{
public void run()
{
for(int k=1;k<=30;k++){
System.out.println("C Thread : k = "+k);
}
System.out.println("Exiting From C Thread");
}
}

class ThreadTest1
{
public static void main(String [] args)
{
Thread t1 = new Thread( new A());
Thread t2 = new Thread( new B());
Thread t3 = new Thread( new C());

t1.start();
t2.start();
t3.start();
}
}

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-49
Topic: Thread Life Cycle OR Thread States
Thread states/Thread life cycle is very basic question, before going deep
into concepts we must understand Thread life cycle.

Thread have following states


 New
 Runnable
 Running
 Waiting/blocked/sleeping
 Terminated (Dead)

Thread states in diagram

start()

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Thread states in detail

1. New State
When you create object of Thread with the new operator that means it
is in the born state, it does not start executing code inside the thread. It
remains in this state until we call the start () method.

2. Runnable State
The thread is in runnable state after invocation of start() method but the
thread scheduler has not selected it to be the running thread.

3. Running State
The thread is in running state, if the thread scheduler has selected it for
running.

4. Waiting or Blocked State


This is the state when the thread is still alive, but currently not eligible to run.
A thread enters in the blocked state when one of the following actions occurs.
(a) When we call sleep() method of the thread.
(b) The thread calls an operation that is blocking an input/ output.
(c) The thread calls the wait method.
(d) The thread tries to lock an object that is currently locked by
other thread.
Moving out of Block State :
(a) When the specified no. of milliseconds is complete.
(b) When the input/ output operation is complete.
(c) When the other thread call notify() or notifyall() method.
(d) When the other thread release the ownership of the lock.

5. Dead State:
A thread is considered dead when its run() method completes.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-50
Topic: Thread Constructors and Its Methods

Constructors
Thread()
Allocates a new Thread object.
Thread(Runnable target)
Allocates a new Thread object.
Thread(Runnable target, String name)
Allocates a new Thread object with specified
name.
Thread(String name)
Allocates a new Thread object with specified
name.

Methods of Thread Class:


static Thread currentThread()
Returns a reference to the currently executing thread
object.
String getName()
Returns this thread's name.
int getPriority()
Returns this thread's priority.
boolean isAlive()
Tests if this thread is alive.
void join()
Waits for this thread to die.
void run()
If this thread was constructed using a
separate Runnable run object, then
that Runnable object's run method is called; otherwise,
this method does nothing and returns.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

void setName(String name)


Changes the name of this thread to be equal to the
argument name.
static void sleep(long millis) throws Exception
Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of
milliseconds, subject to the precision and accuracy of
system timers and schedulers.
void start()
Causes this thread to begin execution; the Java Virtual
Machine calls the run method of this thread.
void setPriority(int newPriority)
Changes the priority of this thread.

Java Thread Priorities:-


 Every thread have priority. Java assign priority to every thread that
determine how that thread should be treated with respect to other.
 The thread priority is an integer value from 1 to 10. Where 1 is the
minimum priority and 10 is the maximum priority.
 When more than one threads are running higher priority thread get
preference over threads with lower priority.
 The default priority of the thread will be 5.
 To set a thread’s priority call setPriority( ) method. The setPriority( )
method require one argument of type int. And the getPriority( ) method
returns the priority of the thread.
 The thread class also contain three constants which are
MAX_PRIORITY
MIN_PRIORITY
NORM_PRIORITY
These constants specify minimum, maximum and default priority.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-51
Topic: Thread Synchronization

Synchronization:- (Object lock)


 When two or more threads need access to a shared resource, they need some
way to ensure that the resource will be used by only one thread at a time. The
process by which this is achieved is called Synchronization.

 Key to synchronization is the concept of the monitor. Only one thread can own
a monitor at a given time. When a thread acquires a lock, it is said to have
entered the monitor. All other threads attempting to enter the locked monitor
will be suspended until the first thread exits the monitor. These other threads
are said to be waiting for the monitor.

Understanding the problem without Synchronization


In this example, there is no synchronization, so output is inconsistent. Let's see
the example:

class Table {

void printTable(int n) { //method not synchronized

System.out.println("Multiplication Table of "+n+ " is");


for(int i=1;i<=5;i++){
System.out.println(n+" X "+i+" = "+n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
System.out.println("---------------------------------------------------");
}
}

class MyThread1 extends Thread {

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Table t;
MyThread1(Table t) {
this.t=t;
}

public void run(){


t.printTable(5);
}
}
class MyThread2 extends Thread {
Table t;
MyThread2(Table t){
this.t=t;
}

public void run(){


t.printTable(7);
}
}
class SysnTest {
public static void main(String args[]) {
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

There are two ways that you can synchronize your code.
1) Using synchronize Method:-
 If you declare any method as synchronized, it is known as synchronized
method.
 Synchronized method is used to lock an object for any shared resource.
 When a thread invokes a synchronized method, it automatically acquires the
lock for that object and releases it when the thread completes its task.

Example of synchronized method:


class Table {
synchronized void printTable(int n) {

System.out.println("Multiplication Table of "+n+ " is");


for(int i=1;i<=5;i++) {
System.out.println(n+" X "+i+" = "+n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
System.out.println("---------------------------------------------------");
}
}
class MyThread1 extends Thread {
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread {
Table t;
MyThread2(Table t){
this.t=t;
}

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

public void run(){


t.printTable(7);
}
}

class SysnTest {
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

2) The synchronized statement:-


 While creating synchronized methods within classes that you create is an
easy and effective means of achieving synchronization. It will not work in all
cases.

 Imagine that you want to synchronize access to objects of a class that was
not designed for multithreaded access. That is the class does not use
synchronized methods. Further, this class was not created by you, but by a
third party and you do not have access to the source code. Thus it is not
possible for you to add synchronized to the appropriate methods within the
class. In this situation, you simply put calls to the methods defined by this
class inside a synchronized block.

 The general form is


synchronized (object)
{
// statement to be synchronized
}

 Here, object is a reference to the object being synchronized. Here is an


alternative of the preceding example. It uses a synchronized block within
the run( ) method.
public void run( )
{
synchronized(t) {
t.printTable(5);
}
}

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-52
Topic: Chapter-9 Files and Stream

Stream :
 A flow of data is referred as Stream.

 We can store the data permanently within the file, data stored in file
is often called as persistent data. To perform any input or output
operation we have to use the concept of stream.

 To get input from any source we use input stream and to write or
send the data to any destination we use output stream.

 The concept of stream is shown below

Source Destination

InputStream OutputStream
Keyboard Monitor

File
File Program

Network

Network
Printer

Types of Streams : Streams are of two types


(i) Binary Stream:
Binary stream classes performs binary input and output.
(ii) Text Stream:
Text stream classes perform text input and output.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Streams

Binary Text

Input Output
Reader Writer
Stream Stream

Binary Input Stream Hierarchy :

Object

InputStream

FileInput ByteArrayInput FilterInput ObjectInput


Stream Stream Stream Stream

DataInput BufferedInput
Stream Stream

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Binary Output Stream Hierarchy :

Object

OutputStream

ByteArray Object
FileOutputStream FilterOutputStream
OutputStream OutputStream

Buffered
DataOutputStream
OutputStream

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-53
Topic: FileInputStream and FileOutputStream

InputStream Class:
This abstract class is the superclass of all classes representing an input stream of
bytes.
Methods of InputStream
Return Type Method Name
int read() throws IOException
Reads the next byte of data from the input stream.
int read(byte[] b) throws IOException
Reads some number of bytes from the input stream and
stores them into the buffer array b.
int available() throws IOException
Returns an estimate of the number of bytes that can be
read
long skip(long n) throws IOException
Skips over and discards n bytes of data from this input
stream.
void close()throws IOException
Closes this input stream and releases any system
resources associated with the stream.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

OutputStream Class:
This abstract class is the superclass of all classes representing an output stream of
bytes.
Methods of OutputStream
Return Type Method Name
void write(byte b) throws IOException
Write the byte b to the output stream.
void write(byte[] b) throws IOException
Writes b.length bytes from the specified byte array to this
output stream.
void close()throws IOException
Closes this input stream and releases any system
resources associated with the stream.

Creating File Input Stream :


This stream is used to read byte by byte value from the file
sample.txt
Object of FileInputStream

A B C D
Program read() a b c d

FileInputStream fin = new FileInputStream(“Sample.txt”);

FileInputStream Class :
Constructors :
1. FileInputStream (String filename) throws FileNotFoundException
Creates a FileInputStream by opening a connection on actual file. It throws
FileNotFound exception if the file does not exist.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

2. FileInputStream (File file) throws FileNotFoundException


Creates a file input stream on the specified file object.
Methods :
1. int read () throws IOException
Read a single byte from this input stream.

2. int read (byte [ ] b) throws IOException.


Read up to b.length bytes of data from this input stream.

3. void skip (int b)


Skip the specified bytes from reading.

4. void close () throws IOException.


Closes the FileInputStream and releases system resources.
Creating FileOutputStream :
This stream is used to write byte by byte value to the file
sample.txt
Object of FileOutputStream

A B C D
Program write() a b c d

FileOutputStream fout = new FileOutputStream(“Sample.txt”);

FileOutputStream Class :
Constructors :
1. FileOutputStream (String filename) throws IOException
Creates a FileOutputStream by opening a connection on actual file. If file
does not exists then it creates a new file.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

2. FileOutputStream (File file) throws IOException


Creates a FileOutputStream on the specified file object.

3. FileOutputStream (String filename, boolean append) throws IOException


Creates a FileOutputStream to write byte at the end of existing file.

Methods :
1. void write(byte b) throws IOException
Write a single byte to output stream.

2. void write (byte [ ] b) throws IOException.


Write up to b.length bytes of data to this output stream.

3. void close () throws IOException.


Closes the FileOutputStream and releases system resources.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-54
Topic: Programs on File Handling

1) Write a program to display content of text file.


import java.io.*;
import java.util.*;
class FileRead
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);

System.out.println("Enter the file name ");


String filename = in.nextLine();

try
{
//open a file with InputStream
FileInputStream fin = new FileInputStream(filename);

int x = fin.read(); //read byte from file

while(x!=-1) // repeat upto End of File


{
System.out.print((char)x); //print character of file
x=fin.read();
}

fin.close(); //closes the file


}
catch(FileNotFoundException e)
{
System.out.println("Error, File does not exists");
}
catch(IOException e)
{
System.out.println(e);

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

}
} // main
} // class

Output

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Write a program to copy contents of one file into another file.


import java.io.*;
import java.util.*;

class FileCopy
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter source file name ");
String sfile = in.nextLine();
try
{
FileInputStream fin = new FileInputStream(sfile);
System.out.println("Enter the destination file name ");
String dfile = in.nextLine();

FileOutputStream fout = new FileOutputStream(dfile);


int b = fin.read();
while(b!=-1)
{
fout.write((byte) b);
b= fin.read();
}
fin.close();
fout.close();
System.out.println("File is copied");
}
catch(FileNotFoundException e)
{
System.out.println("Can't copy, source file does not exists ");
}
catch(IOException e)
{
System.out.println(e);
}
}// main
}// class

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Output

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-55
Topic: BufferedInputStream and BufferedOutputStream

Hierarchy of BufferedInputStream

InputStream

FilterInputStream

BufferedInputStream

BufferedInputStream
 The BufferedIntputStream class is a subclass of FilterlnputStream which reads
as many data as possible into its internal buffer (a protected byte array field
named buf) in a single read () call and then each read ()call reads data from
the buffer instead of the underlying stream.

 When the buffer runs out of data, the buffered stream refills its buffer from
the underlying stream.

 This class does not declare any new methods of its own, rather all the
methods are inherited from the InputStream class.

 Buffered streams are always efficient and faster than non buffered stream.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

BufferedOutputStream
 The BufferedOutputStream class is a subclass of FilterOutputStream that
stores written data in an internal buffer (a protected byte array field named
buf) until the buffer is full or the stream is explicitly flushed using the flush()
method.

 Then it writes the data onto the underlying output stream all at once.

 This class does not declare any new methods of its own, rather all the
methods are inherited from the OutputStream class.

Following program copies the contents of one file into another file using
BufferdInputStream and BufferedOutputStream. This program is much more
faster and efficient than any non buffered streams copying program.

import java.util.*;
import java.io.*;
class FastCopy{
public static void main(String [] args){
Scanner in = new Scanner(System.in);

System.out.println("Enter the source file name ");


String source_file = in.nextLine();
try{

BufferedInputStream fin =new BufferedInputStream( new


FileInputStream(source_file));

System.out.println("Enter the destination file name ");


String dest_file = in.nextLine();

BufferedOutputStream fout = new BufferedOutputStream(new


FileOutputStream(dest_file));

System.out.println("File copy is in progress");

long st_time = new Date().getTime();

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

int b =fin.read();
while(b!=-1){

fout.write((byte)b);
b=fin.read();
}
fin.close();
fout.close();
long end_time = new Date().getTime();
System.out.println("File copied successfully in "+(end_time-
st_time)+" ms");
}
catch(FileNotFoundException e){
System.out.println("Can't copy! Source file does not exists");
}
catch(IOException e){
System.out.println(e);
}
}
}

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-56
Topic: DataInputStream and DataOutputStream

Primitive Input Output


To read or write the values of primitive data types (like int, float, double, long
etc.) to the stream, then we use DataInputStream and DataOutputStream
class.

DataOuptutStream :
Following diagram shows how we create a DataOutputStream to write
primitive values into the file.

File: values.dat
Object of FileOutputStream

Object of DataOutputStream ………


………
Program

DataOutputStream dout = new DataOutputStream (new FileOutputStream (“values.dat”));


int x = 123456;
dout.writeInt(x);
dout.close();

Constructor of DataOutputStream
 DataOutputStream(OutputStream out)
Creates a new data output stream to write data to the specified underlying
output stream.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Methods of DataOutputStream Class :


Following are the various methods to write any type of primitive value to the
output stream.

1. void writeByte (byte b)


Write specified byte b to this output stream.
2. void writeShort (short s)
Write specified short s to this output stream.
3. void writeInt (int i)
Write specified int i to this output stream.
4. void writeLong (long l)
Write specified long l to this output stream.
5. void writeFloat (float f)
Write specified float f to this output stream.
6. void writeDouble (double d)
Write specified double d to this output stream.
7. void writeChar (char c)
Write specified char c to this output stream.
8. void writeBoolean (boolean b)
Write specified boolean b to this output stream.
9. void writeUTF (String s)
Write specified String s to this output stream.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

DataInputStream :
Following diagram shows how we create a DataInputStream to read primitive
values from the file.

File: values.dat
Object of FileInputStream

Object of DataInputStream ………


………
Program

DataInputStream din = new DataInputStream (new FileInputStream (“values.dat”));


int x;
x= din.readInt(); //read one integer value from the file
din.close();

Constructor of DataInputStream
DataInputStream(InputStream in)
Creates a new data input stream to read data from the specified underlying
input stream.
Methods of DataInputStream Class :
Following are the various methods to read any type of primitive value from
the input stream.
1. byte readByte ( )
2. short readShort ( )
3. int readInt ( )
4. long readLong ( )
5. float readFloat ( )
6. double readDouble ( )
7. char readChar ( )
8. boolean readBoolean ( )
9. String readUTF ( )
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Following program demonstrate how to write and read primitive values into the
file.
import java.io.*;
class ValuesIO
{
public static void main(String [] args)throws IOException
{
int x=12345;
double y=567.3455667;
char z='A';

//writing values to the file


DataOutputStream dout =
new DataOutputStream( new FileOutputStream("values.dat"));

dout.writeInt(x);
dout.writeDouble(y);
dout.writeChar(z);

dout.close();

System.out.println("Reading values from file ");


DataInputStream din =
new DataInputStream(new FileInputStream("values.dat"));

int a = din.readInt();
double b = din.readDouble();
char c= din.readChar();

System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("c="+c);
din.close();
}
}
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-57
Topic: ObjectOutputStream and ObjectInputStream

Object Stream and Serialization:


 We have seen in this chapter how we can read and write characters, bytes
and primitive data type.

 It is also possible to perform input/output on object using the object


streams.

 The object streams are created using the ObjectInputStream and


ObjectOutputStream classes.

 Suppose we want to write Employee record to the file then using the
DataOutStream method then we have to write individual field value using
various method e.g. writeInt( ), writeUTF( ) etc. In this case, we may declare
records as object and use the object classes to write and read these objects
from the files. This process is known as object serialization.

ObjectOuptutStream :
Following diagram shows how we create a ObjectOutputStream to write
object into the file.

File: record.dat
Object of FileOutputStream

Object of ObjectOutputStream ………


………
writeObject(obj)
Program
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

To save object data, you first need to open an ObjectOutputStream object.


ObjectOutputStream fout = new ObjectOutputStream(new FileOutputStream(“record.dat”));
Now, to save an object, you simply use the writeObject method of the
ObjectOutputStream class as in the following fragment.
Emp e1 = new Emp(10,”Ajay”,5000);
Emp e2 = new Emp(20,”Harry”,6000);
fout.writeObject(e1);
fout.writeObject(e2);
fout.close();

ObjectInputStream :
Following diagram shows how we create a ObjectInputStream to read
primitive object from the file.

File: record.dat
Object of FileInputStream

Object of ObjectInputStream ………


………
readObject()
Program

To read the object back in, first get an ObjectInputStream object.


ObjectInputStream in = new ObjectInputStream(new FileInputStream(“emp.dat”));

Then, retrieve the objects in the same order in which they were written,
using the readObject method.
Emp e1 = (Emp) in.readObject();
Emp e2 = (Emp) in.readObject();
 When reading back objects, you must carefully keep track of the number of
objects that were saved, their order and their types. Each call to readObject
reads in another object of the type Object. You, therefore, will need to cast
it to its correct type.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

 There is, however, one change you need to make to any class that you want
to save and restore in an object stream. The class must implement the
Serializable interface.
class Employee implements Serializable { . . . . . }

 The Serializable interface has no methods, so you don’t need to change


your classes in any way.

Following program demonstrate how to write and read object into the
file.
import java.io.*;

class Emp implements Serializable


{
int emp_no;
String name;
double salary;

Emp(int a, String b, double c)


{
emp_no=a;
name=b;
salary=c;
}
void disp( )
{
System.out.println("Emp_no :"+emp_no);
System.out.println("Name :"+name);
System.out.println("Salary :"+salary);
System.out.println("-------------------------------------------------------");
}
}
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

class ObjectIOTest
{
public static void main(String args[]) throws Exception
{
Emp e1 = new Emp(10,"XYZ",5000);
Emp e2 = new Emp(20,"ABC",6000);
Emp e3 = new Emp(30,"PQR",7000);

//writing objects into the file


ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream("emp.dat"));
out.writeObject(e1);
out.writeObject(e2);
out.writeObject(e3);
out.close();

//Reading objects from the file


System.out.println("Reading Object from the file ");
ObjectInputStream in = new ObjectInputStream(
new FileInputStream("emp.dat"));
try
{
while(true)
{
Emp ref =(Emp) in.readObject();
ref.disp();
}
}
catch(EOFException e)
{
in.close();
}
} // end of main
}// end of class
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Output:
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-58
Topic: Text Streams

Character streams can be used to read and write 16 bit Unicode characters.
Like byte streams, there are two kinds of characters stream classes, namely,
reader stream classes and writer stream classes.

Reader Stream Classes:


 Reader stream classes are designed to read character from the files.
 Reader class is the base class for all other classes in this group.
 These classes are functionally very similar to the input stream classes,
except input streams use bytes as their fundamental unit of information,
while reader streams use characters.
 The Reader class contains methods that are identical to those available
in the InputStream class, except Reader is designed to handle
characters. Therefore, reader classes can perform all the functions
implemented by the input stream classes.

Writer Stream Classes:


 Like output stream classes, the writer stream classes are designed to
perform all output operations on files.
 Only difference is that output stream classes are designed to write
bytes, the writer stream classes are designed to write characters.

Reader Classes Hierarchy:


Reader

Buffered CharArray FileReader InputSteam StringReader


Reader Reader Reader

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Writer Classes Hierarchy:

Writer

Buffered CharArray FileWriter OutputStream StringWriter


Writer Writer Writer

As pointed out earlier, subclasses of Reader and Writer implement streams


that can handles characters. The two subclasses used for handling
characters in files are FileReader and FileWriter.

BufferedReader class:
 Java BufferedReader class is used to read the text from a character-
based input stream.
 It can be used to read data line by line by readLine() method. It makes
the performance fast. It inherits Reader class.

Following Program shows how to read text file line by line.


import java.io.*;
import java.util.*;
class Test
{
public static void main(String [] args) throws Exception
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the file name ");
String filename = in.nextLine();

try{

BufferedReader fin = new BufferedReader(new FileReader(filename));


String line = fin.readLine();

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

while(line!=null){
System.out.println(line);
line=fin.readLine();
}
fin.close();
}
catch(Exception e){
System.out.println(e);
}
}
}

Writing Text Output:


 For text output, you can use a PrintWriter. A print writer can print strings
and numbers in text format. You can create PrintWriter directly on file as
shown below
PrintWriter out = new PrintWriter(new FileWriter(“data.dat”));
 To write to print writer, you use the same print() and println() methods
that you used with System.out.
 You use these methods to print numbers(int, short, long, float, double),
characters, boolean value, strings and objects.
 If the writer is set to autoflush mode, then all characters in the buffer are
sent to their destination whenever println is called.
 By default, autoflushing is not enabled. You can enable or disable
autoflushing by using the PrintWriter(Writer, boolean) constructor and
passing the appropriate boolean as the second argument.

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Following program demonstrate PrintWriter Stream.


import java.io.*;
class PrintWriterTest
{
public static void main(String args[]) throws Exception
{
PrintWriter fout = new PrintWriter("data.txt");
fout.println(12345678);
fout.println(3456.56);
fout.println(“Hello”);
fout.println( „A‟);
out.close();
}
}

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-59
Topic: File Class

File Management
 The File class is Java’s representation of a file or directory path name.
 You have learned how to read and write data from a file using streams.
 However, there is more to file management than reading and writing.
The File class encapsulate the functionality that you will need to work
with the file system or directory on the users machine.
 The File class contains several methods for working with the path name,
deleting and renaming files, creating new directories, listing the
contents of a directory, and determining several common attributes of
files and directories.
 For example, you use the File class to find out when a file was last
modified or to remove or rename the file.
 The simplest constructor for a File object takes a (full) file name. If you
don’t supply a path name, then Java uses the current directory. For
example
File f = new File(“test.txt”);
gives you file object with this name in the current directory. A call to this
constructor does not create a file with this name if it doesn’t exist.

Methods of File Class


 boolean canRead( )
indicates whether the file can be read by the current application

 boolean canWrite( )
indicates whether the file is writable.

 boolean delete( )
tries to delete the file, returns true if the file was deleted. false otherwise.

 boolean exists( )

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

true if the file or directory exists, false otherwise.


 String getName( )
returns a string that contains the file name of the File object. (does not include
path information).

 String getCanonicalPath() throws IOException


returns a string that contains the file path.

 boolean isDirectory( )
returns true if the File represents a directory, false otherwise.

 boolean isFile()
returns true if the File represents a file, false otherwise.

 boolean isHidden( )
returns true if the File object represents a hidden file or directory.

 long lastModified( )
returns the time the file was last modified or 0 if the file does not exist. Use the
Date(long) constructor to convert this value to a date.

 long length( )
returns the length of the file in bytes, or 0 if the file does not exist.

 String[] list( )
returns an array of strings that contain the names of the files and directories
contained by this File object, or null if this File was not representing a directory.

 boolean mkdir( )
makes a subdirectory whose name is given by the File object. Returns true if the
directory was successfully created, false otherwise.

 boolean renameTo(File dest)


returns true if the name was changed, false otherwise.

Following programs obtains disk information of a file:


import java.io.*;
import java.util.*;

class Sample
{

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

public static void main(String [] args) throws IOException


{
File f = new File("sample.txt");
if(f.exists())
{
System.out.println("File Name: "+ f.getName());
System.out.println("File Path: "+f.getCanonicalPath());
System.out.println("Can Write: "+f.canWrite());
System.out.println("Can Read : "+f.canRead());
System.out.println("File Size: "+f.length()+" bytes");
System.out.println("File Date: "+new Date(f.lastModified()));
System.out.println("Is File : "+f.isFile());
System.out.println("Is Dir : "+f.isDirectory());
}
else
System.out.println("File does not exists");
}
}
Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Following program obtains the list of files and subdirectory names from the
specified directory:
import java.io.*;

class Sample
{
public static void main(String [] args) throws IOException
{
File f = new File("c:\\Advanced Java ");
if(f.exists())
{
String [] names = f.list();
for(String t: names)
{
System.out.println(t);
}
}
else
System.out.println("Directory does not exists");

}
}

Output:

Course: Java Programming, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-60
Topic: Chapter-10 Applet

 Applets are small programs that are primarily used in Internet computing.
They can be transported over the Internet from one computer to another and
run using the AppletViewer or any Web browser that supports Java.

 An applet, like any application program, can do many things for us. It can
perform arithmetic operations, display graphics, play sounds, accept user
input, create animation etc.

Applet Basics:
Before Java, you used HTML to describe the layout of a web page. The basic idea
of how to use applets in a web page is simple, the HTML page must tell the
browser which applets to load and then where to put each applet on the web
page. As you might expect, the tag needed to use an applet must tell the browser
the following.
 From where to get the class files.
 How the applet sits on the web page. (size, location etc)
The browser then retrieves the class files from the Net ( or from the directory on
the user’s machine) and automatically runs the applet, using its Java Virtual
Machine.

Difference between Applet and Application:


Although both the applets and applications are Java programs, there are
significant differences between them.
 Applets do not use the main( ) method for initiating the execution of the code.
Applets, when loaded, automatically call certain methods of Applet class to
start and execute the applet code.
 Unlike stand alone applications, applets cannot be run independently. They
are run from inside a Web page using a special features known as HTML tag.
 Applets cannot read from or write to the files in the local computer.
 Applets cannot communicate with other servers on the network.
 Applets cannot run any program from the local computer.

1 Info Planet.. PH. 0257- 2241229


Course: Java Programming, Prepared By: Atul Kabra, 9422279260

All these restrictions and limitations are placed in the interest of security of
systems. These restrictions ensure that an applet cannot do any damage to the
local system.

Writing a First Applet:


Following are the steps involved in developing and testing an applet
 Building an applet code. ( . java file)
 Creating an executable applet (.class file)
 Designing a Web page using HTML tags.
 Preparing the <APPLET> tag.
 Creating HTML file which uses the APPLET tag.
 Testing the applet code by using the appletviewer or Browser.

Applet Inheritance Hierarchy :

Object

Component

Container

Window Panel

`
Frame Applet

2 Info Planet.. PH. 0257- 2241229


Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Following is the program to create “Hello World” applet.


import java.awt.Graphics;
import java.applet.Applet;

public class HelloWorldApplet extends Applet


{
public void paint(Graphics g)
{
g.drawString(“Hello World”,50,25);
}
}

As above mentioned, an applet is a Java class that runs in the web browser or
appletviewer.
Running the Applet:
To execute the applet, you need to carry out two steps.
 Compile your source files into class files.
 And then type Appletviewer <AppletCode.java> on command prompt and hit
enter key to start applet.

Designing a WEB page:


 Recall that Java applets are programs that reside on Web page. In order to run
a Java applet, it is first necessary to have a Web page that references that
applet.

 A Web page basically made up of text and HTML tags that can be interpreted
by a Web browser or an applet viewer.

 Web pages are stored using a file extension .html such as MyApplet.html.
Such files are referred as HTML files. HTML files should be stored in the same
directory as the compiled code of the applets.

3 Info Planet.. PH. 0257- 2241229


Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Applet tag:
The <APPLET> tag supplies the name of the applet to be loaded and tells the
browser how much space the applet requires. So test the above applet program,
we have to write the following
Hello.html file.
<HTML>
<APPLET CODE=”HelloWorldApplet.class” WIDTH=300 HEIGHT=300>
</APPLET>
</HTML>
Before viewing the applet in a browser, it is a good idea to test it in the
appletviewer program that is a part of the Java SDK. To use the applet viewer in
our example, enter
appletviewer Hello.html
at the command line.

 The HelloWorldApplet implements just one method, the paint method. Most
applets need to handle the paint event.
 This event occurs whenever a part of applet’s visible area is uncovered and
needs to be drawn again.
 The paint method is passed a Graphics object which we have chosen to call g.
 The Graphics class is defined in the java.awt.Graphics package which we have
imported.
 Within the paint method we call Graphics class’s drawString( ) method to
draw the string “Hello World” at the coordinate (50,25). That’s 50 pixels across
and twenty five pixels down from the upper left hand corner of the applet.

4 Info Planet.. PH. 0257- 2241229


Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-61
Topic: Methods of Graphics Class
The Graphics Class:
 Java’s Graphics class includes methods for drawing many different types of
shapes, from simple lines to polygons to text in a variety of fonts.

 To draw a shape on the screen, we may call one of the methods available in
the Graphics class.

 All the drawing methods have arguments representing end points, corners, or
starting locations of a shape as values in the Frame or Applet coordinate
system.

 To draw a shape, we only need to use the appropriate method with the
required arguments. Following is the list of Graphics class methods.

Method Description
clearRect(int x, int y, int width, int height) Clears the specified rectangle by
filling it with the background color
of the current drawing surface.
copyArea(int x,int y,int w, int height, int dx, Copies an area of the component
int dy) by a distance specified by dx and
dy.
drawArc(int x, int y, int width, int height, int Draws the outline of a circular or
startAngle, int arcAngle) elliptical arc covering the
specified rectangle.
drawLine(int x1, int y1, int x2, int y2) Draws a line, using the current
color, between the points (x1, y1)
and (x2, y2) in this graphics
context's coordinate system.
drawOval(int x, int y, int width, int height) Draws the outline of an oval.

1 Info Planet.. PH. 0257- 2241229


Course: Java Programming, Prepared By: Atul Kabra, 9422279260

drawPolygon(int[] xPoints, int[] yPoints, int Draws a closed polygon defined


nPoints) by arrays of x and y coordinates.

drawPolyline(int[] xPoints, int[] yPoints, int Draws a sequence of connected


nPoints) lines defined by arrays of x and y
coordinates.
drawRect(int x, int y, int width, int height) Draws the outline of the specified
rectangle.
drawRoundRect(int x, int y, int width, int Draws an outlined round-
height, int arcWidth, int arcHeight) cornered rectangle using this
graphics context's current color.
drawString(String str, int x, int y) Draws the text given by the
specified string, using this
graphics context's current font
and color.
fillOval(int x, int y, int width, int height) Fills an oval bounded by the
specified rectangle with the
current color.
fillRect(int x, int y, int width, int height) Fills the specified rectangle.
fillRoundRect(int x, int y, int width, int Fills the specified rounded corner
height, int arcWidth, int arcHeight) rectangle with the current color.
getColor() Gets this graphics context's
current color.
getFont() Gets the current font.
setColor(Color c) Sets this graphics context's
current color to the specified
color.
setFont(Font font) Sets this graphics context's font to
the specified font.

2 Info Planet.. PH. 0257- 2241229


Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-62
Topic: Draw a Polygon in Java Applet
 Polygon is a closed figure with finite set of line segments joining one vertex
to the other.

 The polygon comprises of set of (x, y) coordinate pairs where each pair is the
vertex of the polygon.

 The side of the polygon is the line drawn between two successive coordinate
pairs and a line segment is drawn from the first pair to the last pair.

 Graphics class provides drawPolygon() and fillPolygon() methods to draw or


fill polygon.

 Syntax:
drawPolygon(int[] xPoints, int[] yPoints, int numOfPoints);

Following program demonstrate drawPolygon()

/* <APPLET CODE="MyApplet.class" WIDTH=400 HEIGHT=400>


</APPLET> */

import java.applet.Applet;
import java.awt.Graphics;

public class MyApplet extends Applet{


public void paint(Graphics g){
int x[] ={100,200,250,200,100,50};
int y[] ={50,50,150,250,250,150};
g.drawPolygon(x,y,6);
}
}
Output
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

(100,50) (200,50)

1 2

(250,150) 6 3 (250,150)

5 4
(100,250) (200,250)

Following program demonstrate fillPolygon()

/* <APPLET CODE="MyApplet.class" WIDTH=400 HEIGHT=400>


</APPLET>*/

import java.applet.Applet;
import java.awt.Graphics;

public class MyApplet extends Applet{

public void paint(Graphics g){


int x[] ={100,200,250,200,100,50};
int y[] ={50,50,150,250,250,150};
g.fillPolygon(x,y,6);
}
}
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Output

Following program demonstrate drawPolyline()

/* <APPLET CODE="MyApplet.class" WIDTH=400 HEIGHT=400>


</APPLET>
*/
import java.applet.Applet;
import java.awt.Graphics;
public class MyApplet extends Applet{

public void paint(Graphics g){


int x[] ={100,200,250,200,100,50};
int y[] ={50,50,150,250,250,150};
g.drawPolyline(x,y,6);
}
}
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Output
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-63
Topic: Color and Font

Color:
We can also change the draw of fill color using setColor() method of Graphics
class.
Syntax:
void setColor (Color clr)
To set color we need to pass object of Color class which is declared in AWT
package. There are two methods to pass this object
(i) By calling color class constructor
Color (int red, int green, int blue)

Red Green Blue


0 0 0 Black
255 0 0 Red
0 255 0 Green
0 0 255 Blue
255 255 0 Yellow
255 0 255 Magenta
0 255 255 Cyan
127 127 127 Gray
255 255 255 White

(ii) By using predefined color objects


Color.BLACK
Color.WHITE
Color.RED
Color.CYAN
Color.GREEN etc.

Course: Advanced Java, Info Planet Programming Classes Prepared By: Atul Kabra, 9579460114
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Program to demonstrate Color object


/* <applet code="ColorApplet.class" width=700 height=700>
</applet> */
import java.awt.*;
import java.applet.*;
public class ColorApplet extends Applet
{
public void paint(Graphics g)
{
g.setColor(new Color(255,0,0));
g.drawString("Color Demonstration", 50,30);
g.drawLine(50,50,300,50);
g.fillRect(50,60,100,100);

g.setColor(Color.YELLOW);
g.fillOval(50,180,100,100);
}
}

Font:

Course: Advanced Java, Info Planet Programming Classes Prepared By: Atul Kabra, 9579460114
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

We can also change the font of text using setFont() method of Graphics class.
Syntax:
void setFont (Font font)
To set font we need to pass the object of Font class which is declared in AWT
package. The constructor of Font class takes three arguments.
Font(String fontName, int style , int size)

Constants for style parameter


FONT.PLAIN 0
Font.BOLD 1
Font.ITALIC 2
Fotnt.BOLD+Font.ITALIC 3

e.g. First create font object


Then call setFont() method and pass font object to set a font in Graphics.

Font font = new Font(“Arial”,Font.BOLD, 30);


g.setFont(font);

Program to demonstrate Font object


/* <applet code="FontApplet.class" width=700 height=700>
</applet> */

import java.awt.*;
import java.applet.*;

public class FontApplet extends Applet


{
public void paint(Graphics g)
{
g.setColor(new Color(255,0,0));

g.setFont(new Font("Arial", Font.PLAIN, 30));


g.drawString("Font Demonstration", 50,50);

g.setFont(new Font("Arial",Font.BOLD,30));

Course: Advanced Java, Info Planet Programming Classes Prepared By: Atul Kabra, 9579460114
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

g.drawString("Font Demo", 50,100);

g.setFont(new Font("Arial",Font.BOLD+Font.ITALIC,30));
g.drawString("Font Demo", 50,150);
}
}

Methods of Font Class


Sr. No. Return Type Method
1 String getName()
Returns the font name.
2 int getStyle ()
Returns the font style.
3 int getSize()
Returns the font size.
4 boolean isBold ()
Returns true if the font style is bold.
5 boolean isItalic ()
Returns true if the font style is italic.
6 boolean isPlain ()
Returns true if the font style is plain.

Course: Advanced Java, Info Planet Programming Classes Prepared By: Atul Kabra, 9579460114
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-64
Topic: Applet Life Cycle

Applet lifecycle :
Every java applet inherits a set of default behavior from the applet class. As a
result when can applet is loaded it undergoes a series of changes in its state as
shown in the following figure-

Begin
(Load Applet) init ( )
Born

start ( )

paint ( ) stop ( )

Running Idle

start ( )
destroy ( )

(Exit from browser)


Dead

End

Four method in applet class gives the framework on which we can build any
applet.
(i) init ( ) {initialization state}
This method is used for whatever initialization is needed for your applet. It is
automatically called by the browser when java creates the object for the first
time. The initialization occurs only once in the applet lifecycle.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

(ii) start ( ) {running state}


This method is automatically called after java calls the init ( ) method. It is
also called whenever the user returns to the page, containing the applet after
having gone off two other pages.
(iii) stop ( ) {ideal state}
This method is automatically called when the user moves off from the applet
page to other page.
(iv) destroy ( ) {Dead state}
Java call this method when the browser is closed and it destroy the applet
object from the memory.

Methods of Applet Class


1) void init()
- Called by browser when the applet is loaded.
2) void start()
- Called by browser to inform the applet is running.
3) void stop()
- Called by browser to inform the applet is entered in idle state.
4) void destroy()
- Called by browser to inform the applet object is destroyed from the
memory.
5) String getParameter(String name)
- Returns the value of the named parameter passed from the web page
6) void showStatus(String message)
- Display the specified message in the status bar of the browser.

Skeleton of Applet program :


public class LifeApplet extends Applet
{
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

//override init() method to perform any kind of initialization


public void init(){
}
//override start() method to start any thread activity.
public void start(){
}
//override stop() method to stop thread activity.
public void stop(){
}
//override destroy() method to release resources
public void destroy(){
}
}

Difference between Application and Applet :


Application Applet
1) Applications are stand-alone 1) Applets are small program that are
programs that can be run designed to be included in the webpage
independently without a browser. and they run inside browser or applet
viewer.
2) Java application has full access 2) Applet has no disk access or file
to local file system. system access.
3) It requires a main ( ) method of 3) It does not require main ( ) method for
its execution. its execution.
4) Application can run program 4) Applet cannot run process from the
from the local system. local machine
5) Application program is used to 5) An Applet program is used to perform
perform same task directly for small task in the webpage.
the user.
6) It can access all kind of resources 6) It can access only browser specific
available on the system. services.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Java Lecture-65
Topic: Passing Information to Applet

Applet tag and It’s Attributes:


 The basic form of APPLET tag is
<APPLET CODE=”HelloApplet.class” WIDTH=100 HEIGHT=100>

 As you seen, the CODE attributes gives the name of the class file and must
include the .class extension.

 The WIDTH and HEIGHT attributes size the window that will hold the applet.

 The text between the <APPLET> and </APPLET> tags is displayed only if the
browser cannot show applets.

 These tags are required. If any are missing, the browser cannot load your
applet.

Applet Attributes for Positioning:


 CODE
This attribute gives the name of the applet’s class file. The CODE attribute
specifies only the name of the class that contains the applet class.

 CODEBASE
This optional attribute tells the browser that your class files are found below
the directory indicated in the CODEBASE attribute.

 WIDTH, HEIGHT
These attributes are required and give the width and height of the applet,
measured in pixels.

 ALIGN
This attributes specified the alignment of the applet. Possible values are as follows
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

LEFT – Places the applet at the left margin of the page.


RIGHT – Places the applet at the right margin of the page.
BOTTOM – Places the bottom of the applet at the bottom of the text in the current line.
TOP - Places the top of the applet with the top of the text in the current line.
MIDDLE- Places the middle of the applet with the baseline of the current line.

Passing Information to Applets:


Just as applications can use command line information, applets can use
parameters that are embedded in the HTML file. This is done via the HTML tag
called PARAM along with attributes that you define. For example, suppose you
want to let the web page determine the style of the font to use in your applet.
You could use the following tag.

<APPLET CODE=”FontParaApplet.class” WIDTH=200 HEIGHT=200>


<PARAM NAME=”font” VALUE=”Helvetica” >
</APPLET>

You then pick up the value of the parameter, using the getParameter ( ) method
of the Applet class, as in the following example

public class FontParaApplet extends Applet


{
pubic void init( )
{
String fontName= getParameter(“font”);
....
}
}
Parameters are always returned as Strings. You need to convert the string to a
numeric type if that is what is called for.

Example: Write an applet to accept username in the form of parameter and print
“Hello <username>” in the Applet.
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

1) hello.html
<HTML>
<APPLET CODE="MyApplet.class" WIDTH=400 HEIGHT=400>
<param name="username" value="Atul">
</APPLET>
</HTML>

2) MyApplet.java

import java.applet.Applet;
import java.awt.*;

public class MyApplet extends Applet {

public void paint(Graphics g){

Font f = new Font("Times New Roman", Font.ITALIC, 30);


String name = getParameter("username");
g.setFont(f);
g.drawString("Hello "+name,50,30);

}
}
Course: Java Programming, Prepared By: Atul Kabra, 9422279260

Obtaining Font List from local system


To list all the fonts available to you in a Java application, use the

String [] fontNames=GraphicsEnvironment.getLocalGraphicsEnvironment().
getAvailableFontFamilyNames()

method of the GraphicsEnvironment class, which technically returns an array of


all the font family names it finds on the local system.
Here’s a small but complete sample Java program that prints out all the fonts
(font family names):

import java.awt.*;
public class ListOfFonts
{

public static void main(String[] args)


{
String fonts[] = GraphicsEnvironment.getLocalGraphicsEnvironment().
getAvailableFontFamilyNames();

for ( String fontName : fonts )


{
System.out.println(fontName);
}
}
}

Output:

You might also like