Unit - 1 (5 Files Merged)
Unit - 1 (5 Files Merged)
Programming Languages
• Programming languages allows programmers to code software.
• 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
• Example
ADD 1001010, 1011010
• High-Level Languages
• The syntax of HL languages is similar to English.
• 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.
Examples
• C++, Visual Basic.NET and Java.
Object
• Object are entities that encapsulate data & related operations.
• An Object contains both the data and the function, which operates on the data.
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 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.
• 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
• 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
• 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 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.
Applications of Java
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
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.
• 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
• void : It is the return type, meaning this function will not return anything.
• String[] args : This represents an array whose type is String and name is args.
Output
• Hello World
UNIT - II
Variables in Java
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.
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;
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;
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;
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.
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
• After the first character, an identifier can have any combination of characters.
• 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
% remainder of division
++ Increment operator increases 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
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
|| Logical OR (a || b) is true
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
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
! ~ (type) new negation, bitwise NOT, type cast, object creation Right-to-left
• 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
}
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.
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
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 ;
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
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
Create a Class
• To create a class, use the keyword class
• Create a class named "Main" with a variable x:
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
• methods are declared within a class, and that they are used to
perform certain actions.
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.
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.
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();
}
}
}
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="java";
• CharSequence Interface
• The CharSequence interface is used to represent the sequence of characters.
• String, StringBuffer and StringBuilder classes implement it.
• 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).
• Output
java
strings
Example
Output
String: Hello! World
Length: 12
• 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
Output
• Strings first and second are equal: true
• Strings first and third are equal: false
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
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
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.
• Output
Sachin
Sachin
String s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
Output
• S
• h
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.
• 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.
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
}
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);
}
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.
}
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.
• 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:
3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support , for Date / Time operations.
5) java.awt: Contain classes for implementing the components for graphical user
interfaces (like button, menus etc).
• Syntax
• import package.name.Class; // Import a single class
• import package.name.*; // Import the whole package
• Example
• import java.util.Scanner;
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");
}
}
package package_one;
public class ClassTwo {
public void methodClassTwo(){
System.out.println("Hello there i am ClassTwo");
}
}
import package_one;
import package_name.ClassOne;
Output:
• 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 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.
package p1.p2;
class c1{
public void m1() {
System.out.println("m1 of c1");
}
}
• Step 8) Compile the file
• 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.
• 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.
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.
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.
• Exception is a run-time error which arises during the execution of java program.
• 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
• 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.
• 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
• 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.
}
}
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
}
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();
• 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
}
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 ){...}
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
}
• 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
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
• 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);
}
}
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.
• 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
• 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
🙄
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
streams
Flow Via
Filter
😃👉
Writing and
Reading
Primitive Data
😁😁
😁
😃
Random Access Files
😁😁😁👉👉
Thank you😊