0% found this document useful (0 votes)
69 views

JAVA (III Sem) Total Notes

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

JAVA (III Sem) Total Notes

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

III Semester

Object Oriented Programming using Java


Unit I:
What is OOP? Discuss OOP Concepts? (Features/Principles of OOP)
Object Oriented Programming (OOP) approach is a Programming methodology to design computer
programs using Classes and Objects.
There are many concepts related to OOP are:
1. Class
2. Object
3. Inheritance
4. Polymorphism
5. Encapsulation
6. Data Abstraction

1) Class: Class is an encapsulation of data and coding. Classes are expended version of structure.
2) Object: class is a user- defined data type and object is a variable of class type. An object is used to
access class members.
3) Inheritance: Inheritance means access the properties and features of one class to another class. Code
reusability is the main advantage of Inheritance.
4) Polymorphism: ‘Poly’ means ‘many’ and ‘morphos’ meaning ‘forms’. Polymorphism means more than
one function with same name with different working. It can be static or dynamic is the compile time and
run time polymorphism.
5) Encapsulation: The Wrapping up of data and method into a single unit (called class) is known as
Encapsulation. The data is not accessible to the outside class and only those methods.
6) Data Abstraction: The basic idea of data abstraction is to visible only the necessary information,
unnecessary information will be hidden from the outside world.
Advantages of OOP:
1. Reusability of code
2. Easily discover a bug
3. Easier troubleshooting
4. Effective and better problem solving
5. Encapsulation
6. Code organization and maintenance
 POP Vs OOP (Difference between POP and OOP)
POP OOP
1. POP means Procedure Oriented Programming 1. OOP means Object Oriented Programming.
2. In POP, the program is divided into small 2. In POP, the program is divided into parts
parts called functions called objects.
3. In POP, Importance is not given to data but to 3. In OOP, Importance is given to the data rather
functions. than procedures or functions.
4. POP follows a Top-Down approach 4. OOP follows the Bottom-Up approach.
5. To add new data and function in POP is not so 5. OOP provides an easy way to add new data
easy. and function.
6. In POP, Overloading is not possible 6. In OOP, Overloading is Possible.
Ex: C, VB, Fortran, Pascal etc. Ex: C++, JAVA, VB.NET, C#.NET
 What is Java? Write Java Features.
Java is a general purpose object- oriented programming language developed by Sun Micro System of
U.S.A in 1991. Originally it is called OAK by James Gosling. In 1995 Oak was renamed “Java” and Sun Micro
System released Java Development Kit (JDK) 1.0 in 1996.

Features of JAVA:
The various features of java as follows,
1. Simple and small
2. Object-Oriented
3. Platform independent
4. Robust and Secure
5. Distributed
6. Compiled and Interpreted
7. High Performance
8. Multi Threaded
9. Scalability
10. Dynamic

1. Simple and Small: Java is Small and simple language. Many features of C and C++ are maintained in Java
either directly or indirectly.
2. Object-oriented: Java is an Object- oriented Programming Language. This means Java program use
Objects and classes. Almost everything in Java is an Object. Thus Java is called true object oriented
programming language.
3. Platform independent: The java programs can be easily moved from one system to another, means write
once run anywhere (WORA). Thus Java is made platform independent.
4. Robust and Secure: Java has got inbuilt exception handling feature. Thus Java is Robust Language.
Security problems like tampering and virus threats can be eliminated or minimized by using Java on
Internet.
5. Distributed: Using Java, we can distribute the programs on various computers on a network.
6. Complied and Interpreted: Java uses both compiler and Interpreter. First, Compiler translates source code
into byte code and second interpreter generates machine code to running the java program.
7. High performance: In JVM, both interpreter and JIT (Just In Time) compiler work together to run the
program, to enhance the speed of execution.
8. Multithreaded: A thread represents a process executed by JVM. Creating multiple threads is called Multi-
threading.
9. Scalability: Java platform can be implemented from embedded devices to mainframe computers. This is
possible because java is platform independent.
10. Dynamic: The dynamic content to be displayed in the browser was done using an applet program.
 Write about basic (general) java program Structure?
Java program may contain one or more sections as follows.

Documentation Section Suggested

Package Statement Optional

Import Statements Optional

Interface Statements Optional

Class Definition Optional


Main method class
{
Main method definition Essential
}

1. Documentation Section: The documentation Section comprises a set of comment lines.


Usually the comment start with ‘//’ for each line and also use in between off /*……..*/
Type 1:
Syntax: // comment Line
Eg: //Write a program on class and object in java
Type 2:
/* ……… comment Line 1 ………….*/
Eg: /* write a java to perform various string operations */
2. Package Section : This statement declare a package name and the classes defined here belonging to the
package.
Syntax: package packagename;
Eg: package college;
3. Import Statement : This is similar to the #include statement in c. And we can have access to class in other
named packages using import.
Syntax: import packagename.classname;
Eg: import java.lang.System;
4. Interface statement: Interface is like a class but it includes a group of method declaration only.
Syntax: interface interfacename
{
Methods declaration;
………….
}
Eg: interface measurement
{
void area();
void volume();
}
5. Class definition: A java program may contain multiple class definitions.
Syntax: class classname
{
Sub class;
Member variable;
Constructors;
Methods;
}
Eg:
class Student
{
int rollno;
String name;
…………
}
6. Main method class: The main method creates objects of various classes and establishes communications
between them.
Syntax:
public static void main(String args[])
{
Create objects
………
}
 Write about Java Environment.
Java environment include a large number of development tools and hundreds of class and methods. The
development tools are part of the system known as Java Development Kit (JDK) and the classes and methods
are part of the Java Standard Library (JSL) also known as the Application Programming interface (API).
Java Development Kit (JDK)
 appletviewer (for viewing java applet)
 javac (Java compiler)
 java (java interpreter)
 javap (Java disassembler)
 javah (for C header files)
 javadoc (for creating HTML documents)
 jbd (Java debugger)
Application Programming Interface
The Java Standard Library (or API) include hundreds of classes and methods grouped into several functional
packages. Most commonly used packages are:
 Language Support Package: A collection of classes required for input/output manipulation.
 Utilities Package: A Collection of classes provide utility functions such as date and time functions.
 Input/ Output Package: A collection of classes required for input/ output manipulation.
 Networking Package: A collection of classes for communicating with other computers via Internet.
 AWT Package: The Abstract Window Tool Kit package contains classes that implements GUI.
 Applet Package: This includes a set of classes that allows us to create Java applets.
Java Virtual Machine (JVM)
JVM is an engine that provides a runtime environment to drive the java program. It converts java byte
code into machine language to execute the program.
 Compiling source code into byte code using the javac compiler.

 Executing the byte code to human-understandable code using a java interpreter.

 Write about data types in Java?


Every variable in java has a data type. Data types specify the size and type of values that can be stored in
variables.
Data types in java are as shown below:
1. Primitive data type (intrinsic/built in data type)
2. Non- Primitive data type(Derived/reference type)

Datatypes in java

Premitive Non- Premitive


(intrinsic) (Derived)

Numeric Non- Numeric classes Arrays

Integer Floating- Point Character Boolean Interface


Integer:
Integer can hold whole numbers, Java supports four type of integers, they are byte, short, int and long.
Integer

byte short int long

Type Size Minimum value Maximum value


Byte One byte -128 128
short Two byte -32,768 32,767
int Four byte -2,147,483,648 2,147,483,647
long Eight byte -9,223,372,036,854,775,808 9,223,372,036,854,775,807

Floating point:
Floating point type to hold the numbers in fractional parts. They are two types of floating points.
1. Float type (Single precision)
2. Double type (double precision)
Floating point numbers are treated as double- precession quantities. To force them to be in single-
precession mode, we must append f of F to the numbers.
Example:
1.23f
7.56923e5F
Floating Point

Float Double

Type Size Minimum value Maximum value


Float Four byte 3.4e-038 3.4e+038
double Eight byte 1.7e-308 1.7e+308
Character Type
The char type assumes a size of 2 bytes but, basically, it can hold only a single character.
Boolean Type
There are only two values that a boolean type can take: true or false.
Boolean type is donated by the keyword boolean and uses only one bit of storage.
Non-primitive data types: Includes Classes, Interfaces and Arrays
Array: Array is a group of similar data items that have a contiguous memory location share a common name.
Class: Class is a user defined datatype. It is a model for creating objects. Class contains member variable,
methods and constructors.
Interface: An Interface is basically a kind of class contain abstract methods (no body) and final fields.
 Define a variable with scope and life time. (Or) Types of variables.
Variable is a name that denotes a storage location used to store a data value.
Some of the rules of variable identification are…
1. They must not begin with a digit.
2. Uppercase and lowercase are distinct. This means the variable Total is not the same as total or TOTAL
3. It should not be a keyword.
4. White space is not allowed
5. Variable names can be of any length.
A variable must be declared before it is used in the program. (Called flexible declaration)
The general form of declaration of a variable is:
Data type varaible1, variable 2, . . . . . . . . . . . . variable N;
Variables are separated by commas. A declaration statement must end with a semicolon.
Some valid declarations are:
int count;
float x,y;
double pi;
byte b;
char c1,c2,c3;
Types variables with scope and life time
Java variables are actually classified into three kinds:
 Instance variables
 Class variables (static variables)
 Local variable.
 Instance variables and class variables are declared inside a class.
Instance variable are created when the objects are instantiated.
They make different values for each object.
 The class variables are global to a class and belong to the entire set of object that class creates.
Only one memory location is created for each class variable called static varaibles.
 Variables declared and used inside method are called local variables.
Local variables can also be declared inside program blocks that are defined between { } braces.

 Write about various operators in Java.


Operator is a symbol used in programs to manipulate data and variables. They usually form a part of
mathematical or logical expressions.
Java operators can be classified into a number of related categories as below:
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bitwise operators
6. Increment and decrement operators
7. Conditional operators
8. Special operators
1. Arithmetic Operator: Arithmetic operators are used to construct mathematical expression. Java provides all
the basic arithmetic operators as shown below.
Operator Meaning
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division
% Modulo division (Remainder)
2. Assignment Operator: Assignment operators are used to assign the value of an expression to a variable.
Usually the assignment operator is ‘ = ’.In shorthand form variable op= expression;

Statements with simple Statement with


assignment operator shorthand operator
a=a+1 a+=1
a=a-1 a-=1
a=a*(n-1) a+=n-1
a=a/(n-1) a/=n-1
a=a%b a%=b
3. Relational Operator: The Relational Operators are compare two quantities, and depending on their relation,
take certain decisions. Java supports six relational Operators and their meaning as shown below.

Operator Meaning Example Result


> Greater than 100 > 30 True
>= Greater than or equal to 5 >= 3 False
< Less than 40 < 2 False
<= Less than or equal to 10<= 10 True
== Equal to 5= = 2 False
!= Not equal to 5! = 4 True

4.Logical Operator:The Logical Operator is used to form compound conditions by combining two or more
relations.

Operator Meaning Example Result


&& AND (2 > 1) && (4 < 2) True
|| OR (2 > 1) | | (2<1) True
! NOT ! (2>1) False
5. Bitwise Operators: Java supports Bitwise Operators for manipulation of data at values of bit level.

Operator Meaning Example Result


& Bitwise AND 13 & 14 12
| Bitwise OR 13 | 14 15
^ Bitwise XOR 13 ^ 14 3
<< Left shift 50 < < 3 400
>> Right shift 50 > > 3 6
~ Complement ~5 -6
6. Increment and Decrement Operator: The Operator ++ is adds 1 to the Operand. And the Operator - - is
subtracts 1. Both are unary Operators and are used in the following form.
++m; // pre increment or m++; // post increment
--m; // pre decrement or m--; // post decrement
Eg:
int m,i=5,j=5;
m=++i; // i becomes 6 and m is also 6 m= - - j // j becomes 4 and m is also 4
int m,i=5, j=5;
m=i++; // i becomes 6 but m is 5 m=j-- // j becomes 4 but m is 5
7. Conditional Operator: The character pair ? : is a ternary operator available in Java. This operator is used to
construct conditional expressions of the form
exp1 ? exp2 : exp3

For Example consider the following statements:


a = 10;
b = 15;
x = (a > b) ? a : b ;
8. Special Operators:
Instance of Operator- The instance of is an object reference operator and returns true. This operator
allows us to determine whether the object belongs to a particular class or not.
Example:
person instanceof student
is true if the object person belongs to the class student; otherwise it is false.
Dot Operator
The dot operator ( . ) is used to access the instance variable and methods of class objects.
Eg:
person.age=20;
person.salary();
 What is Type Casting?
The process of converting on data type to another is called casting.
There are two types of casting
1. Implicit Type casting / Widening Type casting
2. Explicit Type casting / Narrowing Type casting
1. Implicit Type Casting: It is also called as Automatic convention casting. It is possible to assign a value of
one type to a variable of a different type without a cast automatically is known as implicit type casting. In this
the smaller data type converted to bigger data type. There is no data loss.
Eg:
int num=10;
double data= num; // Automatic conversion
2. Explicit Type casting: To store a value of one type into a variable of another type. The bigger data type is
converted to smaller data type. There is data loss chance. It is done by the user with the help of type cast
operator. i.e. ( ).
Ex: double num=10.99;
int data= (int) num; // manual conversion
Here the double is converted to int type.
 Constant in Java?
A constant refer to fixed value that do not change during the execution of a program.
Java supports several types of constants as follows.

Java Constants

Numeric Constants Character Constants

Integer Real Character String


Constants Constans Constants Constants

1. Integer constant: an Integer constant refer to a sequence of digits.


There are three types of integers, Decimal, Octal, and Hexadecimal;
Decimal Integers consist of a set of digits (0 to 9).
Ex: 123 -321 0 6454312

An octal integer constant consists of any combination of digits from the set 0 through 7, with a leading
0. Some examples of octal integer are:
037 0 0435 0551
A sequence of digits preceded by 0x or 0X is considered as hexadecimal integer (hex integer). They may
also include alphabets A through F or a through f. A letter A through F represents the numbers 10 through 15.
Following are the examples of value hex integers.
0x2 0X9F 0xbcd
2. Real Constants: A digit of numbers containing fractional parts is known as Real constants or floating point
constants.
Ex: 0.0083 -0.75 .95 215.
A real numbers may also expressed in exponential format also, for example the value of 215.65 may be
written as 2.1565e2 in exponential notation.
3. Single Character constant: A Single character constant is a single character enclosed with a pair of single
quote marks (’ ’)
Ex: ‘5’ ‘y’ ‘:‘
4. String Constant: A string constant is a sequence of character enclosed with double quotes.
Ex: “Hello Java” “1997” “?....!” “5+3”
 How to accepting Input from the keyboard in Java.
(OR)
Reading Input with Java.util.Scanner Class

In Java, there are many ways to read input. The simplest one is to make use of the class Scanner
Which is part of the “java.util” package.
We can create an object to read input from the standard input consol System.in as follows:

Scanner obj = new Scanner(System.in);


Input Types:

To read various types, look at the table below:

Method Description
nextBoolean() Reads a boolean value
nextByte() Reads a byte value
nextDouble() Reads a double value
nextFloat() Reads a float value
nextInt() Reads a int value
nextLine() Reads a String value
nextLong() Reads a long value
nextShort() Reads a short value

In the example below, we use various methods to read data of various types:

import java.util.Scanner;
class Input
{
public static void main(String [ ] args)
{
Scanner obj=new Scanner(System.in);
System.out.println(“enter name,age,salary”);
String name=obj.nextLine( );
int age=obj.nextInt( );
double salary=obj.nextDouble( );
System.out.println(“Name: ”+name);
System.out.println(“Age: ”+age);
System.out.println(“Salary: ”+salary);
}
}
 How to displaying Output in Java
(OR)
Displaying Output with System.out.printf( )

In java, we can simply use to send output to standard output screen


System.out.print( )
System.out.println( )
System.out.printf( )

Difference between print( ), println( ), printf( )


 printf( ) – It prints string inside the quotes
 println( ) – It prints string inside the quotes similar like print( ) method. Then the cursor moves to the
beginning of the next line.
 printf( ) – It provides string formatting (similar to printf in C)

Some of the commonly used specifiers are:

Printf specifier Data type


%s String of text
%f floating point value (float or double)
%e Exponential, scientific notation of a float or double
%b boolean true or false value
%c Single character char
%d Base 10 integer, such as a Java int, long, short or byte
%o Octal number
%x Hexadecimal number

Example:
class output
{
public static void main(String args[ ])
{
int x=212;
System.out.printf(“Integer: x=%d\n”,x);
float y=277.3f;
System.out.println(“Float: y=”+y);
System.out.print(“concatenated string and value”);
}
}

In the above example concatenated the string and value use the + operator
 How to Displaying Formatted Output with String.format( )
The java String.format( ) method returns the formatted String. It allows concatenate the string; also we can format
the output of the concatenated string.
Syntax:
String.format(“format specifier”, value)
Example:
Class StringFormat
{
public static void main(String args[ ])
{
String s1=String.format(“%d”,277); //Integer value
String s2=String.format(“%s”, ”ADITYA”); // string value
String s3=String.format(“%f”,1986.27); // float value
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
 Control Statements in Java
We can control the order(flow) of program execution, based on logic and values.
In java, control statements can be divided into the following three categories:
 Conditional statements (Selection statements/Branching statements)
 Looping statements (Iteration statements)
 Unconditional statements (Jumping statements)
Conditional Statements:
The If Statement may be implemented in different forms as follows.
1. Simple if statement
2. If . . else statement
3. Nested if . . else statement
4. else if ladder
1. Simple if Statement:
If the condition is the True the statement will execute, otherwise goes to next statement.
Syntax:
if(Condition)
{
Statements;
Eg: }
Next Statements;
int x=10;
if(x>0)
System.out.println(“positive:”);
2. The if else Statement:
If the condition is true the True block will execute, otherwise the False block will execute.
Syntax:
if(Condition)
{
Statements; // true block
}
else
{
Statements; // false block
}
Next Statements;
Eg: int a=10,b=20;
if(a>b)
System.out.println(a+“ is Big:”);
else
System.out.println(b+“ is Big:”);
3. Nesting of if else Statement:
When the series of decisions are involved, we may have to use more than if.. else
Syntax:
if(condition-1)
{
if(condition-2)
{
Statement-1;
}
else
{
Statement-2;
}
}
else
{
Statement-3;
}
Next statement;
Eg:
int a=10,b=20.c=30,Big;
if(a>b)
if(a>c)
Big=a;
else
Big=c;
else
if(b>c)
Big=b;
else
Big=c;
System.out.println(Big);
4. The else if ladder:
The multipath decisions are involved in statements.
Syntax:
if(condition-1)
{
Statement-1;
}
else if(condition-2)
{
Statement-2;
}
……………….
else if(condition-n)
{
Statement-n;
}
else
{
Statement-x;
}
Next Statement;
Eg:
int x=20;
if(x>0)
System.out.println(“positive:”);
else if(x<0)
System.out.println(“negative:”);
else
System.out.println(“zero”);
5. The Switch Statement:
One case is executed from two or more options in a java program using switch case.
Syntax: switch (expression)
{
case value-1:
Block-1
break;
case value-2:
block-2
break;
.........
.........
default:
default- block
break;
}
Eg: switch(choice) {
case 1: System.out.println(“addition:”+(a+b)); break;
case 2: System.out.println(“subtraction:”+(a-b)); break;
case 3: System.out.println(“multiplication:”+(a*b)); break;
case 4: System.out.println(“division:”+(a/b)); break;
default: System.out.println(“wrong choice:”);
}
Looping Statements:
One or more statements are executed repeatedly is called Looping or Iterative Statement.
The Java language provides three loop operations. They are:
1. while
2. do.. while
3. for
While Loop:
While is an entry controlled loop. The body of the loop is executed repeatedly until the condition is false
Syntax:

Initialization;
while(condition)
{
------------
Body of the loop
-----------
Inc/dec;
}
Eg: int i=10;
while(i<=20)
{
System.out.print(i+“ ”);
i++;
}
Do while Loop:
Do while is an exit controlled loop and evaluate the body of the loop first.
At the end of the loop the condition in the while statement is evaluated.
Syntax:
Initialization;
do
{
------------
Body of the loop
-----------
Inc/dec;
} while(condition);
Eg:
int i=1;
do
{
System.out.print(i+“ ”);
i++;
}while (i<=10);
For Loop:
The initialization, condition and increment/decrements are in a single line is called for statement
Syntax:
for(Initialization;condition;Inc/dec)
{
------------
Body of the loop
-----------
}
Eg:
int n=10,sum=0;
for(int i=1;i<=n;i++)
sum=sum+i;
System.out.println(“the sum of 1 to 10 is:”+sum);
For-each Loop:
The enhanced for loop also called for each loop, to retrieve the array of elements by using array indexes;
Syntax:
for (Type Identifier : Expression)
{
// statements;
}

Eg: int a[ ]={10,20,30,40,50};


for(int i:a)
System.out.println(i);
Un-conditional Statements
Java permits a jump from one statement to the end or beginning of a loop as well as a jump out of a loop.

break Statement: Used to terminates a loop.


Syntax:
break;
Eg:
for(int i=1;i<10;i++)
{
if(i==5)
break;
System.out.println(i);
}

Continue Statement: The continue statement skips the current iteration of a loop.
Syntax:
continue;
Eg:
for(int i=1;i<n;i++)
{
if(i==5)
Continue;
System.out.println(i);
}

Return statement: The return statement is used to explicitly return from amethod
Syntax:
return value;
Eg:
int factorial(int n)
{
if(n==0)
return 1;
else
return n*factorial(n-1);
}
Unit- II
 Discuss array in Java?
An array is a set of same data type elements. Have a common name and stored in continues memory locations.
Syntax:
datatype arrayname[ ]=new datatype[size];
Eg:
int a[ ]=new int[7];
First index 0 1 2 3 4 5 6

<------------ Array length is 7 ----------->


Arrays can be classified in to:
1. 1D Array (Single dimensional Array)
2. 2D Array (Multidimensional Array)
3. 3D Array (Three dimensional Array)
One-dimensional Array:
Elements are specified by one subscript.
 Declaring the array:
Syntax:
datatype arrayname[ ]=new datatype[size];
Eg:
int a[ ]=new int[5];
float b[ ]=new float[10];
 Initialization of an Array
datatype arrayname[ ]={list of elements};
Eg:
int a[ ] = {30,35,40,20,12};
 Display array elements,
for(int i=0; i<a.length; i++)
System.out.println(a[i]);
Two-dimensional Array:
Elements are specified by two subscripts.
 Declaring the 2Darray:
Syntax:
datatype arrayname[ ][ ]=new datatype[size1][size2];
Eg: int a[ ]=new int[2][2];
 Initialization of an Array
datatype arrayname[ ]={{row1 elements},{row2 elements}….};
Eg: int a[ ][ ]= {{1,2},{3,4}};
 Display array elements,
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[i].length;j++)
System.out.print(a[i][j]+" ");
System.out.println();
}
Variable size Array (Jagged/ Rugged array):
An array with different number of columns is called “Variable size Array”.
It is possible to declare a two- dimensional array as follows:
int x[ ][ ]= new int[3][ ];
x[0]=new int[2];
x[1]=new int[4];
x[2]=new int[3];

These statements create a two-dimensional array as having different length for each row.

 What is a String? Explain String class Methods.


String a sequence of Characters. String is an immutable object.
In java, strings are implemented following ways:
 Creating a String by java String literal
String s1=”ADITYA”;
 Creating a String by using new keyword
String s2=new String(“Data Science”);
 Converting char array to string
char ch[ ]={‘I’,’n’,’d’,’i’,’a’};
String s3=new String(ch);
Displaying all the three strings
System.out.println(s1); //ADITYA
System.out.println(s1); // Data Science
System.out.println(s1); // India

String class Methods:


Some most commonly used string methods as follows,
Method call Task performed
s2=s1.toLowerCase(); Convert the string s1 to all lowercase
s2=s1.toUpperCase(); Convert the string s1to all Uppercase
s2=s1.replace(‘x’,’y’); Replace all appearances of x with y
s2=s1.trim( ); Remove while spaces at the beginning and end of the string s1
s1.equals(s2); Returns ‘true’ if s1 is equal to s2
s1.equalsIgnoreCase(s2); Returns ‘true’ if s1==s2, ignoring the case of characters
s1.length( ); Gives the length of s1
s1.charAt( ); Gives nth character of s1
s1.compareTo(s2); Return negative if s1<s2, positive if s1<s2, and zero if s1 is equal s2
s1.concat(s2); Concatenates s1 and s2
 What is command Line argument?
Command Line arguments are parameters that are supplied to the program at the time of execution.
Use the arguments provided in the command line as follows
// command line arguments program
import java.lang.*;
class CommandLine
{
public static void main(String args[])
{
System.out.println(“given names are:”);
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
Steps to run the command line arguments program:
1. First compile the java program, must run the java compiler javac, with the name of source file on
command line.
Eg: javac CommandLine.java
2. Use the java interpreter to run a stand-alone program at the command prompt, use the arguments
provided in the command line as follows.
Eg: java CommandLine India England Australia

 Create a class and define an object to accessing the methods to passing parameters.
Class is a user defined datatype. It is a model for creating objects (class variable).
Class contains member variable, methods and constructors.
Syntax:
[Access Specifiers] class classname
{
[Variable declaration;]
[Method definition]
}
Here,
[access specifiers] are private, public, protected, default
Private: The access level of a private modifier is only within the class.
It cannot be accessed from outside the class.
Default: The access level of a default modifier is only within the package.
It cannot be accessed from outside the package.
If you do not specify any access level, it will be the default.
Protected: The access level of a protected modifier is within the package
It can access outside the package through child class.
Public: The access level of a public modifier is everywhere.
It can be accessed from within the class, outside the class, within the package and outside the package.
[Variable declaration] is called member variables or instance variable.
Syntax:
datatype variablename;
[Method definition] is to manipulate the data in class.
The following syntax can be used to adding methods.
returntype methodname (arguments-list)
{
Method body
}

Object is an instance of the class. We can create multiple objects to one class and access the class members.
Syntax:
classname objectname= new classname();
Eg:
class Rectangle
{
int l,b;
void setData(int length, int width ) // method definition with arguments
{
l= length;
b= width;
}
void display( )
{
System.out.println(“Area of a rectangle is:”+(l*b));
System.out.println(“Perimeter of a rectangle is:”+(2*(l+b)));
}
//To accessing a class methods use the concern object with dot operator in main as follows
public static void main(String args[ ])
{
Rectangle r=new Rectangle( ); // declaring an object
r.setData(10,20); // methods to passing parameter
r.display( );
}
}

 What is static keyword in java give an example?


The static keyword in java is used for memory management mainly.
The static members get memory only once.
We can apply the static keyword variables and methods.
Those are called class variables and class methods.

Eg: class Test


{
static int a=10,b=20;
static void display()
{
System.out.println(“a= ”+a+” b= ”+b);
}
public static void main(String args[])
{
Test.a=100;
Test.b=200;
Test.display();
}
}
Output: a= 100 b=200

 What is constructor? Explain different types of constructors.


OR
How to use ‘this’ keyword in java with example?
A method same name has the class name and must have no return type is called constructor.
There are three types of constructors in Java.
1. Default constructor
2. Parameterized constructor
3. Copy constructor
1. Default constructor: A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax:
<classname>( )
{
//Statements
}
2. Parameterized Constructor: A constructor which has a specific number of parameters is called a
parameterized constructor.
Syntax:
<classname>(Parameter-List)
{
//Statements
}
3. Copy constructor: A constructor which has an object is a parameter is called copy constructor.
Syntax:
<classname>(class object)
{
//Statements
}
‘this’ keyword:
‘this’ keyword is eliminate the confusion between parameters and class variables when both have same names.
Eg:
class Student
{
int rollno;
String name;
Student( ) // default constructor
{
rollno=1;
name=”Aditya”;
}
Student(int rollno, String name ) // parameterized constructor
{
this.rollno=rollno; // this keyword is eliminate the confusion between parameters and class variables
this.name=name;
}
Student(Student s) // copy constructor
{
rollno=s.rollno;
name=s.name;
}
void display( )
{
System.out.println(“Rollno=”+rollno+”\nName=”+name);
}
public static void main(String args[ ])
{
Student s1=new Student( );
s1.display( );
Student s2=new Student(2,”SriRam”);
s2.display( );
Student s3=new Student(s1);
s3.display( );
}
}
 Method overloading in java and How to access them?
Two or more methods have the same name but different parameters list is called method overloading.
Eg:
// Find area of square and rectangle
import java.lang.*;
class Areas
{
void area(int a)
{
System.out.println(“area of square is:”+(a*a));
}
void area(int l,int b)
{
System.out.println(“area of rectangle is:”+(l*b));
}
public static void main(String args[])
{
Areas x=new Areas();
x.area(10);
x.area(4,5);
}
}
 What is Inheritance? Write Inheritance Hierarchies, Superclass and Subclass.
The mechanism of deriving a new class from an old one is called inheritance. The old class is known as the base
class or super class or parent class and the new one is called the sub class or derived class or child class.
Use Inheritance in Java
o For method overriding (so runtime polymorphism can be achieved)
o For code reusebility
Defining a Subclass
A subclass is defined using ‘extends’ keyword as follows:
class subclassname extends superclassname
{
[variables declaration]
[method definition]
}
Terms used in Inheritance
o Class: A class is a group of objects which have common properties. It is a blueprint or template from
which objects are created.
o 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.
o 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.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the
member variables 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.
Example:
class Superclass
{
int x=10;
void show( )
{
System.out.println(“From parent class x value:”+x);
}
}
Class Subclass
{
int y=20;
void display( )
{
System.out.println(“From child class y value:”+y);
}
}

 Discuss Types of Inheritance (Inheritance Hierarchies)


The mechanism of deriving a new class from an old one is called inheritance. The old class is known as the
base class or super class or parent class and the new one is called the sub class or derived class or child
class.
Inheritance may take different forms:
 Single inheritance (only one super class)
 Multilevel inheritance (Derived from a derived class)
 Multiple inheritance (several super classes)
 Hierarchical inheritance (one super class, many subclasses)
1) Single Inheritance: A class is derived from one class is called Single Inheritance.
Syntax: class A
{
Variable declaration
Method definition
}
class B extends A
{
Variable declaration
Method definition
}
2) Multilevel Inheritance: A class is derived from another derived class is called Multilevel Inheritance.
Syntax: class A
{
Variable declaration
Method definition
}
class B extends A
{
Variable declaration
Method definition
}
class C extends B
{
Variable declaration
Method definition
}

3) Multiple Inheritance:
A class is derived from two or more classes is called Multiple Inheritance.
Java Does not support Multiple Inheritance in classes.
That is, classes in java cannot have more than one super class.

4) Hierarchical Inheritance: Two or more classes are derived from one class is called hierarchical
Inheritance.
class A
Syntax:
{
Variable declaration
Method definition
}
class B extends A
{
Variable declaration
Method definition
}
class C extends A
{
Variable declaration
Method definition
}
 Write member access rule in Inheritance.
Member access rules, also known as access modifiers, dictate the visibility of classes, methods and fields within
a program. Java provides four main access modifiers:
1. Private: The access level of a private modifier is only within the class.
(It cannot be accessed from outside the class including subclasses also)
2. Default (no modifier): If no access modifier is specified, the member considered default access.
Means the member is accessible only within the same package.
3. Protected: accessible within same package or by subclasses (even if they are in different package)
4. Public: Accessible from any other class
A Subclass includes all of the members of its Superclass, it cannot access those members of the
Superclass that have been declared as private.
For example, consider the following simple class hierarchy:
class Superclass
{
int i; // by default accessible in subclass
private int j; // private to Superclass but not accessible in Subclass
void setValues(int x, int y)
{
i = x;
j = y;
}
}
class Subclass extends Superclass
{
int total;
void sum( )
{
total = i + j; // ERROR, j is not accessible here
}
}
 How to use super keyword can reference a subclass.
The ‘super’ keyword is similar to the ‘this’ keyword.
The super keyword can be used to access any data member or method of Superclass used in Subclass.
Syntax:
super.<methodname>( );
Eg:
super.display( );
// Access overridden methods of the superclass:
class Animal
{
void display( )
{
System.out.println(“I am an Animal”);
}
}
class Dog extends Animal
{
void display( )
{
super.display( ); //calls the overridden method
System.out.println(“I am Dog”);
}
}
 How to prevent overriding and Inheritance using ‘final’ classes and methods
The keyword final has three uses. First, it can be used to create the equivalent of a named constant.
Second, use final to prevent overriding and third, use final to prevent Inheritance.
1. Using final to prevent overriding:
Methods declared as final cannot be overridden.
The following fragment illustrates final:
class A
{
final void meth( )
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth( ) // ERROR! Can't override.
{
System.out.println("Illegal!");
}
}

2. Using final to prevent inheritance


Sometimes you will want to prevent a class from being inherited.
To do this, precede the class declaration with final.
Declaring a class as final implicitly declares all of its methods as final, too.
Here is an example of a final class:

final class A
{
//...
}
// The following class is illegal.
class B extends A // ERROR! Can't subclass A
{
//...
}
 What is Object class? What are the methods in Object class.
There is one special class, Object, defined by Java.
All other classes are subclasses of Object class. That is, Object is a superclass of all other classes.
Object defines the following methods, which means that they are available in every object.

 What is Dynamic binding (or) Dynamic method dispatching?


Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run
time, rather than compile time. A superclass reference variable can refer to a subclass object.
// Dynamic Method Dispatch
class A
{
void display( )
{
System.out.println("Inside A's method");
}
}
class B extends A
{
void display( ) // override display()
{
System.out.println("Inside B's method");
}
public static void main(String args[])
{
A a = new A( ); // object of type A
B b = new B( ); // object of type B
A r; // obtain a reference of type
A r = a; // r refers to an A object
r.display( ); // calls A's method of display
r = b; // r refers to a B object
r.display(); // calls B's method of display
}
}

 What is method overriding in Java


Defining a method in the subclass has same name, same arguments and same return type as a method in
the super class. When the method is called, the subclass method is invoked. This is known as Overriding.
Consider the following example to illustrate the concept of overriding.
class One
{
int x=10;
void display()
{
System.out.println(“Super x=”+x);
}
}
class Two extends One
{
int y=20;
void display()
{
System.out.println(“Super x=”+x+”\n Sub y=”+y);
}
}
class OverrideTest
{
public static void main(String args[])
{
Two t=new Two( );
t.display();
}
}
 What are the abstract classes and methods?

A method must always be redefined in a subclass, thus making overriding compulsory. This is done
using the modifier keyword abstract in the method definition.
When a class contains at least one abstract method, it should be declare abstract
Eg:
abstract class Animal
{
abstract void display( ); // abstract method
}
class Dog extends Animal
{
void display( ) // redefined the abstract method in Subclass
{
System.out.println(“I am Dog”);
}
public static void main(String args[ ])
{
Animal a=new Dog( );
a.display( );
}
}

While using abstract classes, we must satisfy the following conditions:


 We cannot use abstract classes to instantiate objects directly.
For example,
Animal a=new Animal ( ) // it is not possible because Animal is an abstract class
 The abstract methods of an abstract class must be redefined in its subclass.
 We cannot declare abstract constructors or abstract static methods.
Unit –III
Interfaces, Packages and Exception Handling
 Interface vs Abstract class

Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only
abstract methods. abstract methods.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, static Interface has only static and final
and non-static variables. variables.

4) Abstract class can provide the implementation Interface can't provide the
of interface. implementation of abstract class.

5) The abstract keyword is used to declare abstract The interface keyword is used to declare
class. interface.

6) An abstract class can extend another Java class An interface can extend another Java
and implement multiple Java interfaces. interface only.

7) An abstract class can be extended using keyword An interface can be implemented using
"extends". keyword "implements".

8) A Java abstract class can have class members like Members of a Java interface are public by
private, protected, etc. default.

Example: Example:
abstract class Shape { interface Drawable {
abstract void draw( ); void draw( );
} }

 Defining an Interface and how to extending, implement and access the interface.

An Interface is basically a kind of class contain abstract methods (no body) and static constant fields.
The general form of Interface definition is:

interface interfaceName
{
Variable declaration with value;
Method declaration;
}
Example:
interface Area
{
final static float pi=3.142F;
float compute(float x, float y);
void show( );
}
Extending Interfaces:
Interface can also be extended. An Interface can be sub interfaced from other interfaces.
Syntax:
interface interface2 extends interface1
{
Body of name2
.............
}

Example:
Interface ItemCost
{
int code=1001;
String name=”Fan”;
}
interface Item extends ItemCost
{
void display( );
}

Implementing Interfaces:
Interfaces are used as “Super classes” whose properties are inherited by classes is called implementing
interfaces.
The general from is:
class classname implements interfacename
{
body of classname
}

Accessing Interface Variable:


Interface can be used to declare a set of constants that can be used in different classes. The constant
values will be availble to any class that implements the interface.
Example:
interface ItemList
{ int code=1001;
String name=”Fan”;
void display();
}
class Item implements ItemList
{ int cost=2000;
void display()
{
System.out.println(“code :”+code+”\n name :”+name+”\nprice :”+price);
}
}

 Defining a package? How to creating, accessing and importing a package.


(or) Explain user defined package?

Package is a collection of classes and interfaces and sub-package.


Create a package :
To create our own package we must first declare the name of the package using package keyword and
followed by a package name.
Syntax:
package Packagename;
Eg: package firstpackage;

Java support the concept of package hierarchy i.e., package contains subpackage as follows:
syntax:
package firstpackage.secondpackage;

Importing a package:
We use the ‘import’ statement to access various classes in various packages as follows:

import package1 [.package2] [.package3].classname;


Eg: import firstpackage.secondpackage.Myclass;

Accessing Package:
Java addresses four categories of visibility for class members:
• Subclasses in the same package
• Non-subclasses in the same package
• Subclasses in different packages
• Classes that are neither in the same package nor subclasses
Using a package and adding a class to a package:
When we create our own package named as ‘mypack’ and adding a class named as ‘MyClass’ listed in below
package mypack;
public class MyClass
{
public void display()
{
System.out.println(“ MyClass”);
}
}
Now compile the java file and the .class file is stored in the directory named as mypack.
Now use this class in other program as follows:
import mypack.MyClass;
class PackageTest
{
public static void main(String args[])
{
MyClass m=new MyClass();
m.display();
}
}
Under standing CLASSPATH:
If your package is a subdirectory of the current directory it will be found. You can specify a directory path or
paths by setting the CLASSPATH.
To display the current CLASSPATH variable, use the following commands
In windows  set CLASSPATH = “……….path…………”
Eg:
set CLASSPATH= “C:\users\aditya\desktop\java_prgms\classes”
In Unix  % CLASSPATH = ………path………; export CLASSPATH
Eg: % CLASSPATH = /home/aditya/java_prgms/classes; export CLASSPATH
 Explain concept of Exception handling.
Exception: An exception is a condition that is caused by a run-time error in the program. The error handling
code performs the following tasks.
1. Find the problem (exception)
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (Catch the exception)
4. Take corrective actions (Handle the exception)
Exception Handling:
A mechanism to handle runtime errors such as ArithmeticException, ArrayIndexOutOfBoundsException,
NullPointerException etc. by using the keywords try, catch, finally, throw, throws.
Generally the Exception handling in ways:
1. Checked Exception: Exception occur at Compile time
Identifies the error and throws exception.
2. Un-Checked Exception: Exception occur at Run time
Identifies the cause’s exception in try block and handle the exception in catch block.
Syntax:
try
{
Statements that cause an exception
}
catch(Exception type object)
{
Statements that handles the exception
}
finally
{
Statements always executed
}
Example:
try
{
int a=100/0;
}
catch(ArithmeticException ae)
{
System.out.println(ae);
}
finally
{
System.out.println(“exception handled:”);
}
Built in Exceptions: Exceptions that are already available in Java libraries are referred to as built-in exception.
Create own Exception subclass: (throw the exception) / user defined exception
We can create our own exception with message and condition when throw them.
Eg:
Class ThrowException
{
public static void main(String args[ ])
{
try
{
throw new MyException(“Create own Exception and throw:”);
}
catch(MyException e)
{
System.out.printlne(e.getMessage( )+ “\nCaught the exception”);
}
}
}
 Benefits of Exception Handling
1. Graceful Error Recovery
2. Separation of Concerns
3. Failure Isolation
4. Debugging and Diagnostics
5. Robustness and Reliability
6. Fail – fast principal
7. Resource management
8. Flexibility and Extensibility
Unit- IV
Multithreading
 Write Difference between Multiple processes and Multithreading.
A process is an executing program. In multiprocessing, many processes are executed simultaneously.
Thread is a light weight process. That can be executed independently. In multithreading, many threads are
executed simultaneously.

Factor Multiprocessing Multithreading

Multiple processors/CPUs are added to Multiple threads are created of a process to


Concept the system to increase the computing be executed in a parallel fashion to increase
power of the system. the throughput of the system.

Parallel Multiple processes are executed in a Multiple threads are executed in a parallel
Action parallel fashion. fashion.

Multiprocessing can be classified into


No such classification present for
Categories symmetric and asymmetric
multithreading.
multiprocessing.

Time Process creation is time-consuming. Thread creation is easy and is time savvy.

In multiprocessing, many processes are In multithreading, many threads are


Execution
executed simultaneously. executed simultaneously.

Address In multiprocessing, a separate address In multithreading, a common address space


space space is created for each process. is used for all the threads.

Multiprocessing requires a significant


Multithreading requires less time and few
Resources amount of time and large number of
resources to create.
resources.

 What is a Multithreading? Describe Thread States and Thread Lifecycle.


Thread is a light weight process to represent set of statements executed independently by JVM.
Multithreading means many threads are executed simultaneously.
Multiple threads are executed in a parallel fashion.

There are many states include in Lifecycle of Thread as follows:


1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
Thread Life- Cycle:

1. Newborn State: When we create a thread object is said to be in Newborn state. At this state, we can do only
one of the following things:
start( ) method
stop( ) method

2. Runnable State: the runnable state means that the thread is ready for execution and is waiting for the
availability of execution. The threads are waiting for the execution and based on priority.

3. Running State: means the processor has given its time to the thread for its execution by performing run()
method. A running thread can do any one of the following thing to block:
suspend() method
sleep() method
wait() method

4. Blocked State: A thread is said to be blocked when it is “not runnable” but “not dead” and ready to run
again. This is happens when the thread is suspend() or sleep() or wait().
5. Dead State: Every thread has a lifecycle. A running thread ends its life when it has completed executing its
run() method. And also use the stop() method to kill the executing thread goes to dead state.
 How to creating a thread by extending a thread?
Thread is a light weight process to represent set of statements executed independently by JVM.
Multithreading means many threads are executed simultaneously.
Multiple threads are executed in a parallel fashion.
Creating a Thread:
A new thread can be created in two ways:
1. By creating a thread class: Define a class that extends Thread class and override its run( ) method with the
code required by the thread.
2. By converting a class to a thread: Define a class that implements Runnable interface. The Runnable
interface has one method, run( ), that is to be defined in the method with the code to be executed by the
thread.
Extending a Thread:
We can make our class as thread class by extending the class java.lang.Threaed. This gives us access to all the
thread methods directly. It includes the following steps.
1. Declare the class as extending the Thread class.
2. Implements the run( ) method for executing the sequence of code that the thread will execute.
3. Create a thread object and call the start( ) method to initiate the thread execution.
Declaring a class
The Thread class can be extended as follows:
Syntax: class MyThread extends Thread
{
.........
.........
}
The run() method is only method in which the thread’s behavior can be implemented.
run() would be appear as follows.
Syntax:
public void run( )
{
. . . . . . . . . . (Statements for implementing thread)
..........
}
The run() method is invoked by creating the thread and initiating with another thread method called start().
To Start a new thread is follows.
MyThread mt=new MyThread();
mt.start(); //invokes the run() method
 What is Stopping a thread and blocking a thread or Interrupted a thread?
Stopping a Thread: we want to stop a thread from running thread by calling stop() method.
This statement causes the thread to move to the dead state.
A thread will also move to the dead state automatically when it reaches the end of its method.
Blocking a thread:
A thread can also be temporarily suspended or blocked from running state by using following thread methods:
sleep() //blocked for a specified time
suspend() // blocked until further orders
wait() // blocked until certain condition occurs
 What is Thread Priority? Explain with example?
A thread priority is scheduled for running to share a processor on a first-come first serve basis.
Set the priority a thread using the setPriority() method as follows:

ThreadName.setPriority(intNumber)
;
The intNumber is an integer value to which the thread’s priority is set.
The Thread class defines several priority constrains:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
Whenever multiple threads are ready for execution, the java system chooses the highest priority thread and
executes.
//Thread Priority program
import java.io.*;
class MyThread implements Runnable
{
public static void main(String args[])
{
MyThread mt = new MyThread();
Thread t1 = new Thread(mt,"One");
Thread t2 = new Thread(mt,"Two");
t1.setPriority(1);
t2.setPriority(10);
t1.start();
t2.start();
}
public void run()
{
for(int i=1;i<=5;i++)
System.out.println(Thread.getName());
}
}
 How to interrupting Threads in Java ?
(or)
How to Inter thread communication?
(or)
What is Thread Exception?
The sleep( ) method throws an exception. Thus sleep( ) method enclosed in a try block and followed by
catch block. If we fail to catch the exception, program will not compile. This is called thread exception.
// Thread interrupted program
import java.lang.*;
public class MyThread extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println(" In run : " + i);
try
{
Thread.sleep(2000);
}
catch(InterruptedException ie)
{ }
}
if(i==4) stop();
}
}
public static void main(String args[])
{
MyThread t1 = new Thread1();
t1.start();
MyThread1 t2 = new Thread1();
t2.start();
}
}

 What is synchronization?
If two or more threads are trying to access the same resource and the second thread wait until the first thread
comes out of the thread method by using synchronization. A block of code has synchronized as shown below.
Syntax:
synchronized method1 ( )
{
// Synchronized the statements
}
//Thread Synchronization program
import java.io.*;
class MyThread implements Runnable
{
public static void main(String args[])
{
MyThread mt = new MyThread();
Thread t1 = new Thread(mt,"One");
Thread t2 = new Thread(mt,"Two");
t1.start();
t2.start();
}
public synchronized void run()
{
for(int i=1;i<=5;i++)
System.out.println(Thread.getName());
}
}
 Steps to implementing the “Runnable Interface”?
We create threads in two ways: one by using the extended Thread class and another by implementing Runnable interface.
To do this, we must perform the steps listed below:
1. Declare the class as implementing the Runnable interface.
2. Implement the run( ) method.
3. create a thread by defining an object from this Runnable interface
4. call the thread ‘s start() method to run the thread.
The general form is as follows:
class MyThread implements Runnable
{
public void run()
{
// Statements for implementing thread
}
.............
}
// Multithreading program to use Runnable Interface
import java.io.*;
class MyThread implements Runnable
{
public static void main(String args[])
{
MyThread mt = new MyThread();
Thread t1 = new Thread(mt,"One");
Thread t2 = new Thread(mt,"Two");
t1.start();
t2.start();
t3.start();
}
public void run()
{
for(int i=1;i<=5;i++)
System.out.println(Thread.getName());
}
}
Stream based I/O (java.io)
 What is a stream? Write various Stream based I/O classes in java
Flow of information (data) from source to destination.
Source: file, memory or consol
Destination: file, memory pr consol.
A stream is not active on its own. Some other push data into stream or pull data from stream.
Java Provides two types of streams : 1. Byte Stream
2. Character Stream
1. Byte Stream:
Java Byte Streams are used to perform input and output of 1byte (8 bit)
There are many classes are related to Byte Stream.
Most frequently used classes are: FileInputStream and FileOutputStream.

Some of the Byte Stream classes are listed below.


Byte Stream Description
BufferedInputStream handles buffered input stream data
BufferedOutputStream handles buffered output stream
FileInputStream used to read from a file
FileOutputStream used to write to a file
InputStream Abstract class that describe input stream
OutputStream Abstract class that describe output stream

Byte Stream Classes are in divided in two groups -


 InputStream Classes - These classes are subclasses of an abstract class,
InputStream and they are used to read bytes from a source (file, memory or console)
 OutputStream Classes - These classes are subclasses of an abstract class,
OutputStream and they are used to write bytes to a destination (file, memory or console)

2. Character Stream:
Java Character Streams are used to perform input and output of 2bytes (16 bit) Unicode.
There are many classes are related to Character Stream.
Most frequently used classes are: Reader and Writer
Some of the Character Stream classes are listed below.

Character Stream Description


FileReader provides methods to read characters from the file.
BufferedReader Provides methods to read characters from the buffer.
InputStreamReader provides methods to convert bytes to characters.
FileWriter provides methods to write characters to the file.
BufferredWriter provides methods to write characters to the buffer.
OutputStreamReader provides methods to convert from bytes to characters.
Taking input from keyboard
To take input from a user, we use BufferedReader class by creating an object of it.
For that, we have to write the following code to reading the input data from keyboard.

import java.io.*;
class Testio
{
public static void main( String args[]) throws IOException
{
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter your name:");
String name = b.readLine();
System.out.println(name);
}
}

 What is the Console class? How to Reading Console input and Writing console output.
The Console class provides basic input and output support for applications that read characters from
Console and write characters to the console.
1. It provides methods to read text and passwords.
2. Some of the methods in consol class are: reader( ), writer( ), format( ), printf( ), readLine( ),
readPassword( ) etc..
3. If you are read password using console class it will not be displayed to the user.
4. Console supplies no constructors. Instead, a console object is obtained by calling System.console()
5. So the java.io.Console class is attached with System.console( ) internally.

Reading Console Input and Writing Consol Output:


Java Console class is used to get input from Consol. It provides to read texts and passwords.
// Program ro demonstrate Console class
import java.io.*;
class ConsoleDemo
{
public static void main(String args[])
{
Console con = System.console();
String str = con.readLine("Enter your name: "); // read consol input
System.out.println("Enter the password: ");
char[] ch=con.readPassword();
String pass = String.valueOf(ch);
con.printf("Here is your name: %s\n", str); // write consol output
System.out.println("Password is: " + pass);
}
}
 How to use File classes to reading and writing in files?
Reading and writing in a file
We have been reading the data entered by a user using the keyboard.
Now, we will see how to read and write data in a file.

// Program to Writing data in a file


class Test
{
public static void main( String args[])
{
FileOutputStream fos=new FileOutputStream("File1.txt");
String str="Welcome to Java File handling";
byte b[]=str.getBytes(); //converting string into byte array
fo.write(b);
fos.close();
}
}

Here, byte b[ ]=str.getBytes(); is converting string(character array) into byte array.


Then by writing fos.write(b) we are writing the data in a file named file1.txt
because fos is the object of the FileOutputStream class.

// Program to Reading data from a file


class Test1
{
public static void main( String args[])
{
FileInputStream fis=new FileInputStream("File1.txt");
int n=0;
while((n=fis.read())!= -1)
System.out.println((char)n);
fis.close();
}
}

 What is Serialization?
Serialization in Java is the process of converting an object's state
into a byte stream.
Here are some things to know about serialization in Java:
 Deserialization: The opposite of serialization.
deserialization is the process of converting a byte stream back into
an object.
 JVM-independent: Serialization and deserialization can be performed on different JVMs.
It is mainly used to travel object’s state on the network.

import java.io.Serializable;
class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
class Persist{
public static void main(String args[]){
try{
Student s1 =new Student(211,"ravi");
FileOutputStream fout=new FileOutputStream("file.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.close();
System.out.println("success");
}catch(Exception e){ }
}
}
UNIT-V
GUI Programming with Swing
 Write a short note on MVC architecture.
MVC, or Model-View-Controller, is a design pattern in Java that separates an application's logic and
user interface into three layers:
 Model: Manages the application's data logic, including storing and retrieving data from back-end data
stores.
 View: Provides the user interface (UI) for interacting with the application.
 Controller: Links the model and view together.

Advantages of MVC architecture:


 Development of the application becomes fast.
 Easy for multiple developers to collaborate and work together.
 Easier to update the application.
 Easier to Debug as we have multiple levels properly written in the application.
Limitations of MVC architecture:
Model-View-Controller (MVC) architecture has several limitations, including:
 Complexity
 Tight coupling
 Not suitable for small applications
 Requires knowledge of multiple technologies
 Requires multiple programmers
 Hard to understand
 Write a short note on GUI programming with Swing in Java. (Or)
Write about various Components and Containers in Swing
GUI, or Graphical- User- Interface is a user friendly visual experience builder for Java applications.
Swing is a Set of API (API- Set of Classes and Interfaces), Swing is Provided to Design Graphical User
Interfaces (GUI)
Features of Swing Class
 Pluggable look and feel.
 Uses MVC architecture.
 Lightweight Components.
 Platform Independent.
 Advanced features such as JTable, JTabbedPane, JScollPane, etc.
 The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Some of the components and containers are:

Components:
 Components are the building blocks of GUI applications.
 In java, components are typically represented by classes that extend the javax.swing.JComponent class.
 Examples of components include JButton, JTextField, Jlabel, Jlist, JCheckBox, JScrollPane and more.
 Components are responsible for rending themselves on the screen and handling user interactions like mouse
clicks and keyboard input.
Some of the component classes are:
JButton: It represent a clickable button.
JLabel: It display the text or Image.
JTextField: It allows the user to input text.
JList: It represents a list of elements.
JTable: It represents a table data.
JCheckBox: To check or mark functionality to the data.
JScrollPane: Provides the scrolling functionality to other components
Containers:
 Containers are objects that hold and manage components within a GUI applications
 They provide layout management (arranging the components in a specific manner within the container)
 In java, containers are represent by classes that extend the javax.swing.JFrame class
 Examples of containers include JFrame, JDialog, JPanel, JTabbedPane etc.
 Container can hold other containers as well as components and it provides a space where a component can
be managed and displayed.
Containers are two types:
1. Top level Containers:
It cannot be hold or placed on other containers.
Also called as Heavy weight container.
It is a fully functioning window.
Ex: JFrame, Applet
2. Lightweight:
It inherits from JComponents class.
It is a general purpose container.
It can be contain with another container.
It is a pure container but not like window.
Ex: JPanel
 Understand various Layout Managers in Java.
In Java, the Layout Managers are the set of classes that positions of the component. It is used to
arranging and sizing of graphical components such as Button, TextField, Panel and more.
Some of the Layout Managers are:
1. FlowLayout
2. BoarderLayout
3. CardLayout
4. GridLayout
5. GridBagLayout
FlowLayout:
 Flow Layout is a simple layout manager that arranges components in a row, left to right and top to bottom.
 It is used to arrange the components in a line one after another.
 It is default layout of the Panel or Applet.
Fields of FlowLayout class:
1. LEFT
2. RIGHT
3. CENTER
4. LEADING
5. TRAILING
Example:
import javax.swing.*;
import java.awt.*;
public class FlowLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("FlowLayout Example");
frame.setLayout(new FlowLayout());
frame.add(new JButton("Button 1"));
frame.add(new JButton("Button 2"));
frame.add(new JButton("Button 3"));
frame.setSize(300,150);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Output:

Boarder Layout:
The BoarderLayout divides the container into five regions: EAST, WEST, NORTH, SOUTH, CENTER.
Components can be added to these regions, and they will occupy the available space accordingly.
The Boarder Layout provides five fields for each region.
1. BoarderLayout.EAST
2. BoarderLayout.WEST
3. BoarderLayout.NORTH
4. BoarderLayout.SOUTH
5. BoarderLayout.CENTER
Example:
import javax.swing.*;
import java.awt.*;
public class BorderLayoutExample {
public static void main(String[ ] args) {
JFrame frame = new JFrame("BorderLayout Example");
frame.setLayout(new BorderLayout());
frame.add(new JButton("North"), BorderLayout.NORTH);
frame.add(new JButton("South"), BorderLayout.SOUTH);
frame.add(new JButton("East"), BorderLayout.EAST);
frame.add(new JButton("West"), BorderLayout.WEST);
frame.add(new JButton("Center"), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Output:

Card Layout:
CardLayout allows components to be arrange in a deck. Only one component is visible at a time, and you can
switch between components using methods like next( ) and previous( ).
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CardLayoutExample {
public static void main(String[ ] args) {
JFrame frame = new JFrame("CardLayout Example");
CardLayout cardLayout = new CardLayout();
JPanel cardPanel = new JPanel(cardLayout);
JButton button1 = new JButton("Card 1");
JButton button2 = new JButton("Card 2");
JButton button3 = new JButton("Card 3");
cardPanel.add(button1, "Card 1");
cardPanel.add(button2, "Card 2");
cardPanel.add(button3, "Card 3");
frame.add(cardPanel);
frame.setSize(300,100);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button1.addActionListener(e -> cardLayout.show(cardPanel, "Card 2"));
button2.addActionListener(e -> cardLayout.show(cardPanel, "Card 3"));
button3.addActionListener(e -> cardLayout.show(cardPanel, "Card 1"));
}
}
Output:

Grid Layout:
GridLayout arranges components in a grid with a specified number of rows and columns. Each cell in the grid
can hold a component. Such as a calculator or a game board.
Example:
import javax.swing.*;
import java.awt.*;
public class GridLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("GridLayout Example");
frame.setLayout(new GridLayout(3, 3));
for (int i = 1; i <= 9; i++) {
frame.add(new JButton("Button " + i));
}
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Output:

GridBag Layout:
The GridbagLayout component is used to align components vertically, horizontally or along their base line.
The components may not be same size. It arranges components in a grid, but unlike GridLayout, it allows
varying sizes.
Example:
import javax.swing.*;
import java.awt.*;
public class GridBagLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("GridBagLayout Example");
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
constraints.gridx = 0;
constraints.gridy = 0;
panel.add(button1, constraints);
constraints.gridx = 1;
panel.add(button2, constraints);
frame.add(panel);
frame.setSize(400,200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Output:
Event Handling
 Explain about Event Handling in Java (or) Delegation Event Model in Java.
An action performed on a component is an Event.
An Event is an object that describes a state change in a Source.
Activities that may cause to generate events
1) Actions include Clicking a button
2) Typing text via keyboard
3) Moving, clicking, long pressing, releasing a mouse is an event
4) Moving mouse wheel is an event
5) Moving, adjusting, resizing, minimizing, maximizing and closing a windows is an Event.
Java provides a package java.awt.event that contains several event classes.
The events in categories:

1. Foreground Events: require user interaction to generate event with components in GUI.
For example when a user click on a button, moves the cursor, scrolls the scrollbars, pressing a keyboard key
and selecting an option from the list etc.
2. Background Events: Does not require any user interaction. These events automatically generate in the
background. For example OS failures, OS interrupts, operation completion etc.
Delegation Event Model
The approach java supports for event handling is Delegation Event Model. In this model a source generates an
event and sends it to one or more listeners.
The below image demonstrates the event processing:

Steps to perform Event Handling


Following steps are required to perform event handling:
1. Identify the event source
2. Create an event listener
3. Register the event listener
4. Implement the event handling logic
An Event model is based on the following three components:
1. Event classes
2. Event Sources
3. Event Listeners
Event classes: Represents events at the event handling mechanism using EventClass hierarchy is EventObject.
Some of the types of Events are used in:
• ActionEvents : Click a Button, Select a list Item or Menu Item, enter in TextFiled etc.
• AdjustmentEvents: Scrolling a slider of Scrollbar
• ComponentEvents: Hide a Component, Show a Component, Resize a component ,Move a Component
• ContainerEvents: Add a Component or Remove a Component
• FocusEvents: component is receiving the focus and losing focus
• WindowEvents: minimizing a window, maximizing a window, close, open, resize
• ItemEvents: check or Uncheck the Checkbox or Radio button or Choice or List.
• KeyEvents: press the key or release the key or Typing.
• MouseEvents: Click and relese.
• MouseWheelEvents: Scrolling the mouse Wheel.
• TextEvent: change the contents of the Text field or Text area.
Event Sources:
A Source is an object in any of the following components classes that generates an event.
Button Generates ActionEvents when a button is pressed

Checkbox Generates ItemEvents when the Check box is selected or deselected

Choice Generates ItemEvents when the Choice is selected or deselected

List Generates ItemEvents when the List Item is selected or deselected

MenuItem Generates ItemEvents when the Menu Item is selected or deselected

Scrollbar Generate Adjestment event when Scrolling a slider of Scrollbar

Text Generate TextEvent when enter in Text Field or Text Area


Components
Window Generate WindowEvents when minimizing, maximizing, close, open,
resize a window
Event Listeners:
An Event Listener is an object that invoked when an event trigger.
The listeners require two things; First, must be register with a source,
Second must implement the methods to process the event.
Some of the Event Listeners are:
 ActionListener
 AdjustmentListner
 TextListener
 ItemListener
 KeyListener
 MouseListener
 WindowListener
For registering the component with the Listener, many classes provide the registration methods.
For example:
Button
public void addActionListener(ActionListener a){}
MenuItem
public void addActionListener(ActionListener a){}
TextField
public void addActionListener(ActionListener a){}
public void addTextListener(TextListener a){}
TextArea
public void addTextListener(TextListener a){}
Checkbox
public void addItemListener(ItemListener a){}
Choice
public void addItemListener(ItemListener a){}
List
public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){}
 Write about Adapter classes, Inner classes and Anonymous Inner classes.
Adapter Classes:
Java provides a special feature, called an adapter class, that can simplify the creation of event handlers.
Pros of using Adapter classes:
 It assists the unrelated classes to work combinedly
 It provides ways to use classes in different ways
 It increases the transparency of classes
 It increases the reusability of the class
java.awt.event Adapter classes
Adapter class Li Listener Interface
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
Inner class (Nested classes): A Java inner class is a class that is defined inside another class.
Syntax of Inner class
class Java_Outer_class {
//code
class Java_Inner_class {
//code
}
}
Advantage of Java inner classes
There are three advantages of inner classes in Java. They are as follows:
1. Nested classes represent a particular type of relationship that is it can access all the members of the outer
class, including private.
2. Nested classes are used to develop more readable and maintainable code because it logically group
classes and interfaces in one place only.
3. Code Optimization: It requires less code to write.

Anonymous Inner Class:


A Local Inner class without name is known as anonymous inner class.
An anonymous class is defined and instantiated in a single statement.
Anonymous inner class always extends a class or implements an interface.
Java Anonymous inner class can be created by two ways:
1. Using Class (may be abstract or concrete).
2. Using Interface
There are some restrictions on creating anonymous inner class. They are,
1. Must always extend a class or implements an interface.
2. Must implements all the abstract methods
3. Always uses the no-args constructor from its superclass to create an instance.
4. It is compiled into a outer class name.
5. For example, if the outer class has two inner classes, these two classes are compiled into separately.

You might also like