0% found this document useful (0 votes)
11 views98 pages

Unit - 1 (5 Files Merged)

The document provides an overview of Java programming, detailing the major families of programming languages, including machine, assembly, and high-level languages. It explains key concepts of object-oriented programming such as classes, objects, encapsulation, inheritance, polymorphism, and abstraction, along with their benefits and applications. Additionally, it outlines the history and features of Java, including its platform independence and security, as well as its architecture involving JVM, JDK, and JRE.

Uploaded by

abiskar430
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)
11 views98 pages

Unit - 1 (5 Files Merged)

The document provides an overview of Java programming, detailing the major families of programming languages, including machine, assembly, and high-level languages. It explains key concepts of object-oriented programming such as classes, objects, encapsulation, inheritance, polymorphism, and abstraction, along with their benefits and applications. Additionally, it outlines the history and features of Java, including its platform independence and security, as well as its architecture involving JVM, JDK, and JRE.

Uploaded by

abiskar430
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/ 98

Java Programming

Programming Languages
• Programming languages allows programmers to code software.

• The three major families of languages are:

• Machine languages

• Assembly languages

• High-Level languages

• Machine Languages

• Comprised of 1s and 0s
• Difficult to program – one misplaced 1 or 0 will cause the program to fail.

• Example
11101000101010
10111010110100

• Assembly Languages

• Assembly languages are comprised of a set of elemental commands which are


tied to a specific processor.

•Assembly language code needs to be translated to machine language before the


computer processes it

• Example
ADD 1001010, 1011010
• High-Level Languages
• The syntax of HL languages is similar to English.

HL languages into two groups:

• Procedural languages
• Object-Oriented languages (OOP)

Procedural Languages
• Procedural languages are characterized by sequential sets of linear
commands.
• The focus of such languages is on structure.

• Examples
C, COBOL, Fortran, LISP, Perl, HTML, VBScript

• Object-Oriented Languages
• programming paradigm that relies on the concept of classes and objects.

• The focus of OOP languages is not on structure, but on modeling data.

Examples
• C++, Visual Basic.NET and Java.

• Building blocks of OOP


• Classes
• Objects
• Methods
• Attributes

Object
• Object are entities that encapsulate data & related operations.

• An object can be defined as an instance of a class, and there can be multiple


instances of a class in a program.

• An Object contains both the data and the function, which operates on the data.

• Example - chair, bike, marker, pen, table, car, etc

Class
• Class is a family of objects with similar variable components and methods.
• The class is a group of similar entities.

• Example
• class - > “Expensive Cars”
• Objects - > Mercedes, BMW, Toyota
• Properties - > price, speed of cars
• Methods -> driving, reverse, braking
• Class Objects
• Fruits Mango , banana, orange, grapes
• Vegetables beetroot, onion,
• Furniture table, chair
• Subjects c, c++, java

• Bca subj
• Bsc

• Data Abstraction
• ABSTRACTION refers to the act of representing essential features without including
the background details or explanations.

• Abstraction aims to hide complexity from the users and show them only the relevant
information.

Abstraction in Java:
• Hides the underlying complexity of data.
• Helps avoid repetitive code.
• Presents only the signature of internal functionality.
• Gives flexibility to programmers to change the implementation of the abstract
behavior.
• Partial abstraction (0-100%) can be achieved with abstract classes.
• Total abstraction (100%) can be achieved with interfaces.
• Encapsulation
• The wrapping up of data and operations (that operate on the data ) into a
single unit (called class) is known as ENCAPSULATION.

• Encapsulation allows us to protect the data stored in a class from system-


wide access.

• Encapsulation in Java:
• Restricts direct access to data members (fields) of a class.
• Fields are set to private.
• Each field has a getter and setter method.
• Getter methods return the field.
• Setter methods let us change the value of the field.

• Polymorphism
• It is the ability for a message or data to be processed in more than one form.
• refers to the ability to perform a certain action in different ways.
• polymorphism can take two forms:
• method overloading and method overriding.

• Polymorphism in Java:
• The same method name is used several times.
• Different methods of the same name can be called from the object.
• All Java objects can be considered polymorphic.
• Example of static polymorphism in Java is method overloading.
• Example of dynamic polymorphism in Java is method overriding.

• Inheritance
• Inheritance is the capability of one class of things to inherit capabilities or
properties from other class.

• makes it possible to create a child class that inherits the fields and methods of
the parent class.

• Parent classes are also called superclasses or base classes,


• while child classes are known as subclasses or derived classes.

• Java uses the extends keyword to implement the principle of inheritance in


code.
• Types of Inheritance:
Single Inheritance:
• refers to a child and parent class relationship where a class extends the
another class.
• Multilevel inheritance:
• refers to a child and parent class relationship where a class extends the child
class.
• For example class A extends class B and class B extends class C.
• Hierarchical inheritance:
• refers to a child and parent class relationship where more than one classes
extends the same class.
• For example, class B extends class A and class C extends class A.
• Multiple Inheritance:
• refers to the concept of one class extending more than one classes, which
means a child class has two parent classes.
• Java doesn’t support multiple inheritance.

• Message passing
One object interacts with another object by invoking methods on
that object.
• It is also referred to as Method Invocation.
Benefits of OOP
• OOP models complex things as reproducible, simple structures.
• Reusable, OOP objects can be used across programs.
• Allows for class-specific behavior through polymorphism.
• Easier to debug, classes often contain all applicable information to
them.
• Secure, protects information through encapsulation.
• OOP is faster and easier to execute
• OOP provides a clear structure for the programs
• OOP makes it possible to create full reusable applications with less
code and shorter development time

1. Re-usability
• reusing some facilities rather than building it again and again.
• This is done with the use of a class.
2. Data Redundancy
• created at the place of data storage -where the same piece of data is in two
separate places.
• If we want a similar functionality in multiple classes we can do it by writing
common class definitions for the similar functionalities and inherit them.
3. Code Maintenance
• It helps from doing re-work.
• It is always easy and time-saving to maintain and modify the existing codes
with incorporating new changes into it.
4. Security
• Using data hiding and abstraction mechanism, we are filtering out limited
data to exposure.
• we are maintaining security and providing necessary data to view.

5. Design Benefits
• Object Oriented Programs forces the designers to have a longer and
extensive design phase, which results in better designs.
• After a time when the program has reached some critical limits, it is easier to
program all the non-OOP’s one separately.
6. Better productivity
• having more inbuilt features and easier to read, write and maintain.
• A good number of libraries with useful functions in abundance make it
possible.
7. Easy troubleshooting
• common issues
• advantage of using encapsulation in OOP
8. Polymorphism Flexibility
• means polymorphism is flexibility
• It’s simplicity
• Extensibility
9. Problems solving
• Decomposing a complex problem into smaller ones or discrete components is
a good practice.
• OOP is specialized in this behavior
• it breaks down the code into bite-sized – one object at a time

• Applications of Object-Oriented Programming


• User interface design such as windows, menu.
• Real Time Systems
• Simulation and Modeling
• Object oriented databases
• AI and Expert System
• Neural Networks and parallel programming
• Decision support and office automation systems etc.

• Real-Time Systems Design


• Object-oriented techniques make it easier to control the complexities related
to real-time system design.
• Ex : Flight Control System
• It has two main types
1. Hard Real-Time System
• purely deterministic and 100% time constraint system
• Ex: Satellite launching stations, Missile launching stations and Air Bags
Controls in cars etc.
2. Soft Real-Time System
• deadline is not compulsory for every time but the process should
processed and give the result
• Ex: personal computers, audio and video systems etc.

• Simulation and Modelling System


• Modeling and understanding interactions explicitly are required for
simulating complex systems.
• Object-oriented Programming gives the substitute approach for making these
complex modeling systems easier.

• Object-Oriented Database:
• represent data in the form of objects.
• model complex data easily and captures the relationships in a natural way.
• these databases try to balance a relationship between the real-world and
database objects.

• Client-Server System
• object-oriented programming, Client-Server Systems offer the IT
infrastructure
• i.e operating systems, networks, and hardware etc, creating object-oriented
Client-Server Internet (OCSI) applications.
• These applications have three major technologies:
• The Client Server
• Object-Oriented Programming
• The Internet

• Neural Networking And Parallel Programming:


• the whole time-varying process is divided into numerous time intervals.
• Then, neural networks are developed in a specific time interval to scatter the
load of several networks.
• OOP simplifies the whole process by simplifying the estimation and
prediction capability of networks.

• Office Automation Systems:


• formal and informal electronic systems mainly concerned with information
sharing and communication
• Ex: email, Word processing, Web calendars, Desktop publishing etc.

• AI Expert Systems:
• computer applications which use databases of expert knowledge to make
decisions in many areas as medical diagnosis.
• Their advice and decisions are beyond the reach of a human brain as they are
reliable, highly responsive and understandable.

• Java
• developed by Sun Microsystems
• initiated by James Gosling
• released in 1995
• latest release of the Java Standard Edition is Java SE 8
• Write Once, Run Anywhere

Java Version History


Version Name Coad Name Release Date Description
Java Alpha and Beta 1995 •It was the 1st version but was having
unstable APIs and ABIs.
•It was the 1st version but was having
unstable APIs and ABIs.

JDK 1.0 Oak January 1996 •1st stable version


JDK 1.1 February 1997 •AWT Event modelling retooling.
•Added Inner class, Java Beans, JDBC,
RMI, Reflection, JIT
•Added Inner class, Java Beans, JDBC,
RMI, Reflection, JIT
J2SE 1.2 Playground December 1998 •JDK replaced by J2SE.
•Support strictfp keyword.
•Swing API integrated with core classes.
•Collection framework.

J2SE 1.3 Kestrel May 2000 •HotSPot JVM included


•RMI Modified.
•JNDI(Java Naming and Directory Interface) Supported
•JPDA(Java Platform Debugger Architecture).
•Included Proxy Classes.
J2SE 1.4 Merin February 2002 •Support assert Keyword.
•Improvement in libraries.
•Support Regular expression.
•Support Exception Chaining.
•Support Exception Chaining.
•Included Java Web Start.
•Support API Preferences (java.util.prefs).
J2SE 5.0 Tiger September 2004 •Included Generics, Metadata, Autoboxing/Unboxing,
Enumerations, Varargs.
•Enhanced for each loop.
•Support static imports.

Java SE 6 Mustang December 2006 •Support Win9x version.


•Support Scripting languages.
•Improved Swing performance.
•Support JDBC 4.0
•Upgrade of JAXB to 2.0.
•Improvement in GUI and JVM.
Java SE 7 Dolphine July 2011 •Support of dynamic language in JVM.
•Included 64-bit pointers.
•Support string in the switch.
•Support resource management in the try block.
•Support binary integer literals.
•Support underscore in numeric literals.
•Support multiple exceptions.
•Included I/O library.

Java SE 8(LTS) March 2014 •Support of JSR 335 and JEP 126.
•Support unsigned integer.
•Support Date and time API.
•Included JavaFX.
•Support Windows XP.
Java SE 9 September 2017 •Support multiple gigabyte heaps.
•Included garbage collector.
Java SE 10 March 2018 •Support local variables type inference.
•Support local variables type inference.
•Included Application class.

Java SE 11(LTS) September 2018 •Support bug fixes.


•Include long term support(LTS).
•Support transport layer security.

Java SE 12 March 2019 •Support JVM Constant API.


•Include CDS Archives.

Java SE 13 September 2019 •Updated Switch Expressions.


•Include Text Blocks.
•Support Legacy socket API.

Java SE 14 March 2020 •Support Event Streaming.


•Improved NullPointerException.
•Removal of the Concurrent Mark Sweep
(CMS) in the garbage collector.

Java SE 15 September 2020


Java SE 16 March 2021
Java SE 17(LTS) September 2021
• Java supports
• Object Oriented
• Java can be easily extended since it is based on the Object model
• Platform Independent
• when Java is compiled, it is not compiled into platform specific machine,
rather into platform independent byte code.
• This byte code is distributed over the web and interpreted by the Virtual
Machine (JVM) on whichever platform it is being run on.
• Simple
• Java is designed to be easy to learn.
• Secure
• secure feature it enables to develop virus-free, tamper-free systems
• Architecture-neutral
• Java compiler generates an architecture-neutral object file format, which
makes the compiled code executable on many processors, with the
presence of Java runtime system.

Applications of Java

• Java is not only used in softwares, it is used in designing hardware


controlling software components.
• Developing Desktop Applications.
• Web Applications like Linkedin.com, Snapdeal.com etc.
• Mobile Operating System like Android.
• Embedded Systems.
• Robotics and games etc.

Features of Java
1) Simple
2) Object Oriented
3) Robust
4) Platform Independent
5) Secure
6) Multi Threading
7) Architectural Neutral
8) Portable
9) High Performance
10) Distributed
• Portable
• Being architecture-neutral and having no implementation dependent
aspects of the specification makes Java portable
• Robust
• eliminate error prone situations by emphasizing
• Multithreaded
• write programs that can perform many tasks simultaneously.
• Interpreted
• Java byte code is translated on the fly to native machine instructions and
is not stored anywhere
• High Performance
• Just-In-Time compilers, Java enables high performance.
• Distributed
• distributed environment of the internet
• Dynamic
• more dynamic than C or C++ since it is designed to adapt to an evolving
environment.

• Platform independent

The softwares
• Linux 7.1 or Windows xp/7/8 operating system
• Java JDK 8
• Microsoft Notepad or any other text editor

Java JVM, JDK and JRE


• Java virtual Machine(JVM) - virtual Machine that provides runtime
environment to execute java byte code.
• It enables features such as automated exception handling, Garbage-
collected heap.

JVM Architecture
• Class Loader : Class loader loads the Class for execution.
• Method area : Stores pre-class structure as constant pool.
• Heap : Heap is a memory area in which objects are allocated.
• Stack : Local variables and partial results are store here.
• Each thread has a private JVM stack created when the thread is created.
• Program register : Program register holds the address of JVM instruction currently being
executed.
• Native method stack : It contains all native used in application.
• Executive Engine : Execution engine controls the execute of instructions contained in the
methods of the classes.
• Native Method Interface : Native method interface gives an interface between java code
and native code during execution.
• Native Method Libraries : Native Libraries consist of files required for the execution of
native code.

Difference between JDK and JRE


JRE
The Java Runtime Environment (JRE) provides the
• libraries, the
• Java Virtual Machine, and other components to run applets and
applications written in the Java programming language.
• JRE does not contain tools and utilities such as compilers or
debuggers for developing applets and applications.

• JDK
• The JDK also called Java Development Kit is a superset of the JRE, and
contains everything that is in the JRE, plus tools such as the
compilers and debuggers necessary for developing applets and
applications.
Basic Program
public class MyFirstJavaProgram {
public static void main(String[] args) {
System.out.println("Hello World"); // prints Hello World
}
}
1. Open a notepad and write the code as above.
2. Save the file as: MyFirstJavaProgram.java
3. Open command prompt and go to the directory where you saved
your first java program assuming it is saved in C drive.
4. javac MyFirstJavaProgram.java - to compile
5. java MyFirstJavaProgram - to run

• class : class keyword is used to declare classes in Java


• public : It is an access specifier. Public means this function is visible to all.
• static : static is again a keyword used to make a function static.
To execute a static function you do not have to create an Object of the class.
The main() method here is called by JVM, without creating any object for class.

• void : It is the return type, meaning this function will not return anything.

• main : main() method is the most important method in a Java program.


This is the method which is executed, hence all the logic must be inside the main()
method.
If a java class is not having a main() method, it causes compilation error.

• String[] args : This represents an array whose type is String and name is args.

• System.out.println : This is used to print anything on the console like printf in C


language.

• C:\> javac MyFirstJavaProgram.java


• C:\> java MyFirstJavaProgram

Output
• Hello World
UNIT - II

Constants, Variables, Data Types - Operators and Expressions –


Decision Making and Branching: if, if...Else, nested if, switch, ?:
operator - Decision Making and Looping: while, do, for –Labelled
loops. Classes, Objects and Methods

Variables in Java

• to store any information - store it in an address of the computer.


• complex address where we have stored our information - name that
address
• The naming of an address - variable.
• Variable is the name of memory location.
SYNTAX
datatype variableName;
datatype refers to type of variable
variableName can be any like empid, name, age

• Java Programming language defines mainly three kind of variables.


• Instance Variables
• Static Variables (Class Variables)
• Local Variables

Instance variables in Java


• Instance variables are declared inside a class but outside any method,
constructor or block.
class Student
{
String name;
int age;
}
name and age are instance variable of Student class.
• Static variables in Java
• Static are class variables declared with static keyword.
• Static variables are initialized only once.
• Static variables are also used in declaring constant along with final keyword.
• static variable need not be called from object.
• It is called by classname.static_variable_name

class Student
{
String name;
int age;
static int instituteCode=1101;
}
Here instituteCode is a static variable.
Each object of Student class will share instituteCode property.

Local variables in Java


• Local variables are declared in method, constructor or block.
• Local variables are initialized when method, constructor or block start and
will be destroyed once its end.
• Local variable reside in stack.
• Access modifiers are not used for local variable.

float getDiscount(int price)


{
float discount;
discount=price*(20/100);
return discount;
}

discount is a local variable.

Variable Scope in Java


• Scope of a variable decides its accessibility throughout the program.
• Local variable:
• Scope is limited to the block in which it is declared.
• For example, a variables declared inside a function will be accessible only
within this function.
• Instance variable:
• scope - depends on the access-modifiers (public, private, default).
• If variable is declared as private then it is accessible within class only.
• public then it is accessible for all and throughout the application.
• default the it is accessible with in the same package.
Constants
• A constant is a variable whose value cannot change once it has been
assigned.

Numeric Constants
• Integer Constant
• An Integer constant refers to a series of digits. There are three types of
integer as follows
• Integer - ex 23, 411, 700000, 17.33
• Octal integer - It allows us any sequence of numbers or digits from 0 to 7
with leading 0(Zero) and it is called as Octal integer.
Example: 00, 011, 0425 etc.
• Hexadecimal integer - It allows the sequence which is preceded by 0X or
0x and it also allows alphabets from 'A' to 'F' or 'a'
to 'f' ('A' to 'F' stands for the numbers '10' to '15') it
is called as Hexadecimal integer.
Example: 0x7, 00X, 0A2B etc.

Real Constant
• It allows us fractional data and it is also called as floating point constant.
• It is used for percentage, height and so on.
• Example: 0.0234, 0.777, -1.23 etc.

Character Constants
There are four types of Character Constants
1. Character Constant
• It allows us single character within pair of single quotes.
• Example: 'A', '7', '/' etc.

2. String Constant
• It allows us the series of characters within pair of double quotes.
• Example: "welcome", "A" etc.
• 3. Symbolic Constant
• requires repeatedly and if we want to make changes then we have to make
these changes in whole program where this variable is used.
• For this purpose, Java provides ‘final’ keyword to declare the value of variable
as follows.
• Syntax : final type Symbolic_name=value;
• final float PI=3.1459;

• 4. Backslash character Constant


Constant Importance
'\b' Back space
'\t' Tab
'\n' New line
'\\' Backslash
'\" Single quote
'\"' Double qoute

Data Types in Java


• Data types specify size and the type of values that can be stored in an
identifier.
• data types are classified into two categories :
1. Primitive Data type
2. Non-Primitive Data type

• 1) Primitive Data type


• A primitive data type can be of eight types :
Primitive Data types
char boolean byte short int long float double
• These eight primitive type can be put into four groups
1. Integer
This group includes byte, short, int, long

byte : It is 1 byte(8-bits) integer data type.


Value range from -128 to 127.
Example: byte b=10;

short : It is 2 bytes(16-bits) integer data type.


Value range from -32768 to 32767.
Example: short s=11;

int : It is 4 bytes(32-bits) integer data type.


Value range from -2147483648 to 2147483647.
Example: int i=10;

long : It is 8 bytes(64-bits) integer data type.


Value range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
Example: long l=100012;

2. Floating-Point Number
• This group includes float, double
float : It is 4 bytes(32-bits) float data type.
Default value 0.0f.
Example: float ff=10.3f;

double : It is 8 bytes(64-bits) float data type.


Default value 0.0d.
Example: double db=11.123;
Characters
• This group represent char, which represent symbols in a character set, like letters
and numbers.
• char :
It is 2 bytes(16-bits) unsigned unicode character.
Range 0 to 65,535.
Example: char c='a';

Boolean
This group represent boolean, which is a special type for representing
true/false values.
They are defined constant of the language.
Example: boolean b=true;

2) Non-Primitive(Reference) Data type


• A reference data type is used to refer to an object.
• Object can be instance of any class or entity.
• A reference variable is declare to be of specific and that type can
never be change.
• Example: String str, here str is a reference variable of type String.

Identifiers in Java
• Name used for classes, methods, interfaces and variables are
called Identifier.
• Class and objects:
• Every class is data type and it is also considered as user-defined data types.
• String:
• A string represents a sequence of characters like India, ABC123, etc.
• The simplest way to create a string object is by storing sequence of characters
into string type variable like this:
• String str = “Universe”;
• Array:
• An array in java is an object which is used to store multiple variables of the
same type. These variables can be primitive or non-primitive data type.
• Example : int [ ] scores;
• Interface:
• An interface is declared like a class but the only difference is that it contains
only final variables and method declarations.
• It is a fully abstract class.

• Difference between Primitive and Non-primitive Data types in Java

1. Primitive data types are predefined in Java whereas non-primitive data types
are created by programmers. They are not predefined in Java.

2. In primitive data type, variables can store only one value at a time whereas,
in non-primitive data type, we can store multiple values either the same type
or different type or both.

3. All the data for primitive type variables are stored on the stack whereas, for
reference types, the stack holds a pointer to the object on the heap.

• Rules to be followed

• All identifiers must start with either a letter(a to z or A to Z) or currency


character($) or an underscore.

• After the first character, an identifier can have any combination of characters.

• Java keywords cannot be used as an identifier.

• Identifiers in Java are case sensitive, foo and Foo are two different identifiers.

Some valid identifiers are: int a, class Car, float amount etc.
Java Operators
Symbol which tells to the compiler to perform some operation.
• Java operators can be divided into following categories:
• Arithmetic operators
• Relation operators
• Logical operators
• Bitwise operators
• Assignment operators
• Conditional operators
• Misc operators
• Special operators

Arithmetic operators
• perform operations like:
• addition, subtraction etc and helpful to solve mathematical expressions.
Operator Description
+ adds two operands
- subtract second operands from first

* multiply two operand


/ divide numerator by denumerator

% remainder of division
++ Increment operator increases integer value by one

-- Decrement operator decreases integer value by one

class Arithmetic_operators1{
public static void main(String as[]) {
int a, b, c;
a=10; b=2; c=a+b;
System.out.println("Addtion: "+c);
c=a-b;
System.out.println("Substraction: "+c);
c=a*b;
System.out.println("Multiplication: "+c);
c=a/b;
System.out.println("Division: "+c);
b=3;
c=a%b;
System.out.println("Remainder: "+c);
a=++a;
System.out.println("Increment Operator: "+a);
a=--a;
Relation operators
• to test comparison between operands or values.
• to test whether two values are equal or not equal or less than or
greater than etc.
Operator Description
== Check if two operand are equal
!= Check if two operand are not equal.
> Check if operand on the left is greater than operand on
the right
< Check operand on the left is smaller than right operand

>= check left operand is greater than or equal to right


operand
<= Check if operand on left is smaller than or equal to right
operand

class Relational_operators1{
public static void main(String as[])
{
int a, b;
a=40; b=30;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}
Logical operators
• to check conditional expression

Operator Description Example

&& Logical AND (a && b) is false

|| Logical OR (a || b) is true

! Logical NOT (!a) is false

class Logical_operators1{
public static void main(String as[])
{
boolean a = true;
boolean b = false;
System.out.println("a && b = " + (a&&b));
System.out.println("a || b = " + (a||b) );
System.out.println("! (a && b) = " + !(a && b));
}
}

Bitwise operators
• Bitwise operators are used to perform operations bit by bit.
• Java defines several bitwise operators that can be applied to the
integer types long, int, short, char and byte.

Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift
• The bitwise shift operators shifts the bit value.
• The left operand specifies the value to be shifted and the right
operand specifies the number of positions that the bits in the value
are to be shifted.
• Both operands have the same precedence.
• truth table for bitwise &, | and ^
a b a&b a|b a^b

0 0 0 0 0

0 1 0 1 1

1 0 0 1 1

1 1 1 1 0

class Bitwise_operators1{
public static void main(String as[]) {
int a = 50; int b = 25; int c = 0;
c = a & b;
System.out.println("a & b = " + c );
c = a | b;
System.out.println("a | b = " + c );
c = a ^ b;
System.out.println("a ^ b = " + c );
c = ~a;
System.out.println("~a = " + c );
c = a << 2;
System.out.println("a << 2 = " + c );
c = a >> 2;
System.out.println("a >>2 = " + c );
c = a >>> 2;
System.out.println("a >>> 2 = " + c );
Assignment Operators
• to assign a value to a variable.
Operator Description Example
= assigns values from right side operands to left side a = b
operand
+= adds right operand to the left operand and assign a+=b is same as a=a+b
the result to left

-= subtracts right operand from the left operand and a-=b is same as a=a-b
assign the result to left operand

*= mutiply left operand with the right operand and a*=b is same as a=a*b
assign the result to left operand

/= divides left operand with the right operand and a/=b is same as a=a/b
assign the result to left operand

%= calculate modulus using two operands and assign a%=b is same as a=a%b
the result to left operand

Conditional operator
• It is also known as ternary operator because it works with three
operands.
• It is short alternate of if-else statement.
• It can be used to evaluate Boolean expression and return either true
or false value

• epr1 ? expr2 : expr3

class Conditional_operators1{
public static void main(String as[])
{
int a, b; a = 20;
b = ( (a == 1) ? 30: 40 ) ;
System.out.println( "Value of b is : " + b );
b = ( (a == 20) ? 30: 40 );
System.out.println( "Value of b is : " + b );
}
}
Special Operators
• instanceof operator
• member selection operator(.)

instanceof operator
Object reference operator and returns true is the object on the
left hand side is an instance of the class given.
Example
• person instanceof student
is true if the object person belongs to the class student,
otherwise it is false

Dot Operator
• (.) - used to access the instance variables and methods of class
objects.

• Example
person1.age
person1.age

Operator Meaning Associativity

[] () . array access, method invoke, object member access Left-to-right

++ -- + - increment, decrement, unary plus and minus Right-to-left

! ~ (type) new negation, bitwise NOT, type cast, object creation Right-to-left

*/% multiplication, division, modulo Left-to-right


+- addition, subtraction Left-to-right
+ string concatenation Left-to-right
<< >> >>> shift Left-to-right
< <= > >= relational Left-to-right
instanceof type comparison Left-to-right
== != equality Left-to-right
& bitwise AND Left-to-right
^ bitwise XOR Left-to-right
| bitwise OR Left-to-right
&& logical AND Left-to-right
|| logical OR Left-to-right
?: ternary Right-to-left
= simple assignment Right-to-left
+= -= *= /= %= &= compound assignment Right-to-left
^= |= <<= >>= >>>= compound assignment Right-to-left
Decision Making
• Decision making structures have
• one or more conditions to be evaluated or tested by the program,
along
• with a statement or statements that are to be executed

• Decision Making :

• if,
• if-else,
• switch,
• break,
• continue,
• jump

• if
• 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
}

Example
public class IfDemo1 {
public static void main(String[] args)
{
int marks=95;
if(marks > 90){
System.out.print(“A Grade");
}
}
}
if-else
• if we want to do something else if the condition is false.
• 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
}

Example :
public class IfElseDemo1 {
public static void main(String[] args)
{
int marks=50;
if(marks > 90){
System.out.print(“A Grade ");
}
else {
System.out.print(“B Grade");
}
}
}
if-else-if ladder Statement
• if-else-if ladder statement is used for testing conditions.
• It is used for testing one condition from multiple statements.
Syntax
if(condition1) {
//code for if condition1 is true
}
else if(condition2) {
//code for if condition2 is true
}
else if(condition3) {
//code for if condition3 is true
}
...
Else {
//code for all the false conditions
}

Nested-if

• 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
}
}
Example
public class NestedIfDemo1 {
public static void main(String[] args)
{
int age=25;
int weight=70;
if(age>=18) {
if(weight>50)
{
System.out.println("You are eligible");
break;

}
if(weight>40 && weight <=45)
{
System.out.println("You are eligible");

}
break;
}
}
}

switch-case
• The switch statement is a multi way 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;
}
• The default statement is optional.
• The break statement is used inside the switch to terminate a statement sequence.

Rules while using the switch statement:


There can be one or N numbers of cases.
The values in the case must be unique.
Each statement of the case can have a break statement. It is optional.
Example
public class SwitchDemo1{
public static void main(String[] args)
{
int day = 1;
String dayName;
switch (day) {
case 1:
dayName = "Today is Monday";
break;
case 2:
dayName = "Today is Tuesday";
break;
default:
dayName = "Invalid day";
break;
}
System.out.println(dayName);
}
}
Jump
• These three statements transfer control to other part of the program
• 3 jump statement:
• break, continue and return.
• Break:
• Terminate a sequence in a switch statement (discussed above).
• To exit a loop.
• Used as a “civilized” form of goto fun1();
• Using break to exit a Loop
• immediate termination of a loop
• Break, when used inside a set of nested loops, will only break out of the
innermost loop.
Example
class BreakLoopDemo
{
public static void main(String args[])
{
// Initially loop is set to run from 0-9
for (int i = 0; i < 10; i++) {
// terminate loop when i is 5.
if (i == 5)
break; / 9
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}

Output
i: 0
i: 1
i: 2
i: 3
i: 4
Loop complete.
Using break as a Form of Goto
Java does not have a goto statement.
A Label is use to identifies a block of code.
Syntax:
label:
{
statement1;
statement2;
statement3;
.
.
}

Continue

• Sometimes it is useful to force an early iteration of a loop.


• continue running the loop but stop processing the remainder of the code in
its body for this particular iteration.
Example
class ContinueDemo {
public static void main(String args[]) {
for (int i = 0; i < 10; i++) {
// If the number is even skip and continue
if (i%2 == 0)
continue;
// If number is odd, print it
System.out.print(i + " ");
}
}
}
Output:
13579

Return
• The return statement is used to explicitly return from a method.
• That is, it causes a program control to transfer back to the caller of the method.
Example:
class Return {
public static void main(String args[]) {
boolean t = true;
System.out.println("Before the return.");

if (t)
return ;

// Compiler will bypass every statement after return

System.out.println("This won't execute.");


}
}

Output
Before the return.

Loops
• loops are used to execute a set of instructions/functions repeatedly.
• for loop
• while loop
• do-while loop
• for loop
for statement consumes the initialization, condition and increment/decrement
in one line, providing shorter, easy to debug structure of looping.

Syntax
for (initialization condition; testing condition; increment/decrement)
{
statement(s)
}
• Initialization condition
• we initialize the variable in use.
• It marks the start of a for loop.
• already declared variable can be used or a variable can be declared, local to loop
only.
• Testing Condition
• It is used for testing the exit condition for a loop.
• It must return a boolean value.
• It is also an Entry Control Loop as the condition is checked prior to the execution of
the loop statements.
• Statement execution
• Once the condition is evaluated to true, the statements in the loop body are
executed.
• Increment/ Decrement:
• It is used for updating the variable for next iteration.
• Loop termination
• When the condition becomes false, the loop terminates marking the end of its life
cycle.

Example
class forLoopDemo {
public static void main(String args[]) {
// for loop begins when x=2 , and runs till x <=4
for (int x = 2; x <= 4; x++)
System.out.println("Value of x:" + x);
}
}

Output
Value of x:2
Value of x:3
Value of x:4

while loop
• A while loop is a control flow statement that allows code to be executed
repeatedly based on a given Boolean condition.
• The while loop can be thought of as a repeating if statement.

Syntax
while (boolean condition)
{
loop statements...

}
• While loop starts with the checking of condition.
• If it evaluated to true, then the loop body statements are executed
otherwise first statement following the loop is executed.
• it is Entry control loop
• Once the condition is evaluated to true, the statements in the loop
body are executed.
• Normally the statements contain an update value for the variable
being processed for the next iteration.
• When the condition becomes false, the loop terminates which marks
the end of its life cycle.

Example
class whileLoopDemo {
public static void main(String args[]) {
int x = 1;
// Exit when x becomes greater than 4
while (x <= 4) {
System.out.println("Value of x:" + x);
// Increment the value of x for next iteration
x++;
}
}
}
Output
Value of x:1
Value of x:2
Value of x:3
Value of x:4

• do while
• do while loop is similar to while loop with only difference that it checks for
condition after executing the statements,
• Its an Exit Control Loop.

Syntax
do
{
statements..
}
while (condition);
• do while loop starts with the execution of the statement(s).
• There is no checking of any condition for the first time.
• After the execution of the statements, and update of the variable
value, the condition is checked for true or false value.
• If it is evaluated to true, next iteration of loop starts.
• When the condition becomes false, the loop terminates which marks
the end of its life cycle.
• It is important to note that the do-while loop will execute its
statements atleast once before any condition is checked.
• Its exit control loop.

Example
class dowhileloopDemo {
public static void main(String args[]) {
int x = 21;
do {
// The line will be printed even if the condition is false
System.out.println("Value of x:" + x); ( X=21)
x++; (X=22)
}
while (x < 20);
}
}
Output
Value of x: 21

Labeled For Loop


• We can have a name of each Java for loop.
• use label before the for loop
• It is useful if we have nested for loop so that we can break / continue specific
for loop.

Syntax
labelname:
for(initialization;condition;incr/decr){
//code to be executed
}
Example
public class LabeledForExample {
public static void main(String[] args) {
//Using Label for outer and for loop
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if ( i==2 && j==2){
break aa;
}
System.out.println(i+" "+j);
}
}
}
}

Output
11
12
13
21

Comparison for loop while loop do while loop


Introduction The Java for loop is a control The Java while loop is a The Java do while loop is
flow statement that iterates a control flow statement that a control flow statement
part of the programs multiple executes a part of the that executes a part of
times. programs repeatedly on the the programs at least
basis of given boolean once and the further
condition. execution depends upon
the given boolean
condition.
When to use If the number of iteration is If the number of iteration is If the number of
fixed, it is recommended to not fixed, it is recommended iteration is not fixed and
use for loop. to use while loop. you must have to
execute the loop at least
once, it is recommended
to use the do-while loop.
Syntax for(init;condition;incr/decr){
while(condition){ //code to be do{ //code to be
// code to be executed } executed } executed
}while(condition);
Example //for loop for(int //while loop int i=1; //do-while loop int i=1;
i=1;i<=10;i++){ while(i<=10){ do{
System.out.println(i); } System.out.println(i); i++; } System.out.println(i);
i++; }while(i<=10);
Syntax for for(;;){ //code to be executed while(true){ //code to be do{ //code to be
infinitive loop } executed } executed }while(true);

Create a Class
• To create a class, use the keyword class
• Create a class named "Main" with a variable x:

public class Main {


int x = 5;
}

Create an Object
an object is created from a class.
already created the class named MyClass, so now we can use this to create
objects.
• Create an object of MyClass,
• specify the class name, followed by the object name, and use the
keyword new

public class Main {


int x = 5;
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}

Java Class Methods

• methods are declared within a class, and that they are used to
perform certain actions.

• Create a method named myMethod() in Main

public class Main {


static void myMethod() {
System.out.println("Hello World!");
}
}

• myMethod() prints a text when it is called.


• Inside main, call myMethod():

public class Main {


static void myMethod() {
System.out.println("Hello World!");
}

public static void main(String[] args) {


myMethod();
}
}
Output
"Hello World!"
• https://www.studytonight.com/java/datatypes-and-identifier.php

Unit III
Arrays, Strings – Interfaces: Multiple Inheritance –
Packages: Putting Classes together – Multithreaded Programming

Arrays
• Collection of similar data types
• Static data structure - size of an array must be specified at the time of
its declaration
• Array starts from zero index and goes to n-1 where n is length of the
array
• treated as an object and stores into heap memory
• Array can be single dimensional or multidimensional
3 step process
1) Declaring your Array
2) Constructing your Array
3) Initialize your Array
Features of Array
• It is always indexed. Index begins from 0.
• It is a collection of similar data types.
• It occupies a contiguous memory location.
• It allows to access elements randomly.

• Single Dimensional Array


• use single index to store elements

Array Declaration Syntax

datatype[] arrayName;
or
datatype arrayName[];

• The arrayName can be any valid array name and datatype can be any
like: int, float, byte etc.
int[ ] arr;
char[ ] arr;
short[ ] arr;
long[ ] arr;
int[ ][ ] arr;
• Initialization of Array
• Initialization is a process of allocating memory to an array.
• At the time of initialization, we specify the size of array to reserve memory
area.

• Initialization Syntax
arrayName = new datatype[size]

• The arrayName is the name of array, new is a keyword used to allocate memory
and size is length of array.

both declaration and initialization


• Datatype[] arrayName = new datatype[size]
Example
class arraycreation {
public static void main (String[] args) {
// declares an Array of integers.
int[] arr;
// allocating memory for 5 integers.
arr = new int[5];
// initialize the elements of the array
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i + " : "+ arr[i]);
}
}
• Output
• Element at index 0 : 10
• Element at index 1 : 20
• Element at index 2 : 30
• Element at index 3 : 40
• Element at index 4 : 50

Multidimensional Arrays
• array containing one or more arrays.

Example
int[][] intArray = new int[10][20];

class multiDimensional {
public static void main(String args[]) {
// declaring and initializing 2D array
int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };
// printing 2D array
for (int i=0; i< 3 ; i++) {
for (int j=0; j < 3 ; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}

Addition of 2 Matrices in Java


class Testarray5{
public static void main(String args[]){
//creating matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}
• Output
Compile by: javac Testarray5.java
Run by: java Testarray5
268
6 8 10
Matrix multiplication

Example
public class MatrixMultiplicationExample{
public static void main(String args[]){
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
int c[][]=new int[3][3]; //3 rows and 3 columns
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++) {
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
}
}
}
Output
666

String
• string is an object that represents sequence of char values.
Declaration
char[] ch={'j','a','v','a'};

String s=new String(ch);

String s="java";

• String class - > methods to perform operations on strings such as


• compare(), concat(), equals(), split(), length(), replace(),
compareTo(), intern(), substring() etc.
• The java.lang.String class
implements Serializable, Comparable and CharSequence interfaces.

• CharSequence Interface
• The CharSequence interface is used to represent the sequence of characters.
• String, StringBuffer and StringBuilder classes implement it.

• Java String is immutable which means it cannot be changed.


There are two ways to create String object:
• By string literal
• By new keyword

• 1) String Literal
• Java String literal is created by using double quotes.
Example
String s="welcome";
• Each time you create a string literal, the JVM checks the "string constant pool"
first.
• If the string already exists in the pool, a reference to the pooled instance is
returned.
• If the string doesn't exist in the pool, a new string instance is created and placed
in the pool.

Example
• String s1="Welcome";
• String s2="Welcome";//It doesn't create a new instance
class Main {
public static void main(String[] args) {
// create a string using new
String name = new String("Java String");
System.out.println(name); // print Java String
}
}

2) By new keyword
• String s=new String("Welcome"); //creates two objects and one reference variable.
• JVM will create a new string object in normal (non-pool) heap memory, and the literal
"Welcome" will be placed in the string constant pool.
• The variable s will refer to the object in a heap (non-pool).

public class StringExample{


public static void main(String args[]){
String s1="java"; //creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch); //converting char array to string
String s3=new String("example"); //creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}

• Output
java
strings
Example

Java String class provides a lot of methods to perform operations on strings


such as

compare(), concat(), equals(), split(), length(), replace(),

compareTo(), intern(), substring() etc


• Get Length of a String
• To find the length of a string, we use the length() method of the String.
class Main {
public static void main(String[] args) {
// create a string
String greet = "Hello! World";
System.out.println("String: " + greet);
// get the length of greet
int length = greet.length();
System.out.println("Length: " + length);
}
}

Output
String: Hello! World
Length: 12

• Join two Strings


• We can join two strings in Java using the concat() method.
class Main {
public static void main(String[] args) {
// create first string
String first = "Java ";
System.out.println("First String: " + first);
// create second
String second = "Programming";
System.out.println("Second String: " + second);
// join two strings
String joinedString = first.concat(second);
System.out.println("Joined String: " + joinedString);
}
}
Output
First String: Java
Second String: Programming
Joined String: Java Programming

• String Concatenation in Java


• There are two ways to concat string in java:
1. By + (string concatenation) operator
2. By concat() method

By + (string concatenation) operator

• By concat() method
class TestStringConcatenation1{
public static void main(String args[]){
String s="Sachin“ + " Tendulkar";
System.out.println(s);//Sachin Tendulkar
}
}

• Output
• Sachin Tendulkar
• 2) String Concatenation by concat() method
class TestStringConcatenation3{
public static void main(String args[]){
String s1="Sachin ";
String s2="Tendulkar";
String s3=s1.concat(s2);
System.out.println(s3);//Sachin Tendulkar
}
}

• Output
• Sachin Tendulkar

• Compare two Strings


• In Java, we can make comparisons between two strings using the equals() method.
class Main {
public static void main(String[] args) {
// create 3 strings
String first = "java programming";
String second = "java programming";
String third = "python programming";
// compare first and second strings
boolean result1 = first.equals(second);
System.out.println("Strings first and second are equal: " + result1);
// compare first and third strings
boolean result2 = first.equals(third);
System.out.println("Strings first and third are equal: " + result2);
}
}

Output
• Strings first and second are equal: true
• Strings first and third are equal: false

• There are three ways to compare string in java:


• By equals() method
• By = = operator
• By compareTo() method

1) String compare by equals() method


• The String equals() method compares the original content of the string.
• It compares values of string for equality. String class provides two methods

class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}
Output
True
True
false
• String compare by == operator
• The = = operator compares references not values.
class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to same instance)
System.out.println(s1==s3);//false(because s3 refers to instance created in
nonpool)
}
}

Output :
True
False

• String compare by compareTo() method


• The String compareTo() method compares values lexicographically and
returns an integer value.
• it describes if first string is less than, equal to or greater than second string.

Suppose s1 and s2 are two string variables. If:


s1 == s2 :0
s1 > s2 :positive value
s1 < s2 :negative value

class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
Output
0, 1 ,-1
• Methods of Java String
Methods Description
substring() returns the substring of the string
replaces the specified old character with the specified new
replace()
character
charAt() returns the character present in the specified location
getBytes() converts the string to an array of bytes
indexOf() returns the position of the specified character in the string
compareTo() compares two strings in the dictionary order
trim() removes any leading and trailing whitespaces
format() returns a formatted string
split() breaks the string into an array of strings
toLowerCase() converts the string to lowercase
toUpperCase() converts the string to uppercase
returns the string representation of the specified
valueOf()
argument
toCharArray() converts the string to a char array

• Substring in Java
• A part of string is called substring.
• substring is a subset of another string.
• In case of substring startIndex is inclusive and endIndex is exclusive.
• Index starts from 0.

String s="hello";
System.out.println(s.substring(0,2));//he

• public String substring(int startIndex):


• This method returns new String object containing the substring of the given
string from specified startIndex (inclusive).

• public String substring(int startIndex, int endIndex):


• This method returns new String object containing the substring of the given
string from specified startIndex to endIndex.

public class TestSubstring{


public static void main(String args[]){
String s="SachinTendulkar";
System.out.println(s.substring(6));//Tendulkar
System.out.println(s.substring(0,6));//Sachin
}
}

Java String toUpperCase() and toLowerCase() method


The java string toUpperCase() method converts this string into uppercase letter and string
toLowerCase() method into lowercase letter.

String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)

Output
SACHIN
sachin
Sachin
• Java String trim() method
• The string trim() method eliminates white spaces before and after string.

String s=" Sachin ";


System.out.println(s);// Sachin
System.out.println(s.trim());//Sachin

• Output
Sachin
Sachin

• Java String charAt() method


• The string charAt() method returns a character at specified index.

String s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
Output
• S
• h

• Java String valueOf() method


• The string valueOf() method coverts given type such as int, long, float, double,
boolean, char and char array into string.

int a=10;
String s=String.valueOf(a);
System.out.println(s+10);

Output
1010
• Java String replace() method
• The string replace() method replaces all occurrence of first sequence of
character with second sequence of character.

String s1="Java is a programming language. Java is a platform independent.”


String replaceString=s1.replace("Java",“C++");
System.out.println(replaceString);

• Output
C++ is a programming language. C++ is a platform independent.

• The java.lang.StringBuffer
• The StringBuffer and StringBuilder classes are used when there is a necessity
to make a lot of modifications to Strings of characters.

• objects of type StringBuffer and String builder can be modified over and over
again without leaving behind a lot of new unused objects.

• class is a thread-safe, mutable sequence of characters.


• A string buffer is like a String, but can be modified.
• It contains some particular sequence of characters, but the length and
content of the sequence can be changed through certain method calls.
• They are safe for use by multiple threads.
• Every string buffer has a capacity.

public class Test {


public static void main(String args[]) {
StringBuffer sBuffer = new StringBuffer("test");
sBuffer.append(" String Buffer");
System.out.println(sBuffer);
}
}
Output
test String Buffer
StringBuffer Methods
1 public StringBuffer append(String s)Updates the value of the object that invoked the
method.
The method takes boolean, char, int, long, Strings, etc.

2 public StringBuffer reverse()The method reverses the value of the StringBuffer object
that invoked the method.

3 public delete(int start, int end)Deletes the string starting from the start index until the
end index.

4 public insert(int offset, int i)This method inserts a string s at the position mentioned by
the offset.

5 replace(int start, int end, String str)This method replaces the characters in a substring
of this StringBuffer with characters in the specified String.

Interface in Java
• An interface in Java is a blueprint of a class.
• It has static constants and abstract methods.
• The interface in Java is a mechanism to achieve abstraction.
• An interface is used to group related methods with empty bodies
Syntax
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}

Declaring Interfaces
import java.lang.*;
public interface NameOfInterface {
// Any number of final, static fields
// Any number of abstract method declarations
}

• Why And When To Use Interfaces?


1) To achieve security - hide certain details and only show the important details
of an object (interface).

2) Java does not support "multiple inheritance" (a class can only inherit from
one superclass). However, it can be achieved with interfaces, because the class
can implement multiple interfaces.
Note: To implement multiple interfaces, separate them with a comma
• The relationship between classes and interfaces
• Multiple inheritance in Java by interface

• Extending Interfaces
• An interface can extend another interface in the same way that a class can extend another class.
• The extends keyword is used to extend an interface, and the child interface inherits the methods of the
parent interface.

// Filename: Sports.java
public interface Sports {
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
// Filename: Football.java
public interface Football extends Sports {
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
// Filename: Hockey.java
public interface Hockey extends Sports {
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}

• Extending Multiple Interfaces


• A Java class can only extend one parent class.
• Multiple inheritance is not allowed.
• Interfaces are not classes, however, and an interface can extend more than
one parent interface.
• Example
• public interface Hockey extends Sports, Event
• Interfaces have the following properties −
• An interface is implicitly abstract. You do not need to use the abstract keyword
while declaring an interface.
• Each method in an interface is also implicitly abstract, so the abstract keyword is
not needed.
• Methods in an interface are implicitly public.

Example
interface Animal {
public void eat();
public void travel();
}

• Implementing Interfaces
• A class uses the implements keyword to implement an interface.
• The implements keyword appears in the class declaration following the extends portion of the declaration.

public class MammalInt implements Animal {


public void eat() {
System.out.println("Mammal eats");
}
public void travel() {
System.out.println("Mammal travels");
}
public int noOfLegs() {
return 0;
}
public static void main(String args[]) {
MammalInt m = new MammalInt();
m.eat();
m.travel();
} Output
Mammal eats
Mammal travels

}
Java Package
• A java package is a group of similar types of classes, interfaces and sub-
packages.
• A package in Java is used to group related classes.
• Package in java can be categorized in two form,
• Built-in package
• User-defined package.
• There are many built-in packages such as java, lang, awt, javax, swing, net,
io, util, sql etc.

• Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they can
be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

• import java.util.Scanner
Here:
→ java is a top level package
→ util is a sub package
→ and Scanner is a class which is present in the sub package util.
Advantages of using a package in Java
• Reusability:
• While developing a project in java, we often feel that there are few things
that we are writing again and again in our code.
• Using packages, you can create such things in form of classes inside a package
and whenever you need to perform that same task, just import that package
and use the class.
• Better Organization:
• Again, in large java projects where we have several hundreds of classes, it is
always required to group the similar types of classes in a meaningful package
name so that you can organize your project better and when you need
something you can quickly locate it and use it, which improves the efficiency.
• Name Conflicts:
• We can define two classes with the same name in different packages so to
avoid name collision, we can use packages.
• Types of packages in Java
1) User defined package:
The package we create is called user-defined package.
2) Built-in package:
The already defined package like java.io.*, java.lang.* etc are
known as built-in packages.

• Built-in Packages
• These packages consist of a large number of classes which are a part of Java API.
• Some of the commonly used built-in packages are:

1) java.lang: Contains language support classes(e.g classed which defines primitive


data types, math operations). This package is automatically imported.

2) java.io: Contains classed for supporting input / output operations.

3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support , for Date / Time operations.

4) java.applet: Contains classes for creating Applets.

5) java.awt: Contain classes for implementing the components for graphical user
interfaces (like button, menus etc).

6) java.net: Contain classes for supporting networking operations


• User-defined packages
• These are the packages that are defined by the user.
• First we create a directory myPackage (name should be same as the name of
the package).
• Then create the MyClass inside the directory with the first statement being
the package names.

public class MyClass


{
public void getNames(String s) {
System.out.println(s);
}
}
Now we can use the MyClass class in our program.

• Syntax
• import package.name.Class; // Import a single class
• import package.name.*; // Import the whole package

• Example
• import java.util.Scanner;

• In the example above, java.util is a package, while Scanner is a class of the


java.util package.

import myPackage.MyClass;
public class PrintName
{
public static void main(String args[])
{
// Initializing the String variable with a value
String name = “Hello";
// Creating an instance of class MyClass in
// the package.
MyClass obj = new MyClass();
obj.getNames(name);
}
}
MyClass.java must be saved inside the myPackage directory since it is a part of the package.
Creating our first package:
• To create a package, use the package keyword
• File name – ClassOne.java

package package_name;
public class ClassOne {
public void methodClassOne() {
System.out.println("Hello there its ClassOne");
}
}

• Creating our second package:


• File name – ClassTwo.java

package package_one;
public class ClassTwo {
public void methodClassTwo(){
System.out.println("Hello there i am ClassTwo");
}
}

• Making use of both the created packages:


• File name – Testing.java

import package_one;
import package_name.ClassOne;

public class Testing {


public static void main(String[] args){
ClassTwo a = new ClassTwo();
ClassOne b = new ClassOne();
a.methodClassTwo();
b.methodClassOne();
}
}

Output:

Hello there i am ClassTwo


Hello there its ClassOne
• Key points:

• Every class is part of some package.


• If no package is specified, the classes in the file goes into a special unnamed
package (the same unnamed package for all files).
• All classes/interfaces in a file are part of the same package. Multiple files can
specify the same package name.
• If package name is specified, the file must be in a subdirectory called name
(i.e., the directory name must match the package name).
• We can access public classes in another (named) package using: package-
name.class-name

• How to Create a package?

• Creating a package is a simple task as follows


• Choose the name of the package
• Include the package command as the first line of code in your Java Source File.
• The Source file contains the classes, interfaces, etc you want to include in the package
• Compile to create the Java packages.

1. Consider the following package program in Java:


package p1;
class c1(){
public void m1(){
System.out.println("m1 of c1");
}
public static void main(string args[]){
c1 obj = new c1();
obj.m1();
}
}

• To put a class into a package, at the first line of code define package
p1
• Create a class c1
• Defining a method m1 which prints a line.
• Defining the main method
• Creating an object of class c1
• Calling method m1
Step 2) In next step, save this file as demo.java
Step 3) In this step, we compile the file.
• The compilation is completed.
• A class file c1 is created. no package is created

Step 4) Now we have to create a package, use the command


• javac –d . demo.java

• This command forces the compiler to create a package.


• The "." operator represents the current working directory.

Step 5) When you execute the code, it creates a package p1. When you open the
java package p1 inside you will see the c1.class file.

Step 6) Compile the same file using the following code.


javac –d .. demo.java

Here ".." indicates the parent directory.


In our case file will be saved in parent directory which is C Drive

• File saved in parent directory when above code is executed.


• Step 7) Now let's say you want to create a sub package p2 within our
existing java package p1. Then we will modify our code as

package p1.p2;
class c1{
public void m1() {
System.out.println("m1 of c1");
}
}
• Step 8) Compile the file

• As seen in below screenshot, it creates a sub-package p2 having class


c1 inside the package.

• Step 9) To execute the code mention the fully qualified name of the
class i.e. the package name followed by the sub-package name
followed by the class name –

java p1.p2.c1

• This is how the package is executed and gives the output as "m1 of
c1" from the code file.
• The package keyword is used to create a package in java.
Syntax
package nameOfPackage;

Example

package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

• Multitasking:
• Ability to execute more than one task at the same time is known as
multitasking.
• Multithreading:
• It is a process of executing multiple threads simultaneously.
• Multithreading is also known as Thread-based Multitasking.
• Multiprocessing:
• It is same as multitasking, however in multiprocessing more than one CPUs
are involved.
• On the other hand one CPU is involved in multitasking.
• Parallel Processing:
• It refers to the utilization of multiple CPUs in a single computer system.

MULTITHREADING
• A single thread is basically a lightweight and the smallest unit of
processing.
• Java uses threads by using a "Thread Class".
• There are two types of thread –
• user thread - When an application first begins, user thread is created.
• daemon thread - daemon threads are used when we want to clean the
application and are used in the background.
• Single Thread Example:
package demotest;
public class SingleThread {
public static void main(String[] args) {
System.out.println("Single Thread");
}
}
• Advantages of single thread:
• Reduces overhead in the application as single thread execute in the system
• Also, it reduces the maintenance cost of the application.

Multithreading
• Process of executing two or more threads simultaneously to
maximum utilization of CPU.
• Multithreaded applications execute two or more threads run
concurrently.
• Each thread runs parallel to each other.
• Multiple threads don't allocate separate memory area, hence they
save memory.
• Context switching between threads takes less time.

Advantages of multithread:
• The users are not blocked because threads are independent, and we
can perform multiple operations at times
• As such the threads are independent, the other threads won't get
affected if one thread meets an exception.

Creating a thread in Java


There are two ways to create a thread in Java:
• By extending Thread class.
• By implementing Runnable interface.
• Methods of Thread class
• getName(): It is used for Obtaining a thread’s name
• getPriority(): Obtain a thread’s priority
• isAlive(): Determine if a thread is still running
• join(): Wait for a thread to terminate
• run(): Entry point for the thread
• sleep(): suspend a thread for a period of time
• start(): start a thread by calling its run() method

• Method 1: Thread creation by extending Thread class

class MultithreadingDemo extends Thread{


public void run(){
System.out.println("My thread is in running state.");
}
public static void main(String args[]){
MultithreadingDemo obj=new MultithreadingDemo();
obj.start();
}
}
• Output: My thread is in running state.

• Method 2: Thread creation by implementing Runnable Interface


class MultithreadingDemo implements Runnable{
public void run(){
System.out.println("My thread is in running state.");
}
public static void main(String args[]){
MultithreadingDemo obj=new MultithreadingDemo();
Thread tobj =new Thread(obj);
tobj.start();
}
}
Output: My thread is in running state.

Thread Life Cycle in Java


• New
• Runnable
• Running
• Waiting
• Dead
• New:
• In this phase, the thread is created using class "Thread class".
• It remains in this state till the program starts the thread. It is also known as
born thread.
• Runnable:
• In this page, the instance of the thread is invoked with a start method.
• The thread control is given to scheduler to finish the execution.
• It depends on the scheduler, whether to run the thread.
• Running:
• When the thread starts executing, then the state is changed to "running"
state.
• The scheduler selects one thread from the thread pool, and it starts executing
in the application.

• Waiting:
• This is the state when a thread has to wait.
• As there multiple threads are running in the application, there is a need for
synchronization between threads.
• Hence, one thread has to wait, till the other thread gets executed.
• Dead:
• This is the state when the thread is terminated.
• The thread is in running state and as soon as it completed processing it is in
"dead state".
• Timed Waiting:
• A thread lies in timed waiting state when it calls a method with a time out
parameter.
• A thread lies in this state until the timeout is completed or until a notification
is received.
• For example, when a thread calls sleep or a conditional wait, it is moved to a
timed waiting state.

• BLOCKED
• A thread that is blocked waiting for a monitor lock is in this state.
• To get the current state of the thread, use Thread.getState() method .
• Java provides java.lang.Thread.State class that defines the ENUM
constants for the state of a thread.

Commonly used Methods

Method Description
start() This method starts the execution of the thread and JVM calls the run()
method on the thread.

Sleep(int milliseconds) This method makes the thread sleep hence the thread's execution will pause
for milliseconds provided and after that, again the thread starts executing.
This help in synchronization of the threads.

getName() It returns the name of the thread.


setPriority(int newpriority) It changes the priority of the thread.

yield () It causes current thread on halt and other threads to execute.

Example
class MultithreadingDemo extends Thread {
public void run() {
try {
// Displaying the thread that is running
System.out.println ("Thread " + Thread.currentThread().getId() +
" is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println ("Exception is caught");
}
}
}
public class Multithread {
public static void main(String[] args) {
int n = 8; // Number of threads
for (int i=0; i<n; i++) {
MultithreadingDemo object = new MultithreadingDemo();
object.start();
}
}
}
Output
Thread 8 is running
Thread 9 is running
Thread 10 is running
Thread 11 is running
Thread 12 is running
Thread 13 is running
Thread 14 is running
Thread 15 is running

Thread priorities
• Thread priorities are the integers which decide how one thread
should be treated with respect to the others.
• Thread priority decides when to switch from one running thread to
another, process is called context switching
• A thread can voluntarily release control and the highest priority
thread that is ready to run is given the CPU.
• A thread can be preempted by a higher priority thread no matter
what the lower priority thread is doing.
• Whenever a higher priority thread wants to run it does.
• To set the priority of the thread setPriority() method is used which is
a method of the class Thread Class.
• In place of defining the priority in integers, we can use
MIN_PRIORITY, NORM_PRIORITY or MAX_PRIORITY.

• https://www.javatpoint.com/array-in-java
• https://beginnersbook.com/2013/03/packages-in-java/
Unit - IV
Managing Errors and Exceptions – Applet Programming: Introduction-
How Applet differ from Applications –preparing to write Applets –
Building Applet code.

What is an exception
• An Exception is an unwanted event that interrupts the normal flow of the
program.

• When an exception occurs program execution gets terminated.

• Exception is a run-time error which arises during the execution of java program.

• The term exception in java stands for an “exceptional event”.

• So Exceptions are nothing but some abnormal and typically an event or


conditions that arise during the execution which may interrupt the normal flow
of program.
• Why an exception occurs?
• Opening a non-existing file in your program, Network connection problem,

bad input data provided by user etc.

• A user has entered invalid data.

• A file that needs to be opened cannot be found.

• A network connection has been lost in the middle of communications, or the JVM has
run out of memory.

• If the exception object is not handled properly, the interpreter will display the error and
will terminate the program

There are three categories of errors:


• Syntax errors
• Arise because the rules of the language have not been followed.
• They are detected by the compiler.
• Runtime errors
• occur while the program is running if the environment detects an operation
that is impossible to carry out.
• Logic errors
• occur when a program doesn't perform the way it was intended to.

• Types of Exception:
• There are three types of exceptions:
• Checked Exception
• are checked at compile-time.
• Checked Exceptions means that compiler forces the programmer to check and deal with
the exceptions
• Example : IOException, SQLException etc
• Unchecked Exception
• are not checked at compile-time rather they are checked at runtime.
• Classes that extends Runtime Exception, Error and their subclasses are known as
unchecked exceptions
• Example : Arithmetic Exception, NullPointer Exception, ArrayIndexOutOf Bounds
Exception etc.
• Error
• Error is irrecoverable should not try to catch.
• Example : OutOfMemoryError, VirtualMachineError, AssertionError etc
Exception Handling
If an exception occurs, which has not been handled by
programmer then program execution gets terminated and a system
generated error message is shown to the user.

• Catch errors before they occur


• Deals with synchronous errors (i.e., divide by zero)
• Does not deal with asynchronous errors
• Disk I/O completions, mouse clicks - use interrupt processing
• Used when system can recover from error
• Exception handler - recovery procedure
• Error dealt with in different place than where it occurred
• Useful when program cannot recover but must shut down cleanly

• Exception handling
• Should not be used for program control
• Not optimized, can harm program performance
• Improves fault-tolerance
• Easier to write error-processing code
• Specify what type of exceptions are to be caught
• Another way to return control from a function or block of code

• Error handling used for


• Processing exceptional situations
• Processing exceptions for components that cannot handle them directly
• Processing exceptions for widely used components (libraries, classes,
methods) that should not process their own exceptions
• Large projects that require uniform error processing

• The purpose of exception handling is to detect and report an


exception so that proper action can be taken and prevent the
program which is automatically terminate or stop the execution
because of that exception.
• Java exception handling is managed by using five keywords:
• try, catch, throw, throws and finally
• Try:
• Piece of code of your program that you want to monitor for exceptions are contained
within a try block.
• used to enclose a segment of code that may produce a exception
• Catch:
• Catch block can catch this exception and handle it in some logical manner.
• placed directly after the try block to handle one or more exception types.
• Throw:
• System-generated exceptions are automatically thrown by the Java run-time
system.
• Now if we want to manually throw an exception, we have to use the
keyword.
• to generate an exception or to describe an instance of an exception.

• Throws:
• If a method is capable of causing an exception that it does not handle, it
must specify this behavior so that callers of the method can guard themselves
against that exception.
• You do this by including a throws clause in the method’s declaration.
• Basically it is used for IOException.
• A throws clause lists the types of exceptions that a method might throw.
• This is necessary for all exceptions, except those of type Error or
RuntimeException, or any of their subclasses.

• Finally:
• optional statement used after a try-catch block to run a segment of code
regardless if a exception is generated.

• try {
// block of code to monitor for errors
}
catch (ExceptionType1 e1) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 e2) {
// exception handler for ExceptionType2
}
finally {
// block of code to be executed before try block ends
}
• JVM first checks whether the exception is handled or not.
• If exception is not handled, JVM provides a default exception handler
that performs the following tasks:
• Prints out exception description.
• Prints the stack trace (Hierarchy of methods where the exception occurred).
• Causes the program to terminate.

• if exception is handled by the application programmer, normal flow


of the application is maintained i.e. rest of the code is executed.
• Multiple catch block:
• If more than one exception can occur, then we use multiple catch blocks
• When an exception is thrown, each catch statement is inspected in order,
and the first one whose type matches that of the exception is executed
• After one catch statement executes, the others are bypassed.

• Nested try Statements


• A try statement can be inside the block of another try
• Each time a try statement is entered, the context of that exception is pushed
on the stack
• If an inner try statement does not have a catch, then the next try statement’s
catch handlers are inspected for a match
• If a method call within a try block has try block within it, then then it is still
nested try
• Finally block
• is a block that is always executed.
• To perform some important tasks such as closing connection, stream etc.
• Used to put "cleanup" code such as closing a file, closing connection etc.
• Finally creates a block of code that will be executed after a try/catch block has
completed

• Finally block will be executed whether or not an exception is thrown.


• Each try clause requires at least one catch or finally clause.
• Before terminating the program, JVM executes finally block(if any).
• finally must be followed by try or catch block.
• throw keyword
• keyword is used to explictily throw an exception / custom exception.
throw new ExceptionName("Error Message");
• Throw either checked or uncheked exception.
• throw new ThrowableInstance
• ThrowableInstance must be an object of type
•Throwable / subclass Throwable
• There are two ways to obtain a Throwable objects:
• Using a parameter into a catch clause
• Creating one with the new operator
• Throws
• If a method is capable of causing an exception that it does not handle,
it must specify this behavior so that callers of the method can guard
themselves against that exception
type method-name parameter-list) throws exception-list
{
// body of method
}
• It is not applicable for Error or RuntimeException, or any of their
subclasses
Create our Own Exception:
• class NumberRangeException extends Exception
{
String msg;
NumberRangeException()
{
msg = new String("Enter a number between 20 and 100");
}
}

• public class My_Exception


{
public static void main (String args [ ])
{
try
{
int x = 10;
if (x < 20 || x >100) throw new NumberRangeException( );
}
catch (NumberRangeException e)
{
System.out.println (e);
}

}
}
The Basics of Java Exception Handling
• Exception handling
• Method detects error which it cannot deal with
• Throws an exception
• Exception handler
• Code to catch exception and handle it
• Exception only caught if handler exists
• If exception not caught, block terminates

• Format
• Enclose code that may have an error in try block
• Follow with one or more catch blocks
• Each catch block has an exception handler
• If exception occurs and matches parameter in catch block
• Code in catch block executed
• If no exception thrown
• Exception handling code skipped
• Control resumes after catch blocks

try{
code that may throw exceptions
}
catch (ExceptionType ref) {
exception handling code
}

• Termination model of exception handling


• throw point
• Place where exception occurred
• Control cannot return to throw point
• Block which threw exception expires
• Possible to give information to exception handler
• Example program
• User enters two integers to be divided
• We want to catch division by zero errors
• Exceptions
• Objects derived from class Exception
• Look in Exception classes in java.lang
• Nothing appropriate for divide by zero
• Closest is ArithmeticException
• Extend and create our own exception class

5 public class DivideByZeroException


6 extends ArithmeticException {
7 public DivideByZeroException()
12 public DivideByZeroException( String message
)

• Two constructors for most exception classes


• One with no arguments (default), with default message
• One that receives exception message
• Call to superclass constructor
• Code that may throw exception in try block
• Error handling code in catch block
• If no exception thrown, catch blocks skipped

1 // Fig. 14.1: DivideByZeroException.java


2 // Definition of class DivideByZeroException.
3 // Used to throw an exception when a
4 // divide-by-zero is attempted.
5 public class DivideByZeroException Define our own exception class
6 extends ArithmeticException {
(exceptions are thrown objects).
7 public DivideByZeroException()
Default constructor (default
8 {
message) and customizable
9 super( "Attempted to divide by zero" );
10 }
message constructor.
11
12 public DivideByZeroException( String message )
13 {
14 super( message );
15 }
16 }
17
Try Blocks
• Exceptions that occurs in a try block
• Usually caught by handler specified by following catch block
try{
code that may throw exceptions
}
catch ( ExceptionType ref ) {
exception handling code
}

• Can have any number of catch blocks


• If no exceptions thrown, catch blocks skipped

Throwing an Exception
• throw
• Indicates exception has occurred (throwing an exception)
• Operand
• Object of any class derived from Throwable
95 if ( denominator == 0 )
96 throw new DivideByZeroException();

• Derived from Throwable:


• Exception - most programmers deal with
• Error - serious, should not be caught
• When exception thrown
• Control exits current try block
• Proceeds to catch handler (if exists)

• Exceptions
• Can still throw exceptions without explicit throw statement
• ArrayIndexOutOfBoundsException
• Terminates block that threw exception
Catching an Exception
• catch blocks
• Contain exception handlers
• Format:
catch( ExceptionType ref ) {
error handling code
}

82 catch ( DivideByZeroException dbze ) {


83 JOptionPane.showMessageDialog( this,
dbze.toString(),
84 "Attempted to Divide by Zero",
85 JOptionPane.ERROR_MESSAGE );
86 }

• To catch all exceptions, catch an exception object:


catch( Exception e )

Catching an Exception
• Catching exceptions
• First handler to catch exception does
• All other handlers skipped
• If exception not caught
• Searches enclosing try blocks for appropriate handler
try{
try{
throw Exception2
}
catch ( Exception1 ){...}
}
catch( Exception2 ){...}

• If still not caught, applications terminate

Catching an Exception
• Information
• Information can be passed in the thrown object
• If a catch block throws an exception
• Exception must be processed in the outer try block
• Usage of exception handlers
• Rethrow exception (next section)
• Convert exception to different type
• Perform recovery and resume execution
• Look at situation, fix error, and call method that generated exception
• Return a status variable to environment
Rethrowing an Exception
• Rethrowing exceptions
• Use if catch handler cannot process exception
• Rethrow exception with the statement:
throw e;
• Detected by next enclosing try block
• Handler can always rethrow exception, even if it performed some processing

Throws Clause
• Throws clause
• Lists exceptions that can be thrown by a method
int g( float h ) throws a, b, c
{
// method body
}

92 public double quotient( int numerator, int denominator )


93 throws DivideByZeroException

• Method can throw listed exceptions

• Run-time exceptions
• Derive from RunTimeException
• Some exceptions can occur at any point
• ArrayIndexOutOfBoundsException
• NullPointerException
• Create object reference without attaching object to reference
• ClassCastException
• Invalid casts
• Most avoidable by writing proper code
• Checked exceptions
• Must be listed in throws clause of method
• All non-RuntimeExceptions
• Unchecked exceptions
• Can be thrown from almost any method
• Tedious to write throws clause every time
• No throws clause needed
• Errors and RunTimeExceptions
finally Block
• Resource leaks
• Programs obtain and do not return resources
• Automatic garbage collection avoids most memory leaks
• Other leaks can still occur
• finally block
• Placed after last catch block
• Can be used to returns resources allocated in try block
• Always executed, irregardless whether exceptions thrown or caught
• If exception thrown in finally block, processed by enclosing try block

Java applets are one of three kinds of Java programs:

• An application is a standalone program that can be invoked from the


command line.

• An applet is a program that runs in the context of a browser session.

• A servlet is a program that is invoked on demand on a server program and


that runs in the context of a web server process.

Applet
• An applet is a Java program that runs in a Web browser.
• An applet can be a fully functional Java application because it has the
entire Java API at its disposal.
• Small java programs that are primarily used in internet computing.
• An applet can do many things such as arithmetic operations, display
graphics, play sounds, accept user input, create animation, and play
interactive games.
• Java applets can now therefore make a significant impact on World
Wide Web.
• We can do the graphics programming using applet
• Applet
• Program that runs in
• appletviewer (test utility for applets)
• Web browser (IE, Communicator)
• Executes when HTML (Hypertext Markup Language) document containing
applet is opened and downloaded
• Applications run in command windows
• A fully functioning small Java application

• Used for Web Design

• Need to be embedded into HTML file

• Applet code uses two classes, APPLET & GRAPHICS from our Java
class library.
• The applet class is contained in the java.applet package.
• The applet code imports java.awt package which contains the
Graphics class.
• When the applet is loaded, these methods are automatically invoked in order:
• The init( ) method is invoked by the Java Virtual Machine.
• The start( ) method
• The paint( ) method

• APPLET CLASS
• java.applet.Applet is the super class of the all the applets.
• Applet class has a predefined hierarchy
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorldApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello world!", 50, 25);
}
}

• Write a HTML to call the Applet


<html>
<HEAD>
<TITLE>
Hello World Applet
</TITLE>
</HEAD>
<body>
<h1>Hi, This is My First Java Applet on the Web!</h1>
<applet CODE=“HelloWorldApplet.class" WIDTH="250" HEIGHT="22">
</applet>
</body>
</html>

• Open the HTML file in browser and run it


Applet Life Cycle
• Every applet inherits a set of default behaviours from the Applet class.
As a result, when an applet is loaded, it undergoes a series of changes
in its state.
• The applet states include:
• Initialisation – invokes init()
• Running – invokes start()
• Display – invokes paint()
• Idle – invokes stop()
• Dead/Destroyed State – invokes destroy()

Applet States
• Initialisation –
• Invoked when applet is first loaded.
• This is achieved by the init() method of the applet class.
• At this stage, we may do the following:
• Create objects needed
• Set up initial values
• Load images or icons
• Set up colors etc.

• Running
• Applets enters in the running state when system calls the start() method.
• This occurs automatically after applet is initialized.
• Unlike the init() method, the start method can be called many times. (after
idle state)
• We may override the standard start method
• Display – invokes paint() - more than once
• It happens immediately after the applet enters into the running
state.
• It is responsible for displaying output.

• Idle – invokes stop() - more than once


• It is invoked when the applet is stopped from running.
• For example, it occurs when we leave a web page.

• Dead/Destroyed State – invokes destroy() - only once


• This occurs automatically by invoking destroy() method when we
quite the browser.

• Common Methods
• drawString()
• member of Graphics class, used to output a string to an applet.
• It is typically called from within the paint() or update() method.
• void drawString(String msg,int a, int b)
• setBackground() & getBackground()
• belongs to Component class, used to set and get the background color.
• void setBackground(Color anyColor)
• predefined constants for each color, such as Color.red can be used.
• setForeground() & get Foreground()
• set and gets the color of the text to be displayed on the foreground of the
applet window.
• void setForeground(Color anyColor)
• showStatus()
• display any string in the status window of the browser
• void showString(String text

Graphics class import java.awt.* ;


import java.applet.* ;
public class DrawLineRect extends Applet {
public void paint(Graphics g){
g.drawRect(10,60,40,30);
g.fillRect(60,10,30,80);
g.fillOval(140,160,170,170);
g.drawRoundRect(10,100,80,50,10,10);
g.fillRoundRect(20,110,60,30,5,5);
g.drawArc(280,210,250,220,30,90);
g.drawLine(100,10,230,140);
g.drawLine(100,140,230,10);
}
}
Output

How Applets differ from application?:


• They do not use main method but init(), start() and paint() methods
of the applet class
• They can not be executed indep endently like applications, but from
inside a Web page (or Appletviewer) using a special feature known as
HTML tag .
• Applet can not read from or write to the local computer files.But local
applet development is possible. Remote applet requires URL.
• Applet can not run any program on local machine.
• Applets are restricted to use the library from the other language like c
or c++. Application support this through native method.
• Many of the restrictions are placed on applet because of security.
• Application
• An application is a stand-alone java program that runs with the support of a
virtual machine in a client or server-side.
• A java application is designed to perform a specific function to run on any
Java-compatible virtual machine regardless of the computer architecture.
• An application is either executed for the user or for some other application
program.
• Examples of java applications include database programs, development tools,
word processors, text and image editing programs, spreadsheets, web
browsers, etc.
• Example
public class Demo {
public static void main(String args[]) {
System.out.println(“Welcome to TutorialsPoint”);
}
}

• Applet
• An applet is specifically designed to be executed within an HTML web
document using an external API.

• They are basically small programs, more like the web version of an application
that requires a Java plugin to run on the client browser.

• Applets run on the client-side and are generally used for internet computing.

• They can be transferred over the Internet from one computer to another and
run using the Applet Viewer or any web browser that supports Java.

• A web page can include a java applet which, when executed, can generate
graphics, sounds and moving images rather just containing plain text or a
static image.

• Example
import java.awt.*;
import java.applet.*;
public class AppletDemo extends Applet{
public void paint(Graphics g) {
g.drawString("Welcome to TutorialsPoint", 50, 50);
}
}
/* <applet code="AppletDemo.class" width="300" height="300">
<applet>*/
BASIS FOR COMPARISON APPLET APPLICATION

Basic It is small program uses another application program for An application is the programs executed on
its execution. the computer independently.

main() method Do not use the main method Uses the main method for execution

Execution Cannot run independently require API's (Ex. Web API). Can run alone but require JRE.

Installation Prior installation is not needed Requires prior explicit installation on the
local computer.

Read and write operation The files cannot be read and write on the local Applications are capable of performing
computer through applet. those operations to the files on the local
computer.

Communication with other Cannot communicate with other servers. Communication with other servers is
servers probably possible.

Restrictions Applets cannot access files residing on the local Can access any data or file available on the
computer. system.

Security Requires security for the system as they are No security concerns are there.
untrusted.
Managing input/output
Files
Unit-5

16.12-16.15
By
S.pavithrashangari

Reading/writing bytes
• We have used fileReader and file • We can use
writer classes to read and write 16- them place
bit characters of five reader
• Most file systems use only 8-bit and
bytes. fileWriter
• Java I/o system provides a number
of classes that can handle 8-bit
bytes.
• Two commonly used classes for
handling bytes are fileinputstream
and fileoutputstream classes

Tttt
Handling primitive
Data types

Handling primitive data types


• The basic input and output streams provide read/write
methods that can be used for reading/writing bytes or
characters
• 🌼To read/write the primitive data types such as
integers and doubles, we can use filter classes as
wrappers on the existing I/O streams to filter data to
the original stream.
• ฀The two filter classes supported for creating Data
streams For primitive data types are:
• 🌻DataInputstream
• 🌻DataOutputstream. ฀฀😁

🙄
16.13
Data Input Stream Creation
• 👉Create Input File Stream:
• File stream fis=new FileinputStream("infile");
• 👉Create lnput Data Stream:
• DataInputStream dis=new DataInputstram(fis);
• The above statements wrap data input stream (dis) on
file input stream (fis)and use it as a Filter.
• Methods Supported:
•👣
readBoolean(),readByte(),readChar(),readShort(),readIn
t(),readLong(),readFloat(),readDouble()
• 👉They read data stored in file in binary format

Data Output Stream Creation


• Create Output File Stream:
• 👉FileOutputStream fos=new FileOutputStream("output");
• Create Output Data Stream:
• 👉DataOutputStream dos=new DataOutputstream (fos);
• The above statement wrap dara output stream (dos)on file output
stream (fos) and use it as a Filter.
• Methods Supported:
• 👣WriteBoolean(),writeByte(),writeChar(),.....
• They write data to file in binary format.
• 💦How many bytes are written to file when for statements:
• 💭WriteInt (120),writeInt(10120). ฀😁฀

Data
streams
Flow Via
Filter

😃👉
Writing and
Reading
Primitive Data

😁฀😁

😁
฀😃฀


Random Access Files
😁😁😁฀฀฀👉👉
Thank you😊

You might also like