Sem 3 Java 1 To 5
Sem 3 Java 1 To 5
Unit -3 PACKAGES AND MANAGING EXCEPTIONS Unit-4 THREADS AND SWINGS IN JAVA
⚫
⚫
Threads:
Packages: ⚫ Creating Threads
⚫ Java API Packages ⚫ Extending the Thread Class
⚫ System Packages ⚫ Stopping and Blocking Thread
⚫ Naming Conventions ⚫ Life Cycle of a Thread
⚫ Creating & Accessing a Package ⚫ Thread Exceptions
⚫
⚫
Thread Priority
Adding Class to a Package. ⚫ Synchronization
⚫ Managing Exceptions: ⚫ Basic swing components:
⚫ Types of errors ⚫ JLabel, JTextField, JTextArea, JPasswordField, JButton,
⚫ Handling Exception JCheckBox, JRadioButton, JList, JComboBox, JPanel,User
Interface Design
⚫ multiple catch , Finally Statement ⚫ Event Handling:
⚫ User defined exceptions. ⚫ Action events, Key events, Item events.
Unit -5 NETWORKING, DATABASE CONNECTIVITY
What is Java?
AND COLLECTIONS ⚫ Java:
⚫NETWORKING : ⚫ Java is a general-purpose, class-based, object-oriented
⚫Establishing a simple server programming language, which works on different
operating systems such as Windows, Mac, and Linux.
⚫Establishing a simple client/server interaction with stream
⚫ Can use Java to develop:
socket and datagram socket
• Desktop applications
⚫DATABASE CONNECTIVITY • Web applications
⚫JDBC: JDBC Drivers • Mobile applications (especially Android apps)
⚫Seven steps to connect JDBC • Web and application servers
• Big data processing
⚫COLLECTIONS
• Embedded systems
⚫Overview of Interfaces and classes. ⚫ And much more
Paradigm
•Paradigm can also be termed as method to solve some problem or
do some task.
•Programming paradigm is an approach to solve problem using
some programming language.
⚫ The main focus is on how to achieve the goal. ⚫ Parallel programming is not possible
•OOP treats data as a critical element in the program Program is divided into small parts called functions.
Follows top-down approach.
Program is divided into small parts called objects.
development and does not allow it to flow freely around the There is no access specifier in
Follows bottom-up approach.
systems.
OOP have access specifiers like private, public, protected etc.
POP.
Adding new data and function is easy. Easy to maintain and extend as
new objects can be easily added without modifying the other objects
Adding new data and function is not easy.
Large Programs developed using this approach are difficult to maintain,
•It ties data more closely to the functions that operate on it, debug and extend. OOP provides data hiding so it is more secure. The data of one object
can be accessed by the associated functions of that object only. Other
and protects it from accidental modification from outside POP does not have any proper way for hiding data so it is less secure. functions are not allowed to access that data. ie data is hidden from the
Allows data to move freely from one function to another without any outside world
functions. security. This makes to modify the value of global data by any function.
Overloading is not possible in POP. Overloading is possible in OOP
In POP, function is more important than data. Emphasis is on the In OOP, data is more important than function. Emphasis on data rather
functionality of the Software rather than the data used by the function than the functions or the procedures
POP is based on unreal world. Data and associated functions are loosely OOP is based on real world. Models the real world very well by binding
related. the data and associated functions together under a single unit 11
Object-Oriented Programming (OOP) is an approach that provides a way of
modularizing programs by creating partitioned memory area for both data and
functions that can be used as templates for creating copies of such modules on Features of object-oriented programming:
demand.
•Emphasis is on data rather than procedure.
•Programs are divided into what are known as objects.
•Data structures are designed such that they characterize the objects.
•Data is hidden and cannot be accessed by external functions.
•Objects may communicate with each other through functions.
•New data and functions can be easily added whenever necessary.
•Follows bottom-up approach in program design
Object
Class
Data Abstraction
Encapsulation
Inheritance
Polymorphism
Dynamic Binding
19
Message Passing
Object:
•Objects are basic run time entity.
Object
•Any entity that has state and behavior is known as an object. •Object is an real world entity that has state, behavior and
•They may represent a person, a place, a bank account, a table of data or any identity.
item that the program has to handle. •State :
•It is represented by attributes of an object.
•For example: •It also reflects the properties of an object.
•a chair, pen, table, keyboard, bike, etc. •Behavior :
•It can be physical or logical. •It is represented by methods of an object.
•It also reflects the response of an object with other objects.
•Identity :
• It gives a unique name to an object and enables one object to
interact with other objects.
Object
•An Object can be defined as an instance of a class.
•An object contains an address and takes up some space
in memory.
•Objects can communicate without knowing the details
of each other's data or code.
•The only necessary thing is the type of message
accepted and the type of response returned by the 2
4
objects.
Object concept in programming:
Call a Method
Method Syntax ⚫ To call (execute) a method, write the method's name
followed by two parentheses () and a semicolon;
Example
⚫ public class Student
⚫ { Data Abstraction
⚫ static void MyMethod() ⚫ Data abstraction is the process of hiding certain details and showing
{ only essential information to the user.
⚫ System.out.println("Actions speak louder than words");
⚫ Abstraction can be achieved with either abstract classes or interfaces
⚫ }
public static void main(string[] args) ⚫ The abstract keyword is a non-access modifier, used for classes and
⚫
methods:
{
⚫ MyMethod(); ⚫ Abstract class: is a restricted class that cannot be used to create objects
⚫ MyMethod(); (to access it, it must be inherited from another class).
⚫ MyMethod(); ⚫ Abstract method: can only be used in an abstract class, and it does not
⚫ } have a body. The body is provided by the subclass (inherited from).
⚫ } ⚫ An abstract class can have both abstract and regular methods:
Example
⚫ For Example:
⚫ while driving a car, you do not have to be concerned
with its internal working.(hiding)
⚫ Here you just need to concern about parts like steering
wheel, Gears, accelerator, etc.(essential features)
Example program
⚫ // Abstract class
⚫
Encapsulation
abstract class Animal
⚫ {
⚫ // Abstract method (does not have a body)
⚫ public abstract void animalSound();
Encapsulation
⚫ The meaning of Encapsulation, is to make sure that
"sensitive" data is hidden from users.
Why Encapsulation?
Example
⚫ Better control of class attributes and methods ⚫ public class Person // class creation
⚫ {
⚫ Class attributes can be made read-only (if you only use the ⚫ private String name; // data member declaration-private = restricted access
⚫ // Getter (using get method)
get method), or write-only (if you only use the set method) ⚫ public String getName()
⚫ Flexible: the programmer can change one part of the code ⚫ {
⚫ return name;
without affecting other parts ⚫ }
⚫ Increased security of data.
⚫ // Setter (using set method)
⚫ Data Hiding: ⚫ public void setName(String newName)
⚫ The user will have no idea about the inner implementation of ⚫ {
⚫ this.name = newName;
the class. ⚫ }
⚫ It will not be visible to the user that how the class is stored ⚫ }
values in the variables. ⚫ Note: this keyword is a reference variable.
Sample Program
⚫ public class Main //main class declaration
⚫ {
⚫ public static void main(String[] args)
⚫ { Using class and objects
⚫ Person myObj = new Person(); //object creation
⚫ myObj.setName("John"); //set method
⚫ System.out.println(myObj.getName()); // get method
⚫ }
⚫ }
⚫ Output:
⚫ John
Example
⚫ public class Student
⚫ { OUTPUT
⚫ int id; //data member (also instance variable)
⚫ String name; //data member(also instance variable)
⚫ public static void main(string[] args)
⚫ {
⚫ Student s1 = new Student();
//creating an object of Student
⚫ s1.id = 1;
⚫ s1.name =“Soniya”;
⚫ System.out.println(“Id=”+s1.id);
⚫ System.out.println(“Name=”+s1.name);
⚫ }
⚫ }
Inheritance Cont..
⚫ For Example
⚫ The Car class (subclass) inherits the attributes and methods
from the Vehicle class (superclass)
⚫ Types
Class A
Father
⚫ Single Inheritance
⚫ Hierarchical Inheritance
Binding binding
⚫ Connecting a method call to the method body is
known as binding. or
⚫ Binding is the process of linking a procedure call to the
code to be executed in response to the call
⚫ It means that the code associated with the given
procedure call is not known until the time of the call at
runtime
⚫ Types:
⚫ Static Binding (also known as Early Binding).
⚫ Dynamic Binding (also known as Late Binding).
Static Binding vs Dynamic Binding
⚫ The binding which can be resolved at compile time by ⚫ When compiler is not able to resolve the call/binding
compiler is known as static or early binding. at compile time, such binding is known as Dynamic or
late Binding.
⚫ Binding of private, static and final methods always
happen at compile time since these methods cannot be ⚫ Example:
overridden. ⚫ Method Overriding
⚫
⚫ Platform independent
Simulation and Modeling ⚫ Secured
Robust
⚫ Robust simply means strong.
⚫ Java is robust because:
⚫ It uses strong memory management.
⚫ There is a lack of pointers that avoids security problems.
⚫ There is automatic garbage collection in java which runs
on the Java Virtual Machine to get rid of objects which
are not being used by a Java application anymore.
⚫ There are exception handling and the type checking
mechanism in Java.
Architecture-neutral
⚫ Java is architecture neutral because there are no implementation
dependent features.
Portable High-performance
⚫ Java is portable because it facilitates to carry the Java ⚫ Java is faster than other traditional interpreted
byte code to any platform. programming languages because Java
⚫ It doesn't require any implementation. bytecode is "close" to native code.
⚫ It is still a little bit slower than a compiled language
(e.g., C++).
⚫ Java is an interpreted language that is why it is slower
than compiled languages, e.g., C, C++, etc.
Distributed
⚫ Java is distributed because it facilitates users to create
distributed applications in Java.
⚫ RMI and EJB are used for creating distributed
applications.
⚫ This feature of Java makes us able to access files by
calling the methods from any machine on the internet.
⚫ Note:
⚫ Remote Method Invocation (RMI)
⚫ Enterprise Java Bean (EJB)
Multi-threaded Dynamic
⚫ A thread is like a separate program, executing ⚫ Java is a dynamic language.
concurrently. ⚫ It supports dynamic loading of classes.
⚫ A flow of control is known as a thread. ⚫ It means classes are loaded on demand.
⚫ Can write Java programs that deal with many tasks at ⚫ It also supports functions from its native languages,
once by defining multiple threads. i.e., C and C++.
⚫ The main advantage of multi-threading is that it ⚫ Java supports dynamic compilation and automatic
doesn't occupy memory for each thread. memory management (garbage collection).
⚫ It shares a common memory area.
⚫ Threads are important for multi-media, Web
applications, etc
Thank you
How is Java platform independent?
Java
⚫ Java applications are typically compiled to bytecode
that can run on any Java virtual machine (JVM)
⚫ The meaning of platform-independent is that the java
regardless of computer architecture.
compiled code(byte code) can run on all operating
⚫ The latest version is Java 19 released on Sep 20, 2022 systems.
⚫ JVM, JRE, and JDK are platform dependent because
the configuration of each OS is different from each
other.
⚫ However, Java is platform independent.
JVM
JDK,JRE,JVM ⚫ JVM (Java Virtual Machine) is an abstract machine.
⚫ It is called a virtual machine because it doesn't physically
exist.
⚫ It is a specification that provides a runtime environment in
which Java bytecode can be executed.
⚫ It can also run those programs which are written in other
languages and compiled to Java bytecode.
⚫ The JVM performs the following main tasks:
• Loads code
• Verifies code
• Executes code
• Provides runtime environment
JRE
JRE
⚫ JRE is an acronym for Java Runtime Environment.
⚫ It is also written as Java RTE.
⚫ The Java Runtime Environment is a set of software tools which
are used for developing Java applications.
⚫ It is used to provide the runtime environment.
⚫ It is the implementation of JVM.
⚫ It physically exists.
⚫ It contains a set of libraries + other files that JVM uses at
runtime.
⚫ The implementation of JVM is also actively released by other
companies besides Sun Micro Systems
JDK JDK
⚫ JDK is an acronym for Java Development Kit.
⚫ The Java Development Kit (JDK) is a software development environment
which is used to develop Java applications and applets.
⚫ It physically exists.
⚫ It contains JRE + development tools.
⚫ The JDK contains a private Java Virtual Machine (JVM) and a few other
resources such as an interpreter/loader (java), a compiler (javac), an archiver
(jar), a documentation generator (Javadoc), etc. to complete the development
of a Java Application.
JDK– JAVA DEVELOPMENT KIT
⚫
JDK is a software development environment used in
the development of Java applications and applets.
⚫
JDK is the core component of Java environment.
⚫
It contains JRE (Java Runtime Environment) along
with Java compiler, Java debugger, and other classes.
Data types
⚫ Data types specify the different sizes and values that can be
Example stored in the variable.
⚫ There are two types of data types in Java
⚫ /** ⚫ Primitive data types:
⚫ * ⚫ Boolean,
⚫
⚫
char,
*We can use various tags to depict the parameter ⚫ byte,
⚫ *or heading or author name ⚫
⚫
short,
int,
⚫ *We can also use HTML tags ⚫ long,
⚫
⚫ float
* ⚫ double.
⚫ */ ⚫ Non-primitive data types:
⚫
⚫ Classes
⚫ Interfaces
⚫ Arrays, ect..
Java Primitive Data Types
Variables
⚫ A variable is a container which holds the value while Example
the Java program is executed.
⚫ A variable is assigned with a data type. ⚫ It is a combination of "vary + able" which means its
value can be changed.
⚫ Variable is a name of memory location.
⚫ There are three types of variables in java:
⚫ local,
⚫ instance
⚫ static.
Variable Types
⚫ int data=50;
2.Unary Operators
⚫ 2. Unary Operators: ⚫ ++ : Increment operator, used for incrementing the value by 1.
There are two varieties of increment operators.
⚫ Unary operators need only one operand. ⚫ Post-Increment: Value is first used for computing the result and
⚫ They are used to increment, decrement or negate a then incremented.
⚫ Pre-Increment: Value is incremented first, and then the result is
value computed.
⚫ – : Unary minus, used for negating the values. ⚫ – – : Decrement operator, used for decrementing the value by
⚫ + : Unary plus indicates the positive value 1. There are two varieties of decrement operators.
⚫ Post-decrement: Value is first used for computing the result and
then decremented.
⚫ Pre-Decrement: Value is decremented first, and then the result is
computed
⚫ ! : Logical not operator, used for inverting a boolean value.
3.Assignment Operator
⚫ Assignment Operator: There are 2 categories of assignment operators .
⚫ ‘=’ Assignment operator is used to assigning a value to
They are,
any variable.
⚫ It has a right to left associativity, i.e. value given on the 1. Simple assignment operator
right-hand side of the operator is assigned to the
variable on the left, and therefore right-hand side
( Example: = )
value must be declared before using it or should be a 2. Compound assignment operators
constant.
⚫ The general format of the assignment operator is: ( Example: +=, -=, *=, /=, %=)
⚫ variable = value;
Operators Example/Description
4. Relational Operators
⚫ 4. Relational Operators:
= sum = 10;
10 is assigned to variable sum
+= sum += 10;
⚫ These operators are used to check for relations like
This is same as sum = sum + 10 equality, greater than, and less than.
-= sum -= 10;
⚫ They return boolean results after the comparison and
This is same as sum = sum – 10 are extensively used in looping statements as well as
conditional if-else statements.
⚫
*= sum *= 10;
This is same as sum = sum * 10 Syntax:
⚫ variable relation_operator value
⚫
/= sum /= 10;
This is same as sum = sum / 10 Example
%= sum %= 10;
⚫ X>5
This is same as sum = sum % 10
5.Ternary operator
⚫ ==, Equal to returns true if the left-hand side is equal to ⚫ Ternary operator:
the right-hand side.
⚫ !=, Not Equal to returns true if the left-hand side is not ⚫ Ternary operator is a shorthand version of the if-else
equal to the right-hand side. statement.
⚫ <, less than: returns true if the left-hand side is less than ⚫ It has three operands and hence the name ternary.
the right-hand side.
⚫ <=, less than or equal to returns true if the left-hand side ⚫ The general format is:
is less than or equal to the right-hand side. ⚫ condition ? if true : if false
⚫ >, Greater than: returns true if the left-hand side is
greater than the right-hand side.
⚫ >=, Greater than or equal to returns true if the left-hand
side is greater than or equal to the right-hand side.
Conditional Operator (Ternary Operator)
The conditional operator is also known as a ternary operator. The conditional statements are the decision-making
statements which depends upon the output of the expression. It is represented by two symbols, i.e., '?' and ':'.
6.Logical Operators
As conditional operator works on three operands, so it is also known as the ternary operator.
Logical Operators
⚫ Bitwise Operators:
⚫ These operators are used to perform the manipulation of
| Bitwise OR operator
individual bits of a number.
⚫ They can be used with any of the integer types. ^ Bitwise exclusive OR operator
⚫ They are used when performing update and query operations of
the Binary indexed trees.
⚫ &, Bitwise AND operator: returns bit by bit AND of input ~ One's complement operator (unary operator)
values.
⚫ |, Bitwise OR operator: returns bit by bit OR of input values.
⚫ ^, Bitwise XOR operator: returns bit-by-bit XOR of input << Left shift operator
values.
⚫ ~, Bitwise Complement Operator: This is a unary operator >> Right shift operator
which returns the one’s complement representation of the input
value, i.e., with all bits inverted.
a = 23;
a =6; The binary representation of the above two variables would be:
The binary representation of the above two variables are given b = 0000 1010
below: When we apply the bitwise OR operator in the above two variables, i.e., a|b ,
a = 0110 then the output would be:
Result = 0100
Bitwise ^ (Bitwise XOR) Bitwise ^ (Bitwise XOR)
Let’s take two integers say A = 5 and B = 9. Let’s take two integers say A = 5 and B = 9.
Then what will be the result of A ^ B? Then what will be the result of A ^ B?
Let’s represent each number in binary format. Let’s represent each number in binary format.
A = (0101) A = (0101)
B= (1001) B= (1001)
3 Types
⚫ 8. Shift Operators: ⚫ <<, Left shift operator: shifts the bits of the number to
⚫ These operators are used to shift the bits of a number the left and fills zer0 on voids left as a result. Similar effect
left or right. as multiplying the number with some power of two.
⚫ >>, Signed Right shift operator: shifts the bits of the
⚫ Syntax:
number to the right and fills 0 on voids left as a result. The
⚫ number shift_op number_of_places_to_shift; leftmost bit depends on the sign of the initial number.
⚫ Example: Similar effect as dividing the number with some power of
⚫ 7<<2 two.
⚫ 4>>3 ⚫ >>>, Unsigned Right shift operator: shifts the bits of the
number to the right and fills zero on voids left as a result.
The leftmost bit is set to zer0.(MSB=zer0)
Bitwise shift operators
int a = 5;
Two types of bitwise shift operators. The binary representation of 'a' is given below:
The bitwise shift operators will shift the bits either on the left-side or right-side. a = 0101
Therefore, we can say that the bitwise shift operator is divided into two categories: If we want to left-shift the above representation by 2, then the statement would be:
a << 2;
● Left-shift operator
0101<<2 = 00010100
● Right-shift operator
Left-shift operator
Let's understand through a program.
0 0 0 0 0 1 0 1
#include <stdio.h>
It is an operator that shifts the number of bits to the left-side. int main() 0 0 0 0 0 1 0 1
{
0 0 0 1 0 1 0 0
int a=5; // variable initialization
return 0;
int a = 7;
It is an operator that shifts the number of bits to the right side.
The binary representation of the above variable would be:
Syntax of the right-shift operator is given below:
a = 0111
Operand >> n;
If we want to right-shift the above representation by 2, then the statement would be:
Where, a>>2;
In the case of the right-shift operator, 'n' bits will be shifted on the right-side. The 'n' bits on the 0 0 0 0 0 0 0 1
right-side will be popped out, and 'n' bits on the left-side are filled with 0. #include <stdio.h>
int main()
return 0; }
Operators Summary
⚫ 9. instanceof operator:
⚫ The instance of the operator is used for type checking.
⚫ It can be used to test if an object is an instance of a
class, a subclass, or an interface.
⚫ Syntax:
⚫ object instance of class/subclass/interface
Tutorial:
⚫ Write a java program to implements all the operators
concepts.
⚫ Refer example sample programs for your referece.
1.Example Programs-unary
⚫ Unconditional branching
⚫ Based on particular condition (without any
decisions)
Types of conditional statements in C#
Conditional Statements
⚫ Conditionals ⚫ The if(condition) statement
⚫ Involve a program’s ability to deduce and do different ⚫ The else-if statement
things depending on the conditions of the codes ⚫ The else statement
written in that program.
⚫ Nested if Statements
Syntax
The else if Statement ⚫ if(condition 1)
⚫ {
// code block to be executed when if condition1 evaluates to true
⚫ }
⚫ Multiple else if statements can be used after ⚫ else if(condition 2)
⚫ {
an if statement.
// code block to be executed when
⚫ It will only be executed when the if condition // condition1 evaluates to false
evaluates to false. // condition2 evaluates to true
⚫ }
⚫ So, either if or one of the else if statements can be ⚫ else if(condition 3)
executed, but not both. ⚫ {
// code block to be executed when
// condition1 evaluates to false
// condition2 evaluates to false
// condition3 evaluates to true
⚫ }
Example The else Statement
⚫ int i = 10, j = 20;
⚫ Use the else statement to specify a block of code to be
⚫ if (i == j) executed if the condition is False. Or if-else condition is
⚫ { false.
Console.WriteLine("i is equal to j"); //10=20? False ⚫ Syntax
⚫ } ⚫ if (condition)
⚫ else if (i > j) ⚫ {
{ // block of code to be executed if the condition is True
Console.WriteLine("i is greater than j"); //10>20? False ⚫ }
⚫ } ⚫ else
⚫ else if (i < j) ⚫ {
⚫ { // block of code to be executed if the condition is False
Console.WriteLine("i is less than j"); //10<20? TRUE ⚫ }
⚫ }
Example-1 Example-2
⚫ int time = 9 ; ⚫ int time = 9 ;
⚫ if (time < 12) //9<12 ? TRUE ⚫ if (time < 12)
⚫ {
⚫ {
Console.WriteLine("Good Morning"); //9<12 True
Console.WriteLine("Good Morning"); ⚫ }
⚫} ⚫ else if (time < 16)
⚫ else ⚫ {
⚫{ Console.WriteLine("Good Afternoon."); //9<16 False
⚫ }
Console.WriteLine("Good Afternoon.");
⚫ else
⚫}
⚫ {
Console.WriteLine("GoodEvening”) //False
⚫ }
Syntax
if(condition 1)
Nested if -Statements {
if(condition 2)
{
// code block to be executed when condition 1 and condition 2 evaluates to true
}
Example
int i = 10, j = 20;
if (i != j)
{
if (i < j)
Ternary Operator ?:
{ ⚫ Java includes a decision-making operator ?:
System.out.println("i is less than j"); //10<20 True
} ⚫ which is called the conditional operator or ternary
else if (i > j) operator.
{
⚫ It is the short form of the if else conditions.
System.out.println ("i is greater than j"); //10>20 False
}
}
else
{
System.out.println ("i is equal to j"); //10=20 False
}
Nested Ternary Operator
Syntax ⚫ Nested ternary operators are possible by including a
conditional expression as a second statement.
⚫ Example:
condition ? statement 1 : statement 2 var x = 2, y = 10;
Example: var result = (x * 3 )> y ? x : y > z? y : z;
int x = 20, y = 10; System.out.println(result);
var result = x > y ? "x is greater than y" : "x is less than y"; Explanation:
System.out.println(result); x*3 ?y – Condition
x – True Statement
Output: y > z – Condition
x is greater than y y= true staement
z- False statement
Syntax:
switch statement switch(match expression/variable)
{
⚫ The switch statement can be used instead of if
case constant-value:
else statement when you want to test a variable against
statement(s) to be executed;
three or more conditions.
break;
case constant-value:
statement(s) to be executed;
break;
default: statement(s) to be executed;
break;
}
Example
int x = 10;
switch (x)
Loops
{
case 5:
System.out.println ("Value of x is 5"); ⚫ A loop statement allows us to execute a statement or a
break; group of statements multiple times.
⚫ It can be divides as
case 10:
System.out.println ("Value of x is 10");
break; ⚫ Loop Statements
case 15: ⚫ Loop Control Statements
System.out.println ("Value of x is 15");
break;
default:
System.out.println ("Unknown value");
break;
}
For Loop
⚫ It Uses the Keyword for
Loop Statements ⚫ The for loop executes a block of statements repeatedly
⚫ Loop Statements: until the specified condition returns false.
⚫ Looping statement are the statements execute one or ⚫ For Loops types
more statement repeatedly several number of times ⚫ For
⚫ Nested For
⚫ Infinite For
⚫ Types of Loop Statements ⚫ For each
⚫ For Loop ⚫ Syntax:
⚫ While Loop for(initialization; condition; incr/decr)
⚫ Do-While Loop {
//code to be executed
}
For Loop –Flow Diagram
For Loop Explanation
⚫ Initialization:
⚫ The initialization section is used to initialize a variable.
⚫ It will be local variable to a for loop and cannot be
accessed outside loop.
⚫ Condition:
⚫ The condition is a Boolean expression that will return
either true or false.
⚫ If an expression evaluates to true, then it will execute
the loop again; otherwise, the loop is exited.
⚫ Iteration:
⚫ The iteration defines the increment or decrement of the
loop variable.
Example OUTPUT
⚫
⚫ public class ForExample
⚫ {
⚫ public static void main(string[] args)
⚫ {
⚫ for(int i=1;i<=10;i++)
⚫ {
⚫ System.out.println(i);
⚫ }
⚫ }
⚫ }
Nested For Loop Example
⚫
⚫ For loop is executed inside another For loop, it is ⚫ public class NestedForExample
known as nested for loop. ⚫ {
⚫ Syntax: ⚫ public static void main(string[] args)
⚫ for(initialization; condition; incr/decr) ⚫ {
⚫ for(int i=1;i<=3;i++)
⚫ { ⚫ {
⚫ for(initialization; condition; incr/decr) ⚫ for(int j=1;j<=3;j++)
⚫ { ⚫ {
⚫ System.out.println (i+" "+j);
⚫ System.out.println (---------); ⚫ }
⚫ } ⚫ }
⚫ } ⚫ }
⚫ }
⚫ //statements ⚫ System.out.println(i);
⚫ }
⚫ }
While While Flow Diagram
⚫ A while loop statement in java repeatedly executes a
target statement as long as a given condition is true.
⚫ while loops, which test the loop condition at the start
of the loop
⚫ Syntax
⚫ while(condition)
⚫ {
⚫ statement(s);
⚫ }
Example OUTPUT
⚫ public class WhileExample
⚫ {
⚫ public static void main(string[] args)
⚫ {
⚫ int i=1;
⚫ while(i<=10)
⚫ {
⚫ System.out.println (i);
⚫ i++;
⚫ }
⚫ }
⚫ }
Nested While Loop Example: Example
⚫ While loop is used inside another while loop, it is known as
nested while loop. ⚫ public static void main(string[] args)
⚫ The nested while loop is executed fully when outer loop is ⚫ {
executed once. ⚫ int i=1;
⚫ Syntax: ⚫ while(i<=3)
⚫ while(condition) ⚫ {
⚫ { ⚫ int j = 1;
⚫ // Statements ⚫ while (j <= 3)
⚫ // increment or Decrement ⚫ {
⚫ while (condition) ⚫ System.out.println(i+" "+j);
⚫ { ⚫ j++;
⚫ // Statements ⚫ }
⚫ // increment or Decrement ⚫ i++;
⚫ } ⚫ }
⚫ ⚫ }
⚫ }
Break
⚫
Statement with Inner Loop
public class BreakExample
OUTPUT ⚫
⚫
{
public static void main(string[] args)
⚫ {
⚫ for(int i=1;i<=3;i++) // Outer Loop
⚫ {
⚫ for(int j=1;j<=3;j++) // Inner Loop
⚫ {
⚫ if(i==2&&j==2)
⚫ {
⚫ break;
⚫ }
⚫
⚫ System.out.println+" "+j);
⚫ }
⚫ }
⚫ }
⚫ }
Continue Statement
output ⚫ The continue statement is used to continue loop.
⚫ It continues the current flow of the program and skips
the remaining code at specified condition.
⚫ In case of inner loop, it continues only inner loop.
⚫ Syntax:
continue;
Example
⚫class A
Output
⚫ {
⚫ public static void main(string[] args)
⚫ {
⚫ ineligible:
⚫ System.out.println ("You are not eligible to vote!");
⚫ System.out.println ("Enter your age:\n");
⚫ Scanner input = new Scanner (System.in);
⚫ int age = input.NextInt());
⚫ if (age < 18)
⚫ {
⚫ goto ineligible;
⚫ }
⚫ else
⚫ {
⚫ System.out.println("You are eligible to vote!");
⚫ }
⚫ }
⚫ }
Array
⚫ Normally ,An array is a collection of similar type of elements which has
Example:2 contiguous memory location.
⚫
⚫ Java array is an object which contains elements of a similar data type.
class A
⚫ {
⚫ public static void main(string[] args)
⚫
⚫ The elements of an array are stored in a contiguous memory location.
{
⚫ System.out.println ("Enter your age:\n");
⚫ Scanner input = new Scanner (System.in);
⚫
⚫
int age = input.NextInt());
if (age < 18)
⚫ It is a data structure where can store similar elements.
⚫ {
⚫ goto ineligible; ⚫ Can store only a fixed set of elements in a Java array.
⚫ }
⚫ else
⚫ { ⚫ Array in Java is index-based, the first element of the array is stored at
⚫ System.out.println("You are eligible to vote!"); the zer0th index, 2nd element is stored on 1st index and so on.
⚫ }
⚫ ineligible:
⚫ System.out.println ("You are not eligible to vote!"); ⚫ In Java, array is an object of a dynamically generated class.
⚫
⚫ }
⚫ }
⚫
int arr[][] = { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };
int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; ⚫
⚫ //printing 2D array ⚫ // printing 2D array
⚫
⚫
for (int i = 0; i < 3; i++)
for(int i=0;i<3;i++){ ⚫ {
⚫ for(int j=0;j<3;j++){ ⚫ for (int j = 0; j < 3; j++)
⚫ System.out.print(arr[i][j]+" "); ⚫
⚫
{
⚫
System.out.print(arr[i][j] + " ");
} ⚫ }
⚫ System.out.println(); ⚫
⚫
⚫
}
} ⚫ }
⚫ } ⚫ }
}
Object
•An Object can be defined as an instance of a class.
•An object contains an address and takes up some space
in memory.
•Objects can communicate without knowing the details
of each other's data or code.
•The only necessary thing is the type of message
accepted and the type of response returned by the 4
objects.
Object concept in programming:
Constructor Types
⚫ In Java, a constructor is a block of codes similar to the ⚫ There are two types of constructors in Java:
method.
⚫ no-arg constructor(default)
⚫ It is called when an instance of the class is created.
⚫ parameterized constructor.
⚫ At the time of calling constructor, memory for the object is
allocated in the memory.
⚫ There are two rules defined for the constructor. ⚫ A constructor is called "Default Constructor" when it
doesn't have any parameter.
⚫ Constructor name must be the same as its class name ⚫ Syntax of default constructor:
⚫ A Constructor must have no explicit return type 1. <class_name>()
⚫ A Java constructor cannot be abstract, static, final, and 2. {
synchronized 3. --------
4. }
Defining a Constructor
Constructor class Car
⚫ A constructor is a special method which has same {
name as class name. public string model;
⚫ It will invoke when object is created. public string color;
public Car() //Constructor
⚫ Syntax {
⚫ Constructor name() //same as class name model=“volkswagan polo”;
⚫ { color=“red”;
⚫ } }
}
Type of constructors
⚫ Default Constructor Parameterized Constructor:
⚫ Parameterized Constructor ⚫ When any constructor has at least one parameter, it is
Default Constructor: called the parameterized constructor.
⚫ When constructors do not have parameters, then it is called the default ⚫ Example
constructor. class Car
⚫ These types of constructors have all its objects initialized with the same {
value. public string green;
⚫ Example
public Car(string color) //parameter is used
class Car
{
{
green= color;
public Car()
}
{
……..
}
}
}
2m/3m-important example
⚫ Can we overload java main() method?
⚫ class mover
⚫ {
⚫ Yes, by method overloading. ⚫
⚫
public static void main(String[] args)
{
⚫ We can have any number of main methods in a class ⚫
⚫
System.out.println("main with String[]");
}
by method overloading. ⚫ public static void main(String args)
⚫
⚫ But JVM calls main() method which receives string
{
⚫ System.out.println("main with String");
⚫ }
array as arguments only. ⚫ public static void main()
⚫ {
⚫ System.out.println("main without args");
⚫ }
⚫ }
⚫ O/p
⚫ main with String[]
this keyword in Java Usage of Java this keyword
⚫ There can be a lot of usage of Java this keyword. ⚫ The 6 usage of java this keyword.
⚫ In Java, this is a reference variable that refers to the ⚫ this can be used to refer current class instance
current object. variable.
⚫ this can be used to invoke current class method
(implicitly)
⚫ this() can be used to invoke current class constructor.
⚫ this can be passed as an argument in the method call.
⚫ this can be passed as argument in the constructor call.
⚫ this can be used to return the current class instance
from the method.
Inheritance
⚫ Inheritance (Derived and Base Class)
⚫ It is possible to inherit attributes and methods from
Inheritance Cont..
one class to another. Or ⚫ For Example
⚫ The Car class (subclass) inherits the attributes and methods
⚫ It is a mechanism in which one object acquires all the from the Vehicle class (superclass)
properties and behaviors of a parent object. ⚫ Types
⚫ The "inheritance concept" into two categories: Class A
Father
⚫ superclass (parent) - the class being inherited from ⚫ Single Inheritance
⚫ subclass (child) - the class that inherits from another
class ⚫ Hierarchical Inheritance
⚫ Deriving the properties from super class to sub
⚫ Multiple Inheritance -Interface
class. Class B extends A
⚫ class Main
Example: Programs-single ⚫ {
inheritance ⚫ public static void main(String[] args)
⚫ class Animal
⚫ {
⚫ { ⚫ // create an object of the subclass
⚫
⚫
// field and method of the parent class
⚫ String name; Dog la= new Dog();
⚫
⚫
public void eat()
⚫ { // access field of superclass
⚫
⚫
System.out.println("I can eat");
⚫ } la.name = "Rownu";
⚫
⚫
}
⚫ // inherit from Animal la.display();
⚫
⚫ class Dog extends Animal
⚫ { // call method of superclass
⚫
⚫
// new method in subclass
public void display() ⚫ // using object of subclass
⚫
⚫
{
System.out.println("My name is " + name);
⚫ la.eat();
⚫ } ⚫ }
⚫ }
⚫ }
Hierarchical Inheritance Hierarchical Inheritance
⚫ When two or more classes inherits a single class, it is
known as hierarchical inheritance. FATHER
Example:Hierarchical Program-2
⚫ class parent
⚫ class Animal
⚫ {
⚫
⚫ void eat()
⚫ { {
⚫
⚫ protected static int num1= 15;
System.out.println("eating...");
⚫ }
⚫
⚫
}
⚫
⚫
class Dog extends Animal{
void bark(){System.out.println("barking...");}
protected static void methodA () //method
⚫
⚫
}
class Cat extends Animal{ ⚫ {
⚫
⚫ void meow(){System.out.println("meowing...");}
⚫ } System.out.println ("Value of protected
⚫
⚫
class TestInheritance3{
public static void main(String args[]){ variable num1 in Superclass = " + num1);
⚫ }
⚫ Cat c=new Cat();
⚫ c.meow();
⚫
⚫ c.eat();
⚫ //c.bark();//C.T.Error }
⚫ }}
⚫ class child1 extends parent
⚫ {
⚫
⚫ private static int num2 = 25;
class child2 extends parent
⚫ {
⚫ protected static void methodB () //Method ⚫
⚫
private static int num3 = 45;
public static void methodC () //method
⚫ { ⚫ {
⚫
⚫
System.out.println("Value of private variable num3 in Subclass2 is
System.out.println ("Value of private variable = " + num3);
⚫ }
num2 in Subclass1 is = " + num2); ⚫ public static void main(String args[])
⚫ System.out.println ("Value of protected ⚫ { child2 c2 = new child2 ();
⚫ c2.methodA(); //calling super class method
variable num1 in Superclass = " + num1); ⚫ c2.methodC(); //calling own method
⚫ } ⚫
⚫
child1 c1 = new child1 ();
c1.methodB();
⚫ } ⚫ }
⚫ }
⚫ o/p
⚫ Compile time error– because final method
Visibility Control
⚫ Visibility
⚫ (controlling access to members of a class)
⚫ private visibility allows a variable to only be accessed by its class.
⚫
⚫ public class SomeOtherClass
They are often used in conjunction with public getters and setters
⚫ Example ⚫ {
⚫ class SomeClass ⚫ public static void main(String[] args)
⚫ { ⚫ {
⚫ private int variable; ⚫ SomeClass sc = new SomeClass();
⚫ public int getVariable() ⚫ // These statement won't compile because in SomeClass variable is
⚫ { private:
⚫ return variable; ⚫ sc.variable = 7;
⚫ } ⚫ System.out.println(sc.variable);
⚫ public void setVariable(int variable) ⚫ // Instead, you should use the public getter and setter:
⚫ { sc.setVariable(7);
⚫ this.variable = variable; ⚫ System.out.println(sc.getVariable());
⚫
⚫ }
}
⚫
⚫ }
}
Public Visibility
⚫ Visible to the class, package, and subclass
⚫ Example
⚫ public class Test
⚫ {
⚫ public int number = 2;
⚫ public Test()
⚫ {
⚫ }
⚫ }
⚫ public class Other
⚫ {
⚫ public static void main(String[] args)
⚫ {
⚫ Test t = new Test();
⚫ System.out.println(t.number);
⚫ }
⚫ }
Protected Visibility
⚫ Protected visibility causes means that this member is visible to its package, along with
⚫
any of its subclasses.
Example:
Simple programs-tutorial week 6
⚫ class Animal ⚫ 1.Create a class named 'Person' with the following
⚫ {
⚫ Data members:
⚫ // protected method
⚫ Name
⚫ protected void display()
⚫ Age
⚫ {
⚫ Phone number
⚫ System.out.println("I am an animal");
⚫ } ⚫ Location
⚫ } ⚫ Method:
⚫ class Dog extends Animal ⚫ Person_information
⚫ { ⚫ Note:
⚫ public static void main(String[] args) ⚫ Create a class ‘employee’ which is inherits from ‘person’ class which will hold the
⚫ { method as ‘display details’ and data members as ‘department and designation.
⚫ // create an object of Dog class ⚫ Create a class ‘salary’ which inherits from employee class and hold the method
⚫ Dog dog = new Dog(); ‘net_pay’ and data member salary.
⚫ ⚫ Create an object for ‘salary’ class and invoke all the method associated to classes.
⚫ // access protected method
⚫ dog.display();
⚫ }
⚫ }
⚫ 2. Create a class called hostelwith the following. ⚫ 3. Create a class called Rectangle with the following
⚫
⚫ Data Members:
Data Members:
⚫ Hostel Rent
⚫ Mess bill ⚫ Length
⚫ Wi-Fi charges ⚫ Breadth
⚫ Warden fine ⚫ Area
⚫ Methods ⚫ Perimeter
⚫ To calculate the total monthly expense for an hostel
⚫ To display all the values. ⚫ Methods
⚫ Note: ⚫ To calculate the area of a rectangle
⚫ Use instance methods for setting and retrieving values. ⚫ To Calculate the perimeter of a rectangle
⚫ Instantiate an object to activate the class and their members and ⚫ To display the values
method.
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:
Packages-
⚫ Contains language support classes(e.g classed which defines primitive data types,
math operations). ⚫ java.lang − bundles the fundamental classes
⚫ This package is automatically imported.
⚫ 2) java.io:
⚫ Contains classed for supporting input / output operations.
⚫ 3) java.util:
⚫ java.io − classes for input , output functions are
⚫ Contains utility classes which implement data structures like Linked List, bundled in this package
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 package
Syntax
⚫ user-defined package ⚫ package package_name;
⚫ create your own packages.
⚫ Java uses a file system directory to store them. Just like ⚫ Example
⚫ package mypack;
folders on your computer:
⚫ Example
⚫ └── root
⚫ └── mypack
⚫ └── MyPackageClass.java
⚫ To create a package, use the package keyword
Usage of Packages
⚫ To avoid name conflicts
Example ⚫ Example
⚫ Two classes with name Employee in two packages,
⚫ package mypack; college.staff.cse.Employee
⚫ class MyPackageClass college.staff.ece.Employee
⚫ To write a better maintainable code.
⚫ {
⚫ To Make easier to searching/locating and usage of classes,
⚫ public static void main(String[] args) interfaces and enumerations easier
⚫ { ⚫ To Provide controlled access
⚫ Example:
⚫ System.out.println("This is my package!");
⚫ Protected and default have package level access control.
⚫ } ⚫ A protected member is accessible by classes in the same package
⚫ To run
⚫ java Test // run main class
Program-MathOperations.Java
⚫ package arithmetic; // package creation
⚫ public class MathOperations // class creation and definition
⚫ {
Packages ⚫
⚫
public int addition (int a, int b) // method definition
{
⚫
⚫ 6. B)
return a + b;
PROGRAM TO PERFORM ARITHMETIC ⚫ }
⚫
OPERATION USING PACKAGES ⚫
public int subtraction (int a, int b)
{
⚫ return a - b;
⚫ }
⚫ public int multiplication (int a, int b)
⚫ {
⚫ return a * b;
⚫ }
⚫ public int division (int a, int b)
⚫ {
⚫ return a / b;
⚫ }
⚫ public int mod (int a, int b)
⚫ {
⚫ return a % b;
⚫ }
⚫ }
MathTest.java
⚫ import arithmetic.MathOperations; // Package import (use pakage) ⚫ int sum=obj.addition(n1,n2);
⚫ import java.util.*; // util package ⚫ int diff=obj.subtraction(n1,n2);
⚫ class MathTest ⚫ int prod=obj.multiplication(n1,n2);
⚫ { ⚫ int quot=obj.division(n1,n2);
⚫ public static void main(String args[]) ⚫ int rem=obj.mod(n1,n2);
⚫ { ⚫ System.out.println("Sum= " + sum);
⚫ Scanner input=new Scanner(System.in);
⚫ System.out.println("Difference= " + diff);
⚫ System.out.println("Enter the first number:");
⚫ int n1=input.nextInt(); //read values from user ⚫ System.out.println("Product= " + prod);
⚫ System.out.println("Enter the second number:"); ⚫ System.out.println("Quotient= " + quot);
⚫ int n2=input.nextInt(); //read values from user ⚫ System.out.println("Remainder= " + rem);
⚫ MathOperations obj=new MathOperations(); ⚫ }
⚫ ⚫ }
//Result.java
⚫ totalMarks = marksSubject1 + marksSubject2 +
⚫ package student; // use package marksSubject3 + marksSubject4;
⚫ public class Result extends Test // multilevel inheritance ⚫ percentage = (totalMarks*100.00F/600.00F);
⚫ { ⚫ if (percentage >=50.00F)
⚫ private int totalMarks; ⚫ grade=’D’;
⚫ else
⚫ private float percentage;
⚫ if(percentage >=55.00F && percentage<=60.00F)
⚫ private char grade; ⚫ grade = ‘C’;
⚫ public Result(int rno, String sname, String sadd,int mi, int ⚫ else
m2, int m3, int m4) //parameterized constructor Result ⚫ if (percentage >=6l.00F && percentage<=70.00F)
⚫ { ⚫ grade = ‘B’;
⚫ super(rno,sname,sadd,ml,m2,m3,m4); //super method ⚫ else
⚫ if(percentage >=7l.00F && percentage<=75.00F)
⚫ grade = ‘A’;
⚫ else //Demo.java
⚫ if (percentage >=76.00F && percentage<=85.00F)
⚫ grade = ‘H’;
⚫ else ⚫ import student.Result; //import student package
⚫ grade = ‘S’; ⚫ public class Demo
⚫ } ⚫ {
⚫ public void show()
⚫ { ⚫ public static void main(String ar[])
⚫ super.show(); // It will show Test class show method ⚫ {
⚫ System.out.println(“Total Marks :: ” + totalMarks); ⚫ Result ob = new Result (1001, “Alice”, “New
⚫ System.out.println(“Percentage :: ” + percentage); York”,135,130,132,138);
⚫ System.out.println(“Grade :: ” + grade); ⚫ ob.show (); // display result show method
⚫ } ⚫}
⚫
⚫}
}
Exception
⚫ Exception is an abnormal condition.
⚫ An exception is a condition that causes Run time errors in
the program.
⚫ coding errors made by the programmer.
⚫ Java interpreter encounters an error ,it create an exception
object and throws it(inform us that an error has occurred)
⚫ Exception Handling
Advantage of Exception Handling ⚫ It is a mechanism to handle runtime errors such as
⚫ ClassNotFoundException,
⚫ IOException,
Unchecked Exception
⚫ The classes that inherit the RuntimeException are
known as unchecked exceptions.
⚫ For example,
⚫ ArithmeticException,
⚫ NullPointerException,
⚫ ArrayIndexOutOfBoundsException, etc.
⚫ Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
Java Exception Keywords Throws vs throw 2m/3m
⚫ try
⚫ specify a block of code where should place an exception code
⚫ catch
⚫ The "catch" block is used to handle the exception
⚫ Finally
⚫ The "finally" block is used to execute the necessary code of the
program
⚫ Throw
⚫ The "throw" keyword is used to throw an exception.
⚫ Throws-
⚫ The "throws" keyword is used to declare exceptions.
⚫ It specifies that there may occur an exception in the method.
⚫ It doesn't throw an exception.
⚫ It is always used with method signature.
Throws vs throw syntax
⚫ try
⚫ {
⚫ // Block of code to try
⚫ }
⚫ catch (Exception e)
⚫ {
⚫ // Block of code to handle errors
⚫ }
Try catch
⚫ Try ⚫ Catch
⚫ The try statement allows you to define a block of code ⚫ The catch statement allows you to define a block of
to be tested for errors while it is being executed. code to be executed, if an error occurs in the try block.
⚫ try //try block operation ⚫ catch (ArithmeticException e)
⚫ { ⚫ {
⚫ result = num1 / num2; ⚫ System.out.println(e);
⚫ } ⚫ }
Finally throw
⚫ Finally ⚫ Used to throw own exceptions.
⚫ Used to handle the exception ⚫ Using throw keyword.
⚫ The finally statement lets you execute code, ⚫ Syntax:
after try...catch, regardless of the result: ⚫ throw new throwable_subcclass
⚫ finally //final statement to print result ⚫ Example:
⚫ { ⚫ throw new AgeInvalidException(-----)
⚫ int result=a[1]/a[0];
⚫ system.out.println ("Result: ", result);
⚫ }
Multiple catch-syntax
⚫ try
⚫
Multiple catch statements-3m ⚫
⚫
{
---------
}
//generate exception
⚫ Possible to have one or more catch statements in the ⚫ catch (Exception type-1 e)
⚫ {
catch block ⚫ ------- // process exception type 1
⚫ }
⚫ catch(Exception type-2 e)
⚫ {
⚫ --------- // process exception type 2
⚫ }
⚫ .
⚫ .
⚫ catch(Exception type-N e)
⚫ {
⚫ --------- // process exception type N
⚫ }
Multiple catch statements-3m ⚫ catch(ArithmeticException e)
⚫ {
Example program ⚫ System.out.println(“Divided by zero”);
⚫
⚫ class error
}
⚫ catch(ArrayIndexOutOfBoundException e)
⚫{ ⚫ {
⚫ public static void main(String args[]) ⚫ System.out.println(“Array index error”);
⚫
⚫ { }
⚫ catch(ArrayStoreException e)
⚫ int a[ ]={5,10}; ⚫ {
⚫ int b=5; ⚫ System.out.println(“Wrong Data type”);
⚫ try ⚫ }
⚫
⚫
int y=a[1]/a[0];
{ ⚫ System.ot.println(“y=“ +y);
⚫ int x= a[2]/5-a[1]; ⚫ }
⚫ } ⚫ }
}
System.out.println(“Divided by zero”); Output
⚫ catch(ArrayIndexOutOfBoundException e)
⚫ {
⚫ System.out.println(“Array index error”);
⚫ }
⚫ catch(ArrayStoreException e)
⚫ {
⚫ System.out.println(“Wrong Data type”);
⚫ }
⚫ finally
⚫ {
⚫ int y=a[0]/a[1];
⚫ System.ot.println(“y=“ +y);
⚫ }
⚫ }
⚫ }
Runnable interface:
Thread class ⚫ The Runnable interface should be implemented by any
class whose instances(objects) are intended to be
⚫ Thread class provide constructors and methods to executed by a thread.
create and perform operations on a thread. ⚫ Runnable interface have only one method named run().
⚫ Thread class extends Object class and implements public void run(): is used to perform action for a
Runnable interface. thread.
⚫ Commonly used constructors of thread class ⚫ Starting a thread:
• Thread() ⚫ The start() method of Thread class is used to start a
newly created thread. It performs the following tasks:
• Thread(String name)
• A new thread starts(with new call stack).
• Thread(Runnable r)
• The thread moves from New state to the Runnable state.
• Thread(Runnable r,String name) • When the thread gets a chance to execute, its target run()
method will run.
java Thread Example by
Steps for implementing Runnable implementing Runnable
Interface interface
⚫ The thread can be defined by implementing Runnable interface class Single2 implements Runnable //Step 1
⚫ 1. Define classes by implementing Runnable interface
⚫ class classname implements Runnable
{
⚫ { public void run() // Step 2
⚫ } {
⚫ 2. Override the run() method in all subclasses.
System.out.println("thread is running...");
⚫ public void run ( ) }
⚫ { public static void main(String args[])
⚫ }
{
⚫ 3. Create thread object in the main() method Single2 m1=new Single2(); // class object creation , Step 3
⚫ classname object = new classname();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
⚫ 4. Use Thread Constructor(use any one) and create an thread class object and
⚫ pass the object to thread class //Step 4
⚫ Thread obj1= new Thread("My first thread"); or t1.start(); // Step 5
Thread obj1 = new Thread(object);
}
⚫ 5. Call the start method using the Runnable constructor Thread object. }
⚫ obj1.start(); ⚫ o/p
⚫ thread is running…
Syntax Thread A
synchronized void update() Synchronized method1()
{
{ Synchronized method2()
--------- {
---------
} }
}
Thread B
synchronized (lock object) Synchronized method1()
{
{ Synchronized method2()
--------- ---------
} }
}
Example class MyThread1 extends Thread
class Table {
{
synchronized void printTable(int n) //synchronized method (Step-6) Table t; //object creation for table class
{ MyThread1(Table t) //parameterized constructor
for(int i=1;i<=5;i++) (-step 2)
{
System.out.println(n*i); // print table values (step-7)
{
try this.t=t; //reference variable that refers to the current
{ object of a method or a constructor.
Thread.sleep(400); //thread is in sleep mode for 400 milliseconds }
}
catch(Exception e)
public void run() (Step-4)
{ {
System.out.println(e); t.printTable(5); //invoke printable method
}
}
}
}
} }
Swings
⚫ Basic swing components:
Unit-4 -THREADS AND SWINGS ⚫ JLabel,
⚫ JTextField,
⚫ Creating Threads ⚫ JTextArea,
⚫ Extending the Thread Class ⚫ JPasswordField,
⚫ JButton,
⚫ Stopping and Blocking Thread
⚫ JCheckBox,
⚫ Life Cycle of a Thread ⚫ JRadioButton,
⚫ Thread Exceptions ⚫ JPanel,
⚫ JList,
⚫ Thread Priority-Synchronization. ⚫ JComboBox,
⚫ Swings ⚫ User Interface Design - Event Handling :
⚫ Action events,
⚫ Basic swing components:
⚫ Key events,
⚫ User Interface Design - Event Handling ⚫ Item events.
Swings Java Swing
⚫ Used to create window-based applications. ⚫ Java Swing is a part of Java Foundation Classes (JFC)
⚫ It is built on the top of AWT (Abstract Windowing Toolkit) that is used to create window-based applications.
API and entirely written in java.
⚫ The javax.swing package provides classes for java swing API
such as ⚫ What is JFC?
⚫ JButton,
⚫ JTextField, ⚫ The Java Foundation Classes (JFC) are a set of GUI
⚫ JTextArea, components which simplify the development of
⚫ JRadioButton, desktop applications.
⚫ JCheckbox,
⚫ JMenu,
⚫ JColorChooser etc.
AWT Vs Swings
Features of Swing
⚫ 1.Platform Independent
⚫ 2.Lightweight:
⚫ 3.Pluggable Look and Feel
⚫ 4.Extensible and Configurable
⚫ 5.MVC
⚫ 6.Customizable
⚫ 7.Rich Controls
⚫ Every user interface considers the following three main
aspects .
⚫ UI Elements
⚫ Layouts
⚫ Behavior
Container Class Swing Components in java
⚫ Container classes are classes that can have other
components on it.
⚫ So for creating a GUI, need at least one container object.
⚫ There are 3 types of containers.
⚫ Panel: It is a pure container and is not a window in itself.
The sole purpose of a Panel is to organize the components
on to a window.
⚫ Frame: It is a fully functioning window with its title and
icons.
⚫ Dialog: It can be thought of like a pop-up window that
pops out when a message has to be displayed. It is not a
fully functioning window like the Frame
⚫ Note:
⚫ Add frame to add all the swing components
Java Swing Examples Example- method 1(Association)
import javax.swing.*;
public class MySwingExample
{
JTextField JTextArea
⚫ JTextArea class provides a multi-line text box.
⚫ JTextField provides an editable single-line text box. ⚫ Similar to the JTextField, a user can input
⚫ A user can input non-formatted text in the box. non-formatted text in the field.
⚫ To initialize the text field, call its constructor and ⚫ The constructor for JTextArea also expects two
pass an optional integer parameter to it. integer parameters which define the height and
width of the text-area in columns.
⚫
⚫
This parameter sets the width of the box measured
It does not restrict the number of characters that the
by the number of columns. user can input in the text-area.
⚫ It does not limit the number of characters that can ⚫ JTextArea txtArea = new JTextArea(“Welcome you
be input in the box. all for the Event”, 5, 20);
⚫ JTextField txtBox = new JTextField(20); ⚫ The above code provides a multi-line text-area of
⚫ It renders a text box of 20 column width. height 5 rows and width 20 columns, with default
text initialized in the text-area.
JPasswordField JCheckBox
⚫ JPasswordField is a subclass of JTextField class.
⚫ It provides a text-box that masks the user input text ⚫ JCheckBox provides a check-box with a label.
with bullet points. ⚫ The check-box has two states – on/off.
⚫ This is used for inserting passwords into the ⚫ When selected, the state is on and a small tick is
application. displayed in the box.
⚫ Example: ⚫ CheckBox chkBox = new JCheckBox(“Show Help”,
⚫ JPasswordField pwdField = new JPasswordField(15); true);
var pwdValue = pwdField.getPassword(); ⚫ It is a boolean value that indicates the default state
⚫ it returns a password field of 15 column width. of the check-box.
⚫ The getPassword method gets the value entered by ⚫ True means the check-box is defaulted to on state.
the user.
JRadioButton JList
⚫ JRadioButton is used to provide a group of radio buttons ⚫ JList component provides a scrollable list of elements.
in the UI. ⚫ A user can select a value or multiple values from the list.
⚫ A user can select one choice from the group. ⚫ DefaultListItem cityList = new DefaultListItem();
⚫ ButtonGroup radioGroup = new ButtonGroup(); fruitList.addElement(“Mango”):
JRadioButton rb1 = new JRadioButton(“Red”, true); fruitList.addElement(“Apple”):
JRadioButton rb2 = new JRadioButton(“Green”); fruitList.addElement(“Orange”):
JRadioButton rb3 = new JRadioButton(“Blue”); fruitList.addElement(“Lichi”):
radioGroup.add(rb1); fruitList.addElement(“Jackfruit”):
radioGroup.add(rb2); JList fruits = new JList(fruitList);
radioGroup.add(rb3); fruits.setSelectionModel(ListSelectionModel.SINGLE_S
⚫ The above code creates a button group and three radio ELECTION);
button elements. ⚫ The above code renders a list of fruits with 5 items in the
⚫ All three elements are then added to the group list.
⚫ This ensures that only one option out of the available ⚫ The selection restriction is set to SINGLE_SELECTION.
options in the group can be selected at a time. ⚫ If multiple selections is to be allowed, set the behavior
⚫ The default selected option is set to Easy. to MULTIPLE_INTERVAL_SELECTION.
JComboBox
⚫ JComboBox class is used to provide a dropdown of
the list of options. JPanel
String[] cityStrings = { "Mumbai", "London", "New
⚫ It provides space in which an application can
York", "Sydney", "Tokyo" };
attach any other component.
JComboBox cities = new JComboBox(cityList);
⚫ It inherits the JComponents class.
cities.setSelectedIndex(3);
⚫ The default selected option can be specified through
the setSelectedIndex method. JPanel panel=new JPanel();
⚫ The above code sets Sydney as the default selected panel.setBounds(40,80,200,200);
option. panel.setBackground(Color.gray);
Types of Event
⚫ The events can be broadly classified into two categories −
⚫ Foreground Events
Event Handling
⚫ These events require direct interaction of the user.
⚫ They are generated as consequences of a person interacting with the graphical
⚫ ❖ Event Handling is the mechanism that controls the
components in the Graphical User Interface. event and decides what should happen if an event
⚫ For example,
⚫ clicking on a button, occurs.
⚫ moving the mouse,
⚫ entering a character through keyboard
⚫ ❖ This mechanism has a code which is known as an
⚫ selecting an item from list event handler, that is executed when an event occurs.
⚫ scrolling the page, etc.
⚫ Background Events ⚫ ❖ Java uses the Delegation Event Model to handle the
⚫ These events require the interaction of the end user.
⚫ For Example,
events.
⚫ Operating system interrupts
⚫ hardware or software failure
⚫ ❖ This model defines the standard mechanism to
⚫ timer expiration, generate and handle the events.
⚫
⚫ operation completion
❖
⚫ The Delegation Event Model has the following key participants. ⚫ In the event model, there are three participants:
⚫ ❖ Source ⚫ event source
⚫ The source is an object on which the event occurs. ⚫ event object
⚫ Source is responsible for providing information of the occurred ⚫ event listener
⚫ Event source is the object whose state changes. It generates
event to it's handler.
⚫ Java provide us with classes for the source object.
Events.
⚫ ❖ Listener
⚫ It is also known as event handler.
⚫ Event object (Event) encapsulates the state changes in the
⚫ The listener is responsible for generating a response to an event.
event source.
⚫ ❖ The listener waits till it receives an event. ⚫ Event listener is the object that wants to be notified.
⚫ Once the event is received, the listener processes the event and ⚫ Event source object delegates the task of handling an event
then returns. to the event listener
ActionEvent ActionListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Steps to perform Event
Handling • TextField
• public void addActionListener(ActionListener a){}
⚫ Following steps are required to perform event • public void addTextListener(TextListener a){}
handling: • TextArea
Register the component with the Listener • public void addTextListener(TextListener a){}
⚫ Registration Methods • Checkbox
⚫ For registering the component with the • public void addItemListener(ItemListener a){}
Listener, many classes provide the registration Choice
methods. • public void addItemListener(ItemListener a){}
⚫ For example:
• List
• Button • public void addActionListener(ActionListener a){}
• public void addActionListener(ActionListener • public void addItemListener(ItemListener a){}
a){}
• MenuItem
• public void addActionListener(ActionListener
a){}
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener
Action Listner {
TextField tf;
⚫ ActionListener is notified whenever you click on AEvent()
{
the button or menu item.
⚫ It is notified against ActionEvent. //create components
⚫
tf=new TextField();
The ActionListener interface is found in tf.setBounds(60,50,170,20);
java.awt.event package. Button b=new Button("click me");
⚫
b.setBounds(100,120,80,30);
It has only one method:
⚫ actionPerformed(). //register listener
b.addActionListener(this);//passing current instance
//add components and set size, layout and visibility
add(b);
add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}
Establishing a simple server-
Networking Client vs server General meaning
⚫ Connecting two or more computing devices together ⚫ Client
to share resources. ⚫ It is a computer or computer program that is make a
⚫ Advantage of Java Networking
request for any services and capable of obtaining
services.
⚫ Sharing resources ⚫ Clients are the ones who request services.
⚫ Centralize software management
⚫ Server
⚫ It is also a computer or computer program which
manages access to a centralized resource .
⚫ That provides the services based on the client request.
⚫ A server is the one who provides requested services.
Example
Example
Types of server •
containing a domain name hostname and responds with the
corresponding IP address.
File server
• Application server • A file server is a computer on a network that is used to provide users on a
• Application oriented request processing(Java ,Php,.NET Framework network with access to files.
application) • Mail server
• Blade server • A remote or central computer that holds electronic mail (e-mail) messages
• one rack mount unit that is capable of holding many different for clients on a network is called a mail server.
servers. • Print server
• Cloud server • Computer or standalone device responsible for managing one or more
printers on a network.
• services provided over a network by a collection of remote servers.
• Proxy server
• Database server • A proxy is a server or program that's part of the gateway or another
• A database server is a computer system that provides other computer that separates a local network from outside networks.
computers with services related to accessing and retrieving data • Standalone server
from a database. • SAS is a server that does not rely on any other servers or services.
• Dedicated server • Web server
• A server that is hosted by a company and only allows one company • Computer or collection of computers used to deliver web pages and other
to lease and access it is called a dedicated server. content to multiple users.
Connection-oriented and
Protocols connection-less protocol
⚫ TCP: Transmission Control Protocol ⚫ In connection-oriented protocol,
⚫ provides reliable communication between the sender ⚫ acknowledgement is sent by the receiver.
and receiver. ⚫ So it is reliable but slow.
⚫ TCP is used along with the Internet Protocol referred as ⚫ The example of connection-oriented protocol is TCP.
TCP/IP. ⚫ connection-less protocol,
⚫ UDP: User Datagram Protocol ⚫ acknowledgement is not sent by the receiver.
⚫ provides a connection-less protocol service by allowing ⚫ So it is not reliable but fast.
packet of data to be transferred along two or more nodes
⚫ The example of connection-less protocol is UDP.
Port Number
Socket class
CLIENT SERVER COMMUNICATION
⚫ A socket is simply an endpoint for communications
between the machines.
⚫ The Socket class can be used to create a socket.
ServerSocket class Creating Server:
⚫ To create the server application,
⚫ The ServerSocket class can be used to create a server
socket. ⚫ Step 1: create the instance of ServerSocket class.
⚫ This object is used to establish communication with ⚫ Step 2: use Port number for the communication between
the clients. the client and server.
⚫ Step 3: use accept() method that’s waits for the client.
⚫ Step 4: If clients connects with the given port number, it
returns an instance of Socket.
1. ServerSocket ss=new ServerSocket(6666);
Note:(6666 –IRC-internet relay chat service)
2. Socket s=ss.accept();
// establishes connection and waits for the client
Creating Client:
writeUTF() and readUTF()
⚫ To create the client application, ⚫ Unicode Translation Format
⚫ create the instance of Socket class. ⚫ The writeUTF() method of the java.io.DataOutputStream
⚫ Here, need to pass the IP address or hostname of the class
⚫ accepts a String value as a parameter and writes it in using
Server and a port number.
modified UTF-8 encoding, to the current output stream.
⚫ Here, we are using "localhost" because our server is ⚫ Therefore to write UTF-8 data to a file
running on same system. ⚫ The readUTF() method of the java.io.DataOutputStream
⚫ Coding: ⚫ reads data that is in modified UTF-8 encoding, into a String
⚫ Socket s=new Socket("localhost",6666); and returns it.
⚫ Therefore to read UTF-8 data to a file
Java InetAddress class
⚫
⚫
Java InetAddress class represents an IP address.
⚫
The java.net.InetAddress class provides methods to get the IP of any host name.
Commonly used methods of Inet Address
⚫
Example
www.google.com, www.facebook.com, etc. class
⚫ An IP address is represented by 32-bit or 128-bit unsigned number.
Method Description
⚫ InetAddress types:
public static InetAddress getByName(String host) it returns the instance of InetAddress containing
⚫
throws UnknownHostException LocalHost IP and name.
Unicast
public static InetAddress getLocalHost() throws it returns the instance of InetAdddress containing local
⚫ Multicast. UnknownHostException host name and address.
⚫
public String getHostName() it returns the host name of the IP address.
The Unicast is an identifier for a single interface whereas Multicast is an identifier
public String getHostAddress() it returns the IP address in string format.
for a set of interfaces.
⚫ InetAddress has a cache mechanism to store successful and unsuccessful host name
resolutions.
•DatagramSocket(int port) throws SocketEeption: it creates a • If you send multiple packet, it may arrive in any order.
datagram socket and binds it with the given Port Number. Additionally, packet delivery is not guaranteed.
JDBC
⚫ JDBC stands for Java Database Connectivity.
⚫ JDBC is a Java API to connect and execute the query ⚫ JDBC API to access tabular data stored in any
with the database. relational database.
⚫ It is a part of JavaSE (Java Standard Edition). ⚫ Using JDBC API, we can save, update, delete and fetch
⚫ JDBC API uses JDBC drivers to connect with the data from the database.
database. ⚫ It is like Open Database Connectivity (ODBC)
⚫ There are four types of JDBC drivers: provided by Microsoft.
⚫ JDBC-ODBC Bridge Driver,
⚫ Native Driver,
⚫ Network Protocol Driver, and
⚫ Thin Driver
JDBC interaction with Database
⚫ The current version of JDBC is 4.3.
⚫ It is the stable release since 21st September, 2017.
⚫ It is based on the X/Open SQL Call Level Interface.
⚫ The java.sql package contains classes and interfaces
for JDBC API.
⚫ Before JDBC, ODBC API was the database API to ⚫ We can use JDBC API to handle database using Java
connect and execute the query with the database. program and can perform the following activities:
⚫ But, ODBC API uses ODBC driver which is written in ⚫ Connect to the database
C language (i.e. platform dependent and unsecured). ⚫ Execute queries and update statements to the database
⚫ That is why Java has defined its own API (JDBC API) ⚫ Retrieve the result received from the database.
that uses JDBC drivers (written in Java language).
Architecture Explanation
⚫ Application:
⚫ It is a java applet or a servlet that communicates with a data
source.
⚫ The JDBC API:
⚫ The JDBC API allows Java programs to execute SQL
statements and retrieve results.
⚫ DriverManager:
⚫ It plays an important role in the JDBC architecture.
⚫ It uses some database-specific drivers to effectively connect
enterprise applications to databases.
⚫ JDBC drivers:
⚫ To communicate with a data source through JDBC.
⚫ JDBC driver that intelligently communicates with the
respective data source.
2) Native-API driver
JDBC-ODBC bridge driver
⚫ The Native API driver uses the client-side libraries of the
database.
⚫ The driver converts JDBC method calls into native calls of
the database API.
⚫ It is not written entirely in java.
⚫ Advantage:
⚫ performance upgraded than JDBC-ODBC bridge driver.
⚫ Disadvantage:
⚫ The Native driver needs to be installed on the each client
machine.
⚫ The Vendor client library needs to be installed on client
machine.
2) Native-API driver Network Protocol driver
⚫ The Network Protocol driver uses middleware (application
server).
⚫ That converts JDBC calls directly or indirectly into the
vendor-specific database protocol.
⚫ It is fully written in java.
⚫ Advantage:
⚫ No client side library is required because of application server
that can perform many tasks like auditing, load balancing,
logging etc.
⚫ Disadvantages:
⚫ Network support is required on client machine.
⚫ Requires database-specific coding to be done in the middle tier.
⚫ Maintenance of Network Protocol driver becomes costly because
it requires database-specific coding to be done in the middle
tier.
Thin driver
Network Protocol driver ⚫ The thin driver converts JDBC calls directly into the
vendor-specific database protocol.
⚫ That is why it is known as thin driver.
⚫ It is fully written in Java language.
⚫ Advantage:
⚫ Better performance than all other drivers.
⚫ No software is required at client side or server side.
⚫ Disadvantage:
⚫ Drivers depend on the Database.
Thin driver Java Database Connectivity 7 Steps
Definition Collection
⚫ Any group of individual objects which are represented ⚫ Java Collection framework provides many interfaces and classes
as a single unit is known as the collection of the ⚫ interfaces
⚫ Set
objects. ⚫ List
⚫ In Java, a separate framework named the “Collection ⚫ Queue
Framework” has been defined in JDK 1.2 which holds ⚫ Deque
all the collection classes and interface in it. ⚫ classes
⚫ ArrayList,
⚫ The Collection interface (java.util.Collection) and ⚫ Vector,
Map interface (java.util.Map) are the two main “root” ⚫ LinkedList,
interfaces of Java collection classes. ⚫ PriorityQueue,
⚫ HashSet,
⚫ LinkedHashSet,
⚫ TreeSet
Hierarchy of Collection Framework
⚫ Iterator interface provides the facility of iterating the ⚫ The Iterable interface is the root interface for all the
elements in a forward direction only.Methods of collection classes.
Iterator interface ⚫ The Collection interface extends the Iterable interface
⚫ There are only three methods in the Iterator interface. and therefore all the subclasses of Collection interface
They are: also implement the Iterable interface.
⚫ It contains only one abstract method. i.e.,
⚫ Iterator<T> iterator()
⚫ It returns the iterator over the elements of type T.
Collection Interface List Interface
⚫ The Collection interface is the interface which is
implemented by all the classes in the collection ⚫ List interface is the child interface of Collection interface.
framework. ⚫ It inhibits a list type data structure in which we can store
⚫ It declares the methods that every collection will have. the ordered collection of objects.
⚫ Collection interface builds the foundation on which ⚫ It can have duplicate values.
the collection framework depends. ⚫ List interface is implemented by the classes ArrayList,
LinkedList, Vector, and Stack.
⚫ Some of the methods of Collection interface are
⚫ To instantiate the List interface, we must use :
⚫ Boolean add ( Object obj), ⚫ List <data-type> list1= new ArrayList();
⚫ Boolean addAll ( Collection c), void clear(), etc. ⚫ List <data-type> list2 = new LinkedList();
⚫ which are implemented by all the subclasses of ⚫ List <data-type> list3 = new Vector();
Collection interface. ⚫ List <data-type> list4 = new Stack();
Class Collections