CS 3391
Object Oriented Programming – III Semester CSE
INTRODUCTION TO OOP & JAVA
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Overview of OOP
▪ Replaced structured or procedural programming.
▪ Java is object oriented.
▪ An OOP program is made of objects.
▪ In traditional, first algorithm is designed then operates on data.
▪ OOP reverses the above: Data first than algorithms to operate on data.
▪ For small problems, the breakdown of procedures works well.
▪ Objects are more appropriate for larger problems.
Example:
- Web browser with 2000 procedures. (Traditional)
- OOP: 100 Classes with 20 methods each; Easy to organize, understand and debug.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Procedural Vs OOP
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
OOPS Concepts
Class:
- Specifies how objects are made.
- All codes are written in class.
Object:
- Instance of a class.
- Class’s data / methods can be accessed by creating an object for the class.
Encapsulation:
- Hiding of code and data from outside interference.
- Also called as “Information hiding”.
Example: Access Specifiers.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
OOPS Concepts (Contd.,)
Abstraction:
- Hiding of unwanted information.
- Implementation details are hidden.
Example: Car
Inheritance:
- Inheritance is the process in which one object acquires the properties of another
object.
Polymorphism:
- One interface multiple methods.
- Means many forms.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Java Buzzwords
Simple:
- Can be learnt without a lot of training.
- Omits very rarely used, confusing concepts of C++.
- No need for pointers, structures, unions, operator overloading, virtual
class… etc.
- Can run standalone on all machines.
- Size is also very small.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Java Buzzwords (Contd.,)
Object Oriented:
Distributed:
- Java applications can open and access objects across the Net via URLs easily.
Robust:
- Reliable in a variety of ways.
- Eliminates the possibility of overwriting memory and corrupting data.
- Detects many problems that other languages show only at runtime.
Secure:
- Enables construction of virus-free and tamper-free systems.
- Untrusted code will be executed in sandbox environment.
- Security model of Java is complex.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Java Buzzwords (Contd.,)
Architecture – Neutral:
- The compiled code executes on any processor.
- Java compiler generates byte code instruction that is not having any similarity with
underlying architecture.
Portable:
Interpreted:
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Java Buzzwords (Contd.,)
High-Performance:
- Just in time (JIT) compiler.
- Improves performance of Java at Runtime.
Multithreaded:
- Concurrent operation.
Dynamic:
- Designed to adapt to any environment.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
What is JDK?
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Basics of JAVA
▪ Highly case sensitive.
▪ Easy to find errors.
▪ No previous skill required.
▪ File name should be the class name.
▪ All program should be written inside the class.
▪ File should be saved using an extension (.java).
▪ Requires JDK (Java Development Kit) for execution.
▪ Recent version of JDK is 22.0.2.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
A Simple Java Program File Name
import java.io.*; //Header File pg1.java
class pg1 // Class Name
{
public static void main(String args[]) // Main Function
javac pg1.java
{
System.out.println(“Welcome”); // Print Statement – S is Caps.
Execute
}
} java pg1
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
public static void main(String args[])
Public:
- It is an Access Modifier, which defines who can access this Method.
- Accessible by any class.
Static:
- It can be accessed without creating the instance of a Class.
Void:
- Void means the Method will not return any value.
Main:
- Main method.
String args[]:
- Command line arguments.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Datatypes
▪ Java is a strongly typed language.
▪ 8 datatypes.
▪ Integer – 4
▪ Floating point – 2
▪ Character – 1
▪ Boolean - 1
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Integer Datatype
▪ Numbers without fractional part.
▪ Can include negative numbers !
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Integer Datatype (Contd.,)
▪ Mostly “int” will be used.
▪ long (For very high numbers: number of inhabitants in the planet).
▪ byte and short for special purposes.
▪ Long integers have suffix L or l (for example, 4000000000L)
▪ Hexa-decimal have a prefix 0x or 0X (for example, 0xCAFE).
▪ Octal numbers have a prefix 0. (for example, 010 is 8)
▪ After Java 7, underscores can be added to number literals such as 1_000_000 (To denote 1
million).
▪ Underscores are only for human eyes. (Will be ignored)
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Floating point types
▪ Denotes numbers with fractional parts.
▪ double has twice the precision of floating type.
▪ Numbers of float have a suffix F or f. (for example, 3.14F).
▪ Floating point without suffix are treated as double.
▪ You can optionally supply the D or d suffix. (for example, 3.14D).
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Floating point types (Contd.,)
Three special floating point values to denote overflows and errors.
1. Positive infinity.
2. Negative infinity.
3. NaN (not a number).
➢Result of dividing a positive number by 0 -> Positive infinity.
➢Computing 0/0 or the square root of negative number yields NaN.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
The char type
▪ To describe individual characters.
▪ Values of type char are enclosed in single quotes (‘ ‘).
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
The boolean type
▪ The boolean type has only two values.
▪ 1. True
▪ 2. False
▪ Used for evaluating logical conditions.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Declaring Variables
▪ Every variable has a type.
▪ Declare a variable by placing the type first, followed by the name of the variable.
Examples:
▪ double salary;
▪ int vacationDays;
▪ long earthPopulation;
▪ boolean done;
➢ Semicolon is essential.
➢ Multiple declarations can be done in a single line.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Constants
▪ final keyword for denoting a constant.
▪ Assign variable once, it will not change.
// final double CM_PER_INCH = 2.54;
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Increment / Decrement Operators
▪ int m = 7;
▪ int n = 7;
▪ int a = 2 * ++m; // now a is 16, m is 8
▪ int b = 2 * n++; // now b is 14, n is 8
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Getting Input
Using Scanner Class:
- Scanner in = new Scanner(System.in);
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Object Creation
▪ classname objectname = new classname();
Can be accessed by:
- objectname.method();
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Combining Assignments with Operators
For example,
▪ x += 4;
is equivalent to
▪ x = x + 4;
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Conditional Operator
Condition ? Expression 1: Expression 2
Example:
X<Y ? X : Y
//PROGRAM
a=in.nextInt();
b=in.nextInt();
C=a<b?a:b; 5<10?5:10
System.out.println("C = " + c);
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Strings
▪ String e = ""; // an empty string
▪ String greeting = "Hello";
Substring:
▪ String greeting = "Hello";
▪ String s = greeting.substring(0, 3);
▪ The string s.substring(a, b) always has length b − a.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
String Concatenation
String expletive = "Expletive";
String PG13 = "deleted";
String message = expletive + PG13;
▪ The preceding code sets the variable message to the string "Expletivedeleted".
▪ The + operator joins two strings.
int age = 13;
String rating = "PG" + age;
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Testing strings for equality
s.equals(t) // Returns true if equals.
"Hello".equals(greeting) // Legal
"Hello".equalsIgnoreCase("hello") // To ignore cases
str.length(); // To find the length
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Control Statements
if Loop:
if (condition) { // block of code to be executed if the condition is true }
if-else Statement:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Control Statements (Contd.,)
if-else-if ladder Statement
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Control Statements (Contd.,)
Do While Loop:
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Control Statements (Contd.,)
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Control Statements (Contd.,)
For Loop:
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Arrays
int[] a = new int[10];
▪ This statement declares and initializes an array of 100 integers.
▪ The array length need not be a constant: new int[n] creates an array of length n.
▪ Once you create an array, you cannot change its length.
Shortcut for creating an array object and supplying initial values:
int[] smallPrimes = { 2, 3, 5, 7, 11, 13 };
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Arrays (Contd.,)
String[] authors = {
"James Gosling",
"Bill Joy",
"Guy Steele",
// add more names here and put a comma after each name
};
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Constructors
▪ A constructor in Java is a special method that is used to initialize objects.
▪ The constructor is called when an object of a class is created.
▪ It can be used to set initial values for object attributes.
▪ Note: It is not necessary to write a constructor for a class. It is because
java compiler creates a default constructor if your class doesn’t have any.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Constructors Vs Methods
• Constructors must have the same name as the class within which it is defined while it
is not necessary for the method in Java.
• Constructors do not return any type while method(s) have the return type or void if
does not return any value.
• Constructors are called only once at the time of Object creation while method(s) can
be called any number of times.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Types of Constructors
▪ Default Constructor
▪ Parameterized Constructor
Syntax:
classname()
{
//statements
}
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Jump Statements
Break Statement:
- Transfer control to another part of the program.
- You can force immediate termination of a loop.
- When encountered inside a loop, the loop is terminated and
program control resumes at the next statement following the loop.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Jump Statements (Contd.,)
Continue Statement:
- The continue statement is used in loop control structure when you need to jump to the
next iteration of the loop immediately.
- The Java continue statement is used to continue the loop.
- It continues the current flow of the program and skips the remaining code at the
specified condition.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Switch Statement
▪The Java switch statement executes one statement from multiple conditions.
Syntax:
switch(expression) {
case value1:
//code
break; //optional
case value2:
//code
break; //optional
default:
//code that will execute if all does not match
}
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Access Modifiers
▪ There are 4 types of access variables in Java:
1.Private
2.Public
3.Default
4.Protected
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Access Modifiers (Contd.,)
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Method Overloading
▪ Same function name with different number / type of parameters.
Two Ways:
- Change number of arguments.
- Change data types of arguments.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Inheritance in Java
• Class: A class is a group of objects which have common properties. It is a template
or blueprint from which objects are created.
• Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
• Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
• Reusability: As the name specifies, reusability is a mechanism which facilitates you
to reuse the fields and methods of the existing class when you create a new class.
You can use the same fields and methods already defined in the previous class.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Syntax (Inheritance)
class Subclass-name extends Superclass-name
{
//methods and fields
}
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Types of Inheritance
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Types (Contd.,)
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Why multiple inheritance not supported in Java?
▪ Consider a scenario where A, B, and C are three classes.
▪ The C class inherits A and B classes.
▪ If A and B classes have the same method and you call it from child class
object, there will be ambiguity to call the method of A or B class.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Super Keyword
▪ The super keyword in Java is a reference variable which is used to
refer immediate parent class object.
▪ Whenever you create the instance of subclass, an instance of
parent class is created implicitly which is referred by super
reference variable.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Super Keyword (Contd.,)
Usage of Java super Keyword
1.super can be used to refer immediate parent class instance
variable.
2.super can be used to invoke immediate parent class method.
3.super() can be used to invoke immediate parent class constructor.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Refer immediate parent class instance variable
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
To invoke parent class method
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.eat();
d.work();
}}
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
To invoke parent class constructor.
class Animal{
Animal(){
System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Method Overriding
▪ Same method is defined in both the superclass and the subclass.
▪ The method of the subclass class overrides the method of the
superclass.
▪ This is known as method overriding.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Overriding Rules
▪ Both the superclass and the subclass must have the same method
name, the same return type and the same parameter list.
▪ We cannot override the method declared as final and static.
▪ We should always override abstract methods of the superclass.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Method Overriding (Contd.,)
class Animal {
public void displayInfo() {
System.out.println("I am an animal.");
}
}
class Dog extends Animal {
@Override
public void displayInfo() {
System.out.println("I am a dog.");
}
}
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Super keyword in Java Overriding
class Animal {
public void displayInfo() {
System.out.println("I am an animal.");
}
}
class Dog extends Animal {
public void displayInfo() {
super.displayInfo();
System.out.println("I am a dog.");
}
}
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Dynamic method dispatch
▪ Dynamic method dispatch is the mechanism in which a call to an overridden method
is resolved at run time instead of compile time.
▪ This is an important concept because of how Java implements run-time
polymorphism.
▪ Java uses the principle of ‘a superclass reference variable can refer to a subclass
object’ to resolve calls to overridden methods at run time.
▪ When a superclass reference is used to call an overridden method, Java determines
which version of the method to execute based on the type of the object being
referred to at the time call.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Advantages of Dynamic method dispatch
▪ It allows Java to support overriding of methods, which are
important for run-time polymorphism.
▪ It allows subclasses to incorporate their own methods and define their
implementation.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Abstract Class in Java
▪ A class which is declared with the abstract keyword is known as an abstract class
in Java.
▪ It can have abstract and non-abstract methods (method with the body).
Points to Remember
• An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
• It can have final methods which will force the subclass not to change the body of
the method.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Final Keyword in Java
The final keyword in java is used to restrict the user. Final can be:
1.variable
2.method
3.class
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Final Variable
▪ If you make any variable as final, you cannot change the value of final variable (It will be
constant).
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Final Method
▪ If you make any method as final, you cannot override it.
class Bike
{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Final Class
▪ If you make any class as final, you cannot extend it.
final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
}
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Abstraction
▪ Process of hiding certain details and showing only essential information.
▪ Can be achieved using either abstract classes / interfaces.
▪ Abstract keyword is used for classes and methods.
• Abstract class: is a restricted class that cannot be used to create objects
(to access it, it must be inherited from another class).
• 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).
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Abstraction (Continued)
▪ An abstract class can have both abstract and regular methods:
abstract class Animal //Cannot create object.
{
public abstract void disp(); //Abstract method
public void f1()
{
System.out.println(“Wild Animals");
}
}
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Abstraction (Continued)
▪ Animal myObj = new Animal(); // will generate an error
▪ All abstract methods present in abstract class must be
overridden.
▪ Abstract class may or may not contain abstract methods.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Interface
▪ 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.
▪ There can be only abstract methods in the Java interface, not method
body.
▪ An interface is declared by using the interface keyword.
▪ It provides total abstraction.
▪ A class that implements an interface must implement all the methods
declared in the interface.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Interface (Contd.,)
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Interface (Contd.,)
class childclass implements interface1, interface2..
{
// override all methods declared in interface.
}
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Relationship between classes and interfaces
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Arrays
▪ Arrays are used to store multiple values in a single variable,
instead of declaring separate variables for each value.
▪ Array elements are stored and accessed using an index number.
▪ To declare an array, define the variable type with square brackets:
int[ ] a = new int[10]; // Integer Array
String[ ] b = new String[10]; // String Array
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Arrays (Continued)
Length of Array: length method
Example:
int[] a=new int[10];
int c;
c=a.length; //10
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Arrays (Continued)
Direct Initialization of Arrays with Values:
int[ ] d={10,20};
String[ ] e={"Hai", "Hello"};
Accessing an Array Value: d[0] & e[1]
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Arrays (Continued)
String[ ] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++)
{
System.out.println(cars[i]);
}
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Array Copying
▪ Copy one array variable to another.
Example:
int[ ] a = new int[10];
int[ ] b = new int[10];
a=b;
a[0]=2;
System.out.println(“Value = ” + b[0]); // Value = 2
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Array Copying (Contd.,) int[ ] a = new int[10];
int[ ] b = new int[10];
▪ Using a function “Arrays.copyOf”
a=Arrays.copyOf(b,b.length);
▪ Header file import java.util.Arrays;
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Array Sorting
▪ To sort elements in an array “Arrays.sort(arrayvariable)” function
can be used. (tuned method of quick sort algorithm)
▪ Header file “import java.util.Arrays;”
Example:
Arrays.sort(result); // Sorts array elements
for (int r : result) // Enhanced for loop
System.out.println(r);
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Arrays (Continued)
▪ A multidimensional array is an array of arrays.
▪ Multidimensional arrays are useful when you want to store data
as a tabular form, like a table with rows and columns.
Syntax:
datatype[ ][ ] arrayname = new datatype[rows][columns];
For example: int[ ][ ] arr = new int[10][20];
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Arrays (Continued)
▪ Java has no multidimensional arrays !
▪ Only one dimensional arrays.
▪ Multidimensional arrays are faked as “arrays of arrays”.
▪ Ragged Arrays.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Arrays (Continued)
int[ ][ ] a = new int[3][4];
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Arrays (Continued)
int[ ][ ] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Accessing Array Elements
int[ ][ ] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
System.out.println(myNumbers[1][2]); // Outputs 7
int[ ][ ] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
myNumbers[1][2] = 9;
System.out.println(myNumbers[1][2]); // Outputs 9 instead of 7
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Programs
- Read and print sum of ‘n’ numbers.
- Biggest / Smallest among ‘n’ numbers.
- Arrange ‘n’ numbers in ascending / descending order.
- Matrix addition & Matrix Multiplication
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
JavaDoc Comments
▪ Professional way of writing comments.
▪ Follows certain syntax for writing comments.
The javadoc utility extracts information for the following items:
➢Modules
➢Packages
➢Public classes and interfaces
➢Public and protected fields
➢Public and protected constructors and methods
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Rules for JavaDoc Comments
▪ Each comment is immediately placed above the feature it describes.
▪ A comment starts with /** and ends with */
▪ Contains free form of text between /** …. */ followed by tags.
▪ A tag starts with “@” like, @since or @param.
▪ First sentence of the free form text should be a summary statement.
▪ Javadoc utility extracts this statement.
▪ HTML tags can be used in the free-form of text like, <em> … </em>,
<strong>…</strong> etc.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Class Comments
▪ Placed after import statement
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Class Comments
▪ No need to add star * for each line.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Method Comments
▪ All comments should precede the method.
@param variable description
This tag adds an entry to the “parameters” section of the current method.
@return description
This tag adds a “returns” section to the current method
@throws class description
This tag adds a note that this method may throw an exception.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Method Comments (Continued)
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Field Comments
▪ Only public fields with static constants
/**
* The "Hearts" card suit
*/
public static final int HEARTS = 1;
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
General Comments
▪ @since text (@since 1980)
▪ @author name
▪ @version text
Comment Extraction:
javadoc –d directoryname *.java
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
I/O Classes
▪ Print and Println are the mostly used I/O statements.
▪ Apart from the above more I/O statements are there!
▪ Most real-time applications are based on GUI, AWT, JAVAFX
and Web applications.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
I/O Basics (Contd.,)
▪ Java performs I/O through streams.
▪ Stream is an abstraction that produces or consumes information.
▪ A stream is linked to a physical system by the Java I/O System.
▪ Same I/O classes and methods can be applied to different types of devices.
▪ Input stream can abstract different kinds of input – from file, keyboard or network
socket.
▪ Same for output stream.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
I/O Basics (Contd.,)
Byte Streams:
- Handling input and output of bytes.
- For reading and writing binary data.
Character Streams:
- For handling input and output of characters.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
I/O Basics (Contd.,)
The Byte Stream Classes:
- 2 classes: InputStream and OutputStream
- The above two defines several key methods.
- Two most important are read() and write() – Read and Write
bytes of data.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
I/O Basics (Contd.,)
The Character Stream Classes:
- 2 Classes: Reader and Writer
- Handles Unicode character streams.
- Reader and Writer defines several key methods and the
most important are read() and write().
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
The Predefined Streams
▪ System contains 3 predefined stream variables: in, out and err.
▪ These fields are declared as public, static and final within the system.
▪ Can be used in any part of the program without creating a reference to the specific system
object.
▪ System.out: Refers to standard output stream. (Console – Default).
▪ System.in: Refers to standard input stream. (Keyboard – Default).
▪ System.in – Object of type InputStream.
▪ System.out and System.err – Object of type PrintStream.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Reading Console Input
▪ Earlier byte stream used for reading input from console.
▪ But after that for commercial applications – character-oriented stream is used.
▪ Character-oriented stream is easy to maintain.
For this:
- Reading from System.in.
- Wrap System.in in a BufferedReader Object. BufferedReader(Reader inputReader)
- Use InputStreamReader – Converts bytes to characters.
- BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Reading Characters
▪ To read characters, BufferedReader uses read() method.
▪ Each time read() is called it will return an integer.
▪ It returns -1 if it reaches the end of stream and throws
IOException.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Writing Console Output
▪ Most easily accomplished using print() and println().
▪ These methods are defined by the class PrintStream().
▪ PrintStream is an Output stream derived from OutputStream, it implements
a low-level method called write().
▪ Write() can be used to write to the console.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Writing Console to Output:
Write Method: - Special handling of stream of bytes
Two types of syntax
1.write(int b)
2.write(byte [] b, int off, int len)
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Reading Files
▪ FileInputStream and FileOutputStream are used.
▪ To read a file, read() method is used.
▪ read() returns a integer value and if it returns -1, which means an
attempt is made to read the end of file.
▪ Similarly, for writing to a file, write() is used.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Packages
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Static Keyword
static keyword
• In order to share the same method or variable of any given class, we use
the static keyword.
• We can use it for blocks, variables, methods, and nested classes.
Static variable
• A static variable is nothing but the class variable.
• It is common for all objects of a class, or let’s say it is shared by all
objects of a class, whereas the non-static variable is different for each
object of a class.
• E.g., static String name=“Sample”;
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Static Keyword (Continued)
Static block
• To initialize static variables, we use a static block.
• It gets executed only once after class is loaded or an object is created.
• A class can contain multiple static blocks.
• E.g. – static String name;
static
{
name = “Java”;
}
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Static Keyword (Continued)
Static method
• A static method is one that can be invoked without creating object of a class.
• It can access static variables without using the object of the class.
• It can access static and non-static methods directly.
• Eg – public static void main(String args[])
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Static Keyword (Continued)
• Static class
• We can declare a class as static only if it is a nested class.
• Non-static members of the Outer class are not accessible by
the static class.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Static Program
import java.io.*;
class sample
{
static int a; // static variable
static { // static block
a=10;
}
static void f1() { // static method
a++;
System.out.println("Welcome = " + a);
} }
class statmain
{
public static void main(String args[]) {
sample ob1=new sample();
ob1.f1();
sample ob2=new sample();
ob2.f1();
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
}}
Packages
▪ A package in Java is used to group related classes.
▪ Similar to a folder / directory.
2 Categories:
- Built-in packages.
- User defined packages.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Packages (Continued)
▪ Include the below statement before the start of class inside the package
package packagename;
- Import the created package using the below statement
import packagename.*;
- Package should be created using “public” access specifier.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Access modifiers in JAVA
▪ Restricts the scope of a class.
Types of Access Modifiers:
- Default (No keyword required)
- Private
- Protected
- Public
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Default Access Modifier
▪ When no modifier is specified for class, method or data
member then it is said to have default access modifier by
default.
▪ Default access modifiers are accessible only within the
same package.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Private Access Modifier
- The private access modifier is specified using the keyword private.
- The methods or data members declared as private are accessible
only within the class in which they are declared.
• Any other class of the same package will not be able to access these
members.
▪ private means “only visible within the enclosing class”.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Protected Access Modifiers
▪ The protected access modifier is specified using the
keyword protected.
▪ The methods or data members declared as protected
are accessible within the same package or subclasses in
different packages.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Strings (String, StringBuffer, StringBuilder)
▪ Collection of characters.
Substring:
▪ String greeting = "Hello";
▪ String s = greeting.substring(0, 3);
Concatenation:
▪ String expletive = "Expletive";
▪ String PG13 = "deleted";
▪ String message = expletive + PG13;
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Strings (Contd.,)
Equality:
- s.equals(t) // To test two strings are equal or not (Returns Boolean)
- "Hello".equals(greeting) // Another option
- "Hello".equalsIgnoreCase("hello")
String Length:
▪ String greeting = "Hello";
▪ int n = greeting.length(); // is 5
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Strings (Contd.,)
replace:
- String replace(char original, char replacement)
trim:
- Removes leading and trailing spaces.
Changing Cases:
- toLowerCase( ) and toUpperCase( )
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Strings (Contd.,)
charAt():
▪ char first = greeting.charAt(0); // first is 'H'
▪ char last = greeting.charAt(4); // last is ‘o ‘
StringBuilder Class:
- To build strings from many small pieces.
- Create an object for the class “StringBuilder”.
- StringBuilder ob=new StringBuilder();
- ob.append(ch); // appends a single character.
- ob.append(str); // appends a string.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Strings (Contd.,)
- Call “toString” method.
- String finalstr=ob.toString(); // Prints the entire string in ob.
Joining Strings:
- join(CharSequence delim, CharSequence . . . strs)
- String.join(“ “, “Welcome”,”Java”);
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
StringBuffer
▪ Supports modifiable string.
▪ String represent fixed-length.
▪ StringBuffer represents growable and writable character
sequences.
▪ StringBuffer will automatically grow to make room for such addition.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
String Buffer (Contd).,
Four Constructors:
- StringBuffer() – Reserves space for 16 Characters
- StringBuffer(int size)
- StringBuffer(String str) – str + Add 16 Char
- StringBuffer(CharSequences chars) – Chars + Add 16 Char
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
String Buffer (Contd.,)
▪ Length Method – length()
▪ Capacity Method – capacity()
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Example
import java.io.*;
class strbuff
{
public static void main(String agrs[])
{
StringBuffer sb=new StringBuffer("Hello");
System.out.println("Buffer = " + sb);
System.out.println("Length = " + sb.length());
System.out.println("Capacity = " + sb.capacity());
}
}
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
String Buffer (Contd.,)
ensureCapacity:
- To preallocate room for a certain number of characters after a
StringBuffer has been constructed, you can use ensureCapacity( ) to set
the size of the buffer.
▪ void ensureCapacity(int minCapacity)
▪ minCapacity specifies the minimum size of the buffer.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
String Buffer (Contd.,)
setLength():
▪ To set the length of the string within a StringBuffer object, use
setLength( ).
▪ void setLength(int len)
▪ Here, len specifies the length of the string. Value should be
non-negative.
▪ The characters stored beyond the new length will be lost.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
charAt() and setCharAt()
▪ The value of a single character can be obtained from a StringBuffer via the
charAt( ) method.
▪ You can set the value of a character within a StringBuffer using setCharAt( ).
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
append ()
▪ The append( ) method concatenates the string representation of any other
type of data to the end of the invoking StringBuffer object.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
insert ()
▪ The insert( ) method inserts one string into another.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
reverse ()
▪ You can reverse the characters within a StringBuffer object using reverse( )
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
delete () and deleteCharAt()
▪ The delete( ) method deletes a sequence of characters from
the invoking object
▪ The deleteCharAt( ) method deletes the character at the
index specified by loc.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Program
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
replace ()
▪ You can replace one set of characters with another set inside a
StringBuffer object by calling replace( ).
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Exception Handling and Multithreading
Exception:
- Unexpected Situation. (Abnormal Condition)
- To be handled gracefully.
Exception Handling:
- Powerful mechanism to handle runtime errors.
- To maintain the normal flow of the application.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Public Access Modifier
▪ The public access modifier is specified using the keyword public.
• The public access modifier has the widest scope among all other
access modifiers.
▪ Classes, methods, or data members that are declared as public
are accessible from everywhere in the program. There is no restriction
on the scope of public data members.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Advantage of Exception Handling
▪ To maintain normal flow of the
application.
▪ An exception disrupts the normal flow
of application.
Example: ->
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Hierarchy of Java Exception Classes
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Types of Exceptions
1.Checked Exception – IOException, SQLException..
2.Unchecked Exception – Arithmetic, Nullpointer…
3.Error – Out of memory ….
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Java Exception Keywords
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Multiple Catch Statements
▪ A try block can be followed by one or more catch blocks.
▪ Each catch block must contain a different exception handler.
▪ To perform different tasks at the occurrence of different exceptions, use java multi-
catch block.
To Remember:
▪ At a time only one exception occurs and at a time only one catch block is executed.
▪ All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Contd.,
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Java Nested Try Block
▪ A try block inside another try block is permitted.
▪ It is called as nested try block.
▪ Example: the inner try block can be used to
handle ArrayIndexOutOfBoundsException while the outer try
block can handle the ArithemeticException (division by zero).
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Syntax
//main try block
try
{
statement 1;
statement 2;
//try catch block within another try block
try
{
statement 3;
statement 4;
//try catch block within nested try block
try
{
statement 5;
statement 6;
}
catch(Exception e2)
{
//exception message
}
}
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Contd.,
▪ When any try block does not have a catch block for a
particular exception, then the catch block of the outer
(parent) try block are checked for that exception, and if it
matches, the catch block of outer try block is executed.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Java User Defined Exception
▪ We can create our exception.
▪ Derived from “Exception” class.
▪ We can have your own exception and message.
▪ Exception class can be obtained using getMessage() method
on the object we have created.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Why use custom exceptions?
• To catch and provide specific treatment to a subset of
existing Java exceptions.
▪ Business logic exceptions: These are the exceptions related
to business logic and workflow.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Multithreading
▪ Process is divided into two or more subprograms.
▪ A thread is a small piece of execution.
▪ A unique property of java is multithreading.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Multithreaded Program
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Creating Threads
▪ Simple task.
▪ Implemented in the form of objects that contain a method called as
run().
▪ The run() method is the main part of thread.
▪ In run() method the thread behavior is implemented.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Thread creation – 2 Ways
Creating a thread class:
- Define a class that extends “Thread” class and override its
run() method.
Converting a class into thread:
- Define a class that implements “runnable” interface and
implement run() method.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Extending Thread Class
▪ Declare the class and extend Thread class.
▪ Implement run() method and write required coding.
▪ Create a thread object and call the start() method to
initiate the thread execution.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Declaring thread class
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Implementing run () method
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Starting a new thread
Mythread ob= new Mythread();
ob.start();
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Blocking a thread
Thread can be temporarily suspended / blocked using
▪ sleep() // blocked for a specific time
▪ suspend() //blocked until further orders “resume()”
▪ wait() //blocked until certain condition occurs “notify()”
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Stopping a Thread
▪To stop a thread from running further.
▪Stop() method is used.
▪Artificial Death.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Lifecycle of a thread
States of a thread:
- Newborn
- Runnable
- Running
- Blocked
- Dead
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
State transition diagram of a thread
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Newborn State
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Runnable State
▪ Thread is ready for execution and it is waiting for the
availability of processor.
▪ Thread joins the queue of thread for execution.
▪ It can relinquish its control to another thread using yield().
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Running State
▪ Processor has given time for the thread to execute.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Contd.,
▪ Blocked State – prevented from entering into runnable
and running.
▪ Dead State – Natural Death / Artificial Death
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Thread Priority
▪ Each thread is assigned a priority which affects the order in which
it is scheduled for running.
▪ Priority can be assigned using “setPriority(int number)”.
Priority:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Synchronization in Java
▪ Controlling access of multiple threads to a shared
resource.
Why Synchronization?
- What problem will arise?
- Allows only one thread to access the shared resource.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
GENERICS, STRING HANDLING
▪ Print and Println are the mostly used I/O statements.
▪ Apart from the above more I/O statements are there!
▪ Most real-time applications are based on GUI, AWT, JAVAFX
and Web applications.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
I/O Basics (Contd.,)
▪ Java performs I/O through streams.
▪ Stream is an abstraction that produces or consumes information.
▪ A stream is linked to a physical system by the Java I/O System.
▪ Same I/O classes and methods can be applied to different types of devices.
▪ Input stream can abstract different kinds of input – from file, keyboard or network
socket.
▪ Same for output stream.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
I/O Basics (Contd.,)
Byte Streams:
- Handling input and output of bytes.
- For reading and writing binary data.
Character Streams:
- For handling input and output of characters.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
I/O Basics (Contd.,)
The Byte Stream Classes:
- 2 classes: InputStream and OutputStream
- The above two defines several key methods.
- Two most important are read() and write() – Read and Write
bytes of data.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
I/O Basics (Contd.,)
The Character Stream Classes:
- 2 Classes: Reader and Writer
- Handles Unicode character streams.
- Reader and Writer defines several key methods and the
most important are read() and write().
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
The Predefined Streams
▪ System contains 3 predefined stream variables: in, out and err.
▪ These fields are declared as public, static and final within the system.
▪ Can be used in any part of the program without creating a reference to the specific system
object.
▪ System.out: Refers to standard output stream. (Console – Default).
▪ System.in: Refers to standard input stream. (Keyboard – Default).
▪ System.in – Object of type InputStream.
▪ System.out and System.err – Object of type PrintStream.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Reading Console Input
▪ Earlier byte stream used for reading input from console.
▪ But after that for commercial applications – character-oriented stream is used.
▪ Character-oriented stream is easy to maintain.
For this:
- Reading from System.in.
- Wrap System.in in a BufferedReader Object. BufferedReader(Reader inputReader)
- Use InputStreamReader – Converts bytes to characters.
- BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Reading Characters
▪ To read characters, BufferedReader uses read() method.
▪ Each time read() is called it will return an integer.
▪ It returns -1 if it reaches the end of stream and throws
IOException.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Reading Strings
▪ To read a string from keyboard use readLine() – a member of
BufferedReader class.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Writing Console Output
▪ Most easily accomplished using print() and println().
▪ These methods are defined by the class PrintStream().
▪ PrintStream is an Output stream derived from OutputStream, it implements
a low-level method called write().
▪ Write() can be used to write to the console.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Writing Console to Output:
Write Method: - Special handling of stream of bytes
Two types of syntax
1.write(int b)
2.write(byte [] b, int off, int len)
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Reading Files
▪ FileInputStream and FileOutputStream are used.
▪ To read a file, read() method is used.
▪ read() returns a integer value and if it returns -1, which means an
attempt is made to read the end of file.
▪ Similarly, for writing to a file, write() is used.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Generic Programming
▪ Generics means parameterized types.
▪ Type of data is specified as parameter.
▪ A class, interface or method that operates on parameterized type
is called as generic – A generic class or generic method.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Bounded Types
▪ To restrict type parameter to be subtypes of particular class.
▪ If a class is specified using bounded parameter then, only
subtypes of that particular class are accepted by generic
class.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Strings
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Contd.,
String Length:
s.length();
String Concatenation:
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Contd.,
String Concatenation with Other Types:
toString() Method:
public String toString()
{
return “welcome”;
}
charAt();
String s=“Hai”;
System.out.println(s.charAt(1));
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Contd.,
getChars():
- Copy from one source to another.
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
equals and equalsIgnoreCase():
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Contd.,
equals() versus ==:
indexOf(‘c’) & lastIndexOf(‘t’):
substring(int startIndex, int endIndex);
concat():
String s1 = "one";
String s2 = s1.concat("two");
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Contd.,
Searching Strings:
- int indexOf(int ch) // To search the first occurrence of a character
- int lastIndexOf(int ch) // To search for the last occurrence of a character.
- int indexOf(int ch, int startIndex) // Specify a starting point for search
- int lastIndexOf(int ch, int startIndex) // Specify starting point to search from last to zero.
- int indexOf(String str, int startIndex)
- int lastIndexOf(String str, int startIndex)
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Modifying a String
▪ To extract a substring from a string
- String substring(int startIndex) // Where the substring will begin
- String substring(int startIndex, int endIndex) // Range of substring extraction
Example: str.substring(0,4);
Concat:
To concatenate two strings using concat.
String concat(String str).
Example:
S1.concat(s2);
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Contd.,
Replace a string:
String s = "Hello".replace('l', 'w’);
String replace(CharSequence original, CharSequence replacement)
trim( ) and strip( ) (From Java 11)
▪ The trim( ) method returns a copy of the invoking string from which any leading and trailing spaces
have been removed.
Changing Cases:
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
String Buffer
▪ Supports modifiable string.
▪ String represents fixed length.
▪ StringBuffer represents growable and writable character sequences.
▪ StringBuffer will automatically grow to make room for such additions.
Contructors:
StringBuffer()
StringBuffer(int size)
StringBuffer(String str)
StringBuffer(CharSequence char
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
String Buffer (Contd.,)
buffer = Hello
length = 5
capacity = 21
Its capacity is 21 because room for 16 additional characters is automatically added.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
String Buffer (Contd.,)
ensureCapacity():
- To preallocate room for certain number of characters after a StringBuffer has been
constructed, you can use ensureCapacity() to set the size of buffer.
setLength():
- If you call setLength( ) with a value less than the current value returned by length( ),
then the characters stored beyond the new length will be lost.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
String Buffer (Contd.,)
charAt( ) and setCharAt( ):
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
StringBuffer (Contd.,)
getChars( ):
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
append( ):
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
StringBuffer (Contd.,)
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
StringBuffer (Contd.,)
reverse( ):
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
StringBuffer(Contd.,)
delete( ) and deleteCharAt( )
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
StringBuffer(Contd.,)
replace( ):
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
UNIT V – JAVAX EVENT HANDLING, CONTROLS AND
COMPONENTS
▪ A top level window (window contained inside another window is called as frame).
▪ Swing version is called JFrame and extends Frame class.
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering
Adding Component to the Frame
Dr.P.Dinesh Kumar, AP/Sri Eshwar College of Engineering