Unit-All-Oops Using Java1
Unit-All-Oops Using Java1
Name : ______________________________
RollNo: ______________________________
Group: ______________________________
Section: _____________________________
Year : ________________________________
UNIT-I
OOPs Concepts and Java Programming: Introduction to Object-Oriented
concepts, procedural and object-oriented programming paradigm
Java programming: An Overview of Java, Java Environment, Data types,
Variables, constants, scope and life time of variables, operators, type conversion
and casting, Accepting Input from the Keyboard, Reading Input with
Java.util.Scanner Class, Displaying Output with System.out.printf(), Displaying
Formatted Output with String.format(), Control Statements
UNIT-II
Arrays, Command Line Arguments, Strings-String Class Methods
Classes & Objects: Creating Classes, declaring objects, Methods, parameter
passing, static fields and methods, Constructors, and ‘this’ keyword, overloading
methods and access
Inheritance: Inheritance hierarchies, super and subclasses, member access rules,
‘super’ keyword, preventing inheritance: final classes and methods, the object
class and its methods; Polymorphism: Dynamic binding, method overriding,
abstract classes and methods;
UNIT-III
Interface: Interfaces VS Abstract classes, defining an interface, implement
interfaces, accessing implementations through interface references, extending
interface;
Packages: Defining, creating and accessing a package, understanding
CLASSPATH, importing packages.
Exception Handling: Benefits of exception handling, the classification of
exceptions, exception hierarchy, checked exceptions and unchecked exceptions,
usage of try, catch, throw, throws and finally, rethrowing exceptions, exception
specification, built in exceptions, creating own exception sub classes.
UNIT-IV
Multithreading: Differences between multiple processes and multiple threads,
thread states, thread life cycle, creating threads, interrupting threads, thread
priorities, synchronizing threads, inter thread communication.
Stream based I/O (java.io) – The Stream classes-Byte streams and Character
streams, Reading console Input and Writing Console Output, File class, Reading
and writing Files, The Console class, Serialization
UNIT-V
GUI Programming with Swing- Introduction, MVC architecture, components,
containers. Understanding Layout Managers - Flow Layout, Border Layout, Grid
Layout, Card Layout, Grid Bag Layout.
Event Handling- The Delegation event model- Events, Event sources, Event
Listeners, Event classes, Handling mouse and keyboard events, Adapter classes,
Inner classes, Anonymous Inner classes.
Disadvantages:
Krishnaveni Degree College: Narasaraopet Page No.: 3
Object Oriented Programming using Java UNIT - I
Advantages:
1. Object Oriented Programming allows the reusability of the code.
2. Object Oriented Programming allows the programmer to build
secure programs.
data together and keeps both data and code safe from outside
interference and misuse. In an object-oriented language, code and data
may be combined as a self-contained "black box". In Java, the basis of
encapsulation is the class. A class defines the structure and behavior (data
and code) that will be shared by a set of objects.
Figure : Inheritance
A super-class can have any number of subclasses. But a subclass can have
only one superclass. This is because Java does not support multiple
inheritance. The superclass and subclass have “is-a” relationship between
them.
targeted for that CPU. The problem is that compilers are expensive and time-
consuming to create. An easier and cost-efficient solution was needed. In an
attempt to find such a solution, Gosling and others began work on a portable,
platform independent language that could be used produce code that would
run on a variety of CPUs under differing environments. This effort ultimately
led to the creation of JAVA.
Java Virtual Machine: Java solves both the security and the portability
problems by making the output of a Java compiler as bytecode which is not
an executable code. Bytecode is a highly optimized set of instructions
designed to be executed by the Java run-time system, which is called the Java
Virtual Machine (JVM). The original JVM was designed as an interpreter for
bytecode.
Data Types: Every variable in java has a data type. Data types specify the size
and type of value that can be stored in a variable. Java language is rich in its
data types and there are two types of data types. They are
1. Primitive data types
2. Non-primitive data types
The classification of data types in java are shown in figure below.
to127 i.e. -27 to 27-1. Default value stored in byte variable is 0. byte data type
is used to save space in large arrays, mainly in place of integers, since a byte
is four times smaller than an integer.
Ex: byte a = 100, byte b = -50
short: short data type is a 16-bit signed integer number. The negative
numbers are expressed in two‘s complement form. The range accepted by
byte is -32,768 to 32,767 i.e. -215 to 215 -1. Default value stored in short
variable is 0.
Ex: short s = 10000, short r = -20000
int: int data type is a 32-bit signed integer number. The negative numbers
are expressed in two‘s complement form. The range accepted by int is-
2,147,483,648 to 2,147,483,647 i.e. -231 to 231-1. int is generally used as the
default data type for integer values unless there is a concern about memory.
Default value stored in int variable is 0.
Ex: int a = 100000, int b = -200000
Long: Long data type is a 64-bit signed integer number. The negative
numbers are expressed in two‘s complement form. The range accepted by
long is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 i.e. -263 to
263 -1. This type is used when a wider range than int is needed. Default value
stored in long variable is 0.
Ex: long a = 100000L, long b = -200000L
Floating point data types: Floating point data types are used to store numbers
that have a fractional part. Floating point data types are classified into two
types. They are
1. float
2. double
float: float data type is a single-precision 32-bit floating point number. float
is mainly used to save memory in large arrays of floating point numbers.
Default value stored in float variable is 0.0
Ex: float f1 = 234.5f
double: double data type is a double-precision 64-bit floating point number.
This data type is generally used as the default data type for fractional
numbers. Default value stored in double variable is 0.0
Ex: double d1 = 123.4
Non-Numeric data types: In Java, two of the eight primitive data types are
non-numeric types. Non-Numeric data types are classified into two types.
They are
1. char data types
2. boolean data types
char: char data type is a single 16-bit Unicode character. The range accepted
by char is 0 to 65,535 i.e. 0 to 216-1. Char data type is used to store any
character.
Ex: char letterA = 'A'
boolean: boolean data type represents one bit of information. There are only
two possible values i.e. true and false. This data type is used for simple flags
that track true/false conditions. Default value is false
Ex: boolean found = true
Non-Primitive Data Types: The non-primitive data types are also commonly
referred as derived data types. Non-Primitive data types are classified into
three types. They are
1. Classes
2. Arrays
3. Interfaces
Classes: Class is an encapsulation of data along with its method. It is a user
defined data type. It acts as an template for creating objects.
Arrays: An array is a group of similar data items referred to by a common
name.
Interfaces: Interfaces are syntactically similar to classes, but they lack in
instance variables, and their methods are declared without any body.
Here, type is one of Java’s atomic types, or the name of a class or interface.
The identifier is the name of the variable. The variable can be initialized by
specifying an equal sign and a value.
Examples
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing d and f.
Constants: Constants in Java are called Literals. Literal can be any number,
text, or other information that represents a value. Depending on the value
the literals are classified into 4 types. They are
1. Integer Literal
2. Floating-Point Literals
3. Boolean Literal
4. Character Literals
5. String Literals
Integer Literals: Any whole number is an integer literal. Examples are 1, 2, 3,
and 42. These are all decimal values, meaning they are describing a base 10
number. There are two other bases which can be used in integer literals, octal
(base eight) and hexadecimal (base 16). Octal values are denoted in Java by
a leading zero. Normal decimal numbers cannot have a leading zero. Thus,
the valid value 09 will produce an error from the compiler, since 9 is outside
of octal‘s 0 to 7 range. A more common base for numbers used by
programmers is hexadecimal. A hexadecimal constant with a leading zero-x,
(0x or 0X). The range of a hexadecimal digit is 0 to 15, so A through F (or a
through f ) are substituted for 10 through 15.
Floating-Point Literals: Floating-point numbers represent decimal values with
a fractional component. They can be expressed in either standard or scientific
notation. Standard notation consists of a whole number component followed
by a decimal point followed by a fractional component. For example, 2.0,
3.14159, and 0.6667 represent valid standard-notation floating-point
numbers. Scientific notation uses a standard-notation, floating-point
number plus a suffix that specifies a power of 10 by which the number is to
be multiplied. The exponent is indicated by an E or e followed by a decimal
number, which can be positive or negative. Examples include 6.022E23,
314159E–05, and 2e+100. Floating-point literals in Java default to double
precision. To specify a float literal, an F or f must be append to the constant.
Boolean Literals: Boolean literals are simple. There are only two logical values
that a boolean value can have, true and false. The values of true and false do
not convert into any numerical representation. The true literal in Java does
not equal 1, nor does the false literal equal 0. In Java, they can only be
assigned to variables declared as boolean, or used in expressions with
Boolean operators.
Character Literals: Characters in Java use the Unicode character set. They are
16-bit values that can be converted into integers and manipulated with the
integer operators, such as the addition and subtraction operators. A literal
character is represented inside a pair of single quotes. Ex: ‘a‘, ‘z‘, and ‘@‘.
String Literals: String literals in Java are a sequence of characters enclosed
between a pair of double quotes. Ex: “Hello World”.
Scope and life time of variables: Java allows variables to be declared within
any block. A block is begun with an opening curly brace and ended by a
closing curly brace. A block defines a scope. Thus, each time you start a new
block, you are creating a new scope. A scope determines what objects are
visible to other parts of the program. It also determines the lifetime of those
objects.
Scopes can be nested. In a nested scope, the outer scope encloses the
inner scope. This means that objects declared in the outer scope will be
visible to code within the inner scope. However, the reverse is not true.
Objects declared within the inner scope will not be visible outside it.
// Demonstrate block scope.
class Scope
{
public static void main(String args[])
{
int x; // known to all code within main
x = 10;
if(x == 10)
{ // start new scope
int y = 20; // known only to this block
System.out.println("x and y: " + x + " " + y); // x and y both known
x = y * 2;
}
The Assignment Operator: The assignment operator is the single equal sign,
=. It has this general form:
var = expression;
Here, the type of var must be compatible with the type of expression. The
assignment operator allows to create a chain of assignments.
Ex: int x, y, z;
x = y = z = 100; // set x, y, and z to 100
This fragment sets the variables x, y, and z to 100 using a single statement.
This works because the = is an operator that yields the value of the right-
hand expression. Thus, the value of z = 100 is 100, which is then assigned to
y, which in turn is assigned to x. Using a chain of assignments it is an easy
way to set a group of variables to a common value.
The ? Operator: Java includes a special ternary (three-way) operator that can
replace certain types of if-then-else statements. ?. is the ternary operator and
its general form is
expression1 ? expression2 : expression3
Here, expression1 can be any expression that evaluates to a boolean value.
If expression1 is true, then expression2 is evaluated; otherwise, expression3
is evaluated. Both expression2 and expression3 are required to return the
same type, which can‘t be void.
Ex: ratio = denom == 0 ? 0 : num / denom;
Type conversion and casting: In Java two types of conversions take place.
They are
1. Java’s Automatic Conversions
2. Type Casting
Java’s Automatic Conversions: When one type of data is assigned to another
type of variable, an automatic type conversion will take place if the following
two conditions are met. They are
• The two types are compatible.
• The destination type is larger than the source type.
When these two conditions are met, a widening conversion takes place. For
example, the int type is always large enough to hold all valid byte values, so
no explicit cast statement is required. For widening conversions, the numeric
types, including integer and floating-point types, are compatible with each
other. However, there are no automatic conversions from the numeric types
to char or boolean. Also, char and boolean are not compatible with each
other. As mentioned earlier, Java also performs an automatic type conversion
when storing a literal integer constant into variables of type byte, short, long,
or char.
Accepting Input from the Keyboard: There are many ways to read data
from the keyboard. They are
1. InputStreamReader
2. Console
3. Scanner
4. DataInputStream etc.
InputStreamReader class: InputStreamReader class can be used to read data
from keyboard.It performs two tasks. They are
1. connects to input stream of keyboard
2. converts the byte-oriented stream into character-oriented stream
BufferedReader class: BufferedReader class can be used to read data line by
line by readLine() method. Example of reading data from keyboard by
InputStreamReader and BufferdReader class. In this example, we are
connecting the BufferedReader stream with the InputStreamReader stream
for reading the line by line data from the keyboard.
// Reading data from the keyboard with the InputStreamReader
import java.io.*;
class keyBoardRead
{
public static void main(String args[])throws Exception
{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}
{
public static void main(String[] args)
{
// using print()
// all are printed in the
// same line
System.out.print("GfG! ");
System.out.print("GfG! ");
System.out.print("GfG! ");
}
}
println(): This method in Java is also used to display a text on the console. It
prints the text on the console and the cursor moves to the start of the next
line at the console. The next printing takes place from the next line.
// Java code to illustrate println()
import java.io.*;
class Demo_println
{
public static void main(String[] args)
{
// using println()
// all are printed on
// separate line
System.out.println("GfG! ");
System.out.println("GfG! ");
System.out.println("GfG! ");
}
}
printf(): printf() is the easiest of all methods as this is similar to printf in C.
Note that System.out.print() and System.out.println() take a single argument,
but printf() may take multiple arguments. This is used to format the output
in Java.
// A Java program to demonstrate working of printf() in Java
class JavaFormatter1
{
public static void main(String args[])
{
int x = 100;
System.out.printf( "Printing simple" + " integer: x = %d\n", x);
}
}
statements allow the program to jump to the required statement within the
block.
if(num<0)
num=-num;
System.out.println("The absolute value of "+num1+" is "+num);
}
}
if-else Statement: The if-else statement is an extension of simple if statement.
If-else statement initially tests the condition. If the condition is true it
executes the true-statement-block and moves to the next statement. If the
condition is false it executes the false-statement-block and moves to the next
statement. In any case , either true-statement-block or false-statement-block
is executed and moves to the next statement.
}
}
Nested – if: When one if statement is nested in another if statement then it
is called as nested if statement.
max = num1;
else
max = num3;
else
if(num2 > num3)
max = num2;
else
max = num3;
System.out.println(“Maximum number is "+max);
}
}
else-if ladder : When one if statement is added in the else part of another if
statement then it is called as else – if ladder statement.
else
if(marks>= 60)
System.out.println("First Class");
else
if(marks>= 50)
System.out.println("Second Class");
else
if(marks>= 35)
System.out.println("Third Class");
else
System.out.println("Fail");
}
}
switch statement: The switch statement is a multiway branch statement. It
provides an easy way to select one of the option among several options. It
often provides a better alternative than a large series of if-else-if statements.
Here is the general form of a switch statement:
switch (expression)
{
case value1: statement1-block;
break;
case value2: statement2-block;
break;
...
case valueN: statementN-block;
break;
default: defaultstatement-block;
}
The expression must be of type byte, short, int, or char. Each of the values
specified in the case statements must be of a type compatible with the
expression. Each case value must be a unique literal that is, it must be a
constant, not a variable. Duplicate case values are not allowed.
The switch statement works like this: The value of the expression is
compared with each of the literal values in the case statements. If a match is
found, the code sequence following that case statement is executed. If none
of the constants matches the value of the expression, then the default
}
}
do-while: The do-while loop is an exit controlled loop. The do-while loop
always executes its body at least once, because its conditional expression is
at the bottom of the loop. Its general form is
do
{
// body of loop
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and
then evaluates the conditional expression. If this expression is true, the loop
will repeat. Otherwise, the loop terminates.
// Program to print the reverse of a given number
import java.util.Scanner;
class RevNum
{
public static void main(String args[])
{
int num,rev,rem ;
Scanner input = new Scanner(System.in);
System.out.print("Enter any integer number :");
num=input.nextInt();
int num1=num;
rev=0;
do
{
rem = num % 10;
rev=rev*10+rem;
num = num /10;
}while(num!=0);
System.out.print("The reverse number of " + num1+"is "+rev);
}
}
for: Beginning with JDK 5, there are two forms of the for loop. The first is the
traditional form that has been in use since the original version of Java. The
second is the new one i.e. for-each form.
For loop: For loop executes group of Java statements as long as the boolean
condition evaluates to true. For loop combines three elements which we
generally use: initialization statement, boolean expression and increment or
decrement statement. Here is the general form of the traditional for
statement:
for(initialization; condition; iteration)
{
// body
}
If only one statement is being repeated, there is no need for the curly
braces.
The for loop operates as follows. When the loop first starts, the initialization
portion of the loop is executed. Generally, this is an expression that sets the
value of the loop control variable, which acts as a counter that controls the
loop. It is important to understand that the initialization expression is only
executed once. Next, condition is evaluated. This must be a Boolean
expression. It usually tests the loop control variable against a target value. If
this expression is true, then the body of the loop is executed. If it is false, the
loop terminates. Next, the iteration portion of the loop is executed. This is
usually an expression that increments or decrements the loop control
variable. The loop then iterates, first evaluating the conditional expression,
then executing the body of the loop, and then executing the iteration
expression with each pass. This process repeats until the controlling
expression is false.
// Program to print factorial of a number
import java.util.Scanner;
class ReturnFact
{
public static void main(String args[])
{
int n,i ;
long f=1;
Scanner input = new Scanner(System.in);
System.out.print("Enter any number: ");
n=input.nextInt();
for(i=1;i<=n;i++)
f*=i;
System.out.println("Factorial of "+n+" is "+f);
}
}
For-Each : A for each style loop is designed to cycle through a collection of
objects, such as an array, in strictly sequential fashion, from start to finish.
The advantage of this approach is that no new keyword is required, and no
preexisting code is broken. The for-each style of for is also referred to as the
enhanced for loop.
The general form of the for-each version of the for is shown here:
for(type itr-var : collection)
statement-block
Here, type specifies the type and itr-var specifies the name of an iteration
variable that will receive the elements from a collection, one at a time, from
beginning to end.
// Program to read numbers using for and print them using for each
import java.util.Scanner;
class ForEachDemo
{
public static void main(String args[])
{
int i, n;
Scanner input = new Scanner(System.in);
System.out.print("Enter how many numbers: ");
n=input.nextInt();
float num[] = new float[n];
System.out.println("Enter "+n+" numbers one by one: ");
for(i=0;i<n;i++)
num[i] = input.nextFloat();
System.out.println(n+" numbers in an array are as follows: ");
for(float number: num)
System.out.println(number);
}
}
Nested Loops: Like all other programming languages, Java allows loops to be
nested. That is, one loop may be inside another. For example, here is a
program that nests for loops:
// Program to sort a given list of numbers
import java.util.*;
public class Sort
{
public static void main(String args[])
{
int n;
Scanner input = new Scanner(System.in);
System.out.println("Enter how many numbers: ");
n=input.nextInt();
System.out.println("Enter "+n+" numbers one by one ");
float number[]= new float[n];
for(int i=0;i<n;i++)
number[i]=input.nextFloat();
for(int i=0;i<n-1;i++)
for(int j=0;j<n-i-1;j++)
if(number[j]>number[j+1])
{
float temp=number[j];
number[j]=number[j+1];
number[j+1]=temp;
}
System.out.println("sorted list is as follows");
for(int i=0;i<n;i++)
System.out.print(" "+number[i]);
}
}
used to exit a loop. Third, it can be used as a civilized form of goto. The last
two uses are explained here.
// Program to check prime number using break
import java.util.Scanner;
class PrimeChk
{
public static void main(String args[])
{
int i,n;
Scanner input = new Scanner(System.in);
System.out.println("Enter any number: ");
n=input.nextInt();
for(i=2;i<=n/2;i++)
if(n%i==0)
break;
if(i>n/2)
System.out.println(n+" is Prime Number");
else
System.out.println(n+" is not Prime Number");
}
}
Labelled break : The labelled break statement can also be used to construct
a civilized form of the goto statement. The general form of the labeled break
statement is shown here.
break label;
Most often, label is the name of a label that identifies a block of code. But
you cannot use break to transfer control out of a block that does not enclose
the break statement.
// Program to print triangle of stars
import java.util.Scanner;
class BreakStarTri
{
public static void main(String args[])
{
int i,j,n;
Scanner input = new Scanner(System.in);
{
public long fact(int n)
{
int i ;
long f=1;
for(i=1;i<=n;i++)
f*=i;
return f;
}
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.print("Enter any number: ");
int n1=input.nextInt();
ReturnFact rf = new ReturnFact();
System.out.println("Factorial of "+n1+" is "+rf.fact(n1));
}
}
{
int i,j,k,m, n,p,q;
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of matrix A: ");
m = input.nextInt();
n=input.nextInt();
System.out.println("Enter the size of matrix B: ");
p = input.nextInt();
q=input.nextInt();
if((m==p) &&(n==q))
{
float a[][] = new float[m][n];
float b[][]=new float[p][q];
float c[][]=new float[m][q];
System.out.println("Enter " + m * n +"numbers of matrix A: ");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
a[i][j] = input.nextFloat();
System.out.println("Enter " + p * q +"numbers of matrix B: ");
for (i = 0; i < p; i++)
for (j = 0; j < q; j++)
b[i][j] = input.nextFloat();
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
c[i][j]=a[i][j]+b[i][j];
System.out.println("The resultant matrix after addition is: " );
for (i = 0; i < m; i++)
{
for (j = 0; j < q; j++)
System.out.print(c[i][j]+" ");
System.out.println();
}
}
else
System.out.println("Matrix addition not possible");
}
}
Krishnaveni Degree College: Narasaraopet Page No.: 41
Object Oriented Programming using Java UNIT - II
int num1=Integer.parseInt(args[0]);
int num2=Integer.parseInt(args[1]);
int sum = num1 +num2;
System.out.println("Sum = "+sum);
}
}
Ex:
String s = new String();
S will be created with no characters in it.
To create a String initialized by an array of characters, use the constructor
shown here:
String(char chars[ ])
Here is an example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
This constructor initializes s with the string "abc".
To specify a subrange of a character array as an initializer using the following
constructor:
String(char chars[ ], int startIndex, int numChars)
Here, startIndex specifies the index at which the subrange begins, and
numChars specifies the number of characters to use. Here is an example:
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
This initializes s with the characters “cde”.
To construct a String object that contains the same character sequence as
another String object using this constructor:
String(String strObj)
Here, strObj is a String object.
String snew = new String(s);
This initializes snew with the characters “cde” that are contained in strng s.
String Class Methods: The String class has a set of built-in methods that can
be used on strings. They are
Method Description Example Result
charAt() Returns the String s1 = new ‘e’
character at the String("Hello");
specified index s1.charAt(1)
(position)
compareTo() Compares two String s1 = new 4
strings String("Hello");
lexicographically String s2 =
new String("Hai");
int
res=s1.compareTo(s2);
concat() Appends a String s1 = "one"; “Onetwo”
string to the end String s2 =
of another string s1.concat("two");
length() Returns the String s1 = "one"; 3
length of a Len=s1.length()
specified string
split() Splits a string Pattern pat = “one”
into an array of Pattern.compile("[ ,.!]"); “two”
substrings String strs[] = “alpha9”
pat.split("one “12”
two,alpha9 12!done."); “done”
substring() Returns a new String s1 = "Hello"; “He”
string which is
the substring of String result =
a specified s1.substring(0, 2);
string
toLowerCase() Converts a S1.toLowerCase() “hello”
string to lower
case letters
Krishnaveni Degree College: Narasaraopet Page No.: 44
Object Oriented Programming using Java UNIT - II
Classes: - Class is the logical construct upon which the entire Java language
is built. A class is the basic building block of an object-oriented language
such as Java. It is a template that describes the data and behaviour
associated with instances of that class.
Every class in Java can be composed of the following elements:
{
// body of method
}
}
Ex 1:
class Stud1
{
int studno;
String name;
}
Ex2:
class StudDet
{
int studno;
String name;
void getDet()
{
-----
}
void printDet()
{
------
}
}
class Box
{
double width;
double height;
double depth;
}
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
The first line declares mybox as a reference to an object of type Box. After
this line executes, mybox contains the value null, which indicates that it does
not yet point to an actual object. Any attempt to use mybox at this point will
result in a compile-time error. The next line allocates an actual object and
assigns a reference to it to mybox.
After the second line executes, use mybox to refer to the Box object. But in
reality, mybox simply holds the memory address of the actual Box object. The
two step process of Decaling an object can be combined as
Box mybox = new Box();
// Program to demonstrate class with only data members
import java.util.*;
class Stud1
{
int studno;
String name;
}
public class StudDetails
{
public static void main(String args[])
{
Stud1 s1=new Stud1();
Scanner input = new Scanner(System.in);
System.out.println("Enter Student no and name : ");
s1.studno = input.nextInt();
s1.name = input.next();
System.out.println("The Student Details are as follows : ");
System.out.println("Roll Number : "+s1.studno);
System.out.println("Name : "+s1.name);
}
}
Methods: Classes usually consist of two things. They are instance variables
and methods. The general form of a method is
type name(parameter-list)
{
// body of method
}
Here, type specifies the type of data returned by the method. This can be any
valid type, including class types that are already created. If the method does
not return a value, its return type must be void. The name of the method can
be any legal identifier other than those already used by other items within
the current scope. The parameter-list is a sequence of type and identifier
pairs separated by commas. Parameters are essentially variables that receive
the value of the arguments passed to the method when it is called. If the
method has no parameters, then the parameter list will be empty.
// Program to use class that contains data members and methods
import java.util.*;
class StudDet
{
private int studno;
private String name;
void getDet()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter Student no and name : ");
studno = input.nextInt();
name = input.next();
}
void printDet()
{
System.out.println("The Student Details are as follows : ");
System.out.println("Roll Number : "+studno);
System.out.println("Name : "+name);
}
}
public class Stud
{
public static void main(String args[])
{
StudDet s1=new StudDet();
s1.getDet();
s1.printDet();
}
}
Parameter Passing: In general, there are two ways to pass argument to a
method. They are
1. call-by-value
2. call-by-reference
call-by-value: call-by-value approach copies the value of an argument into
the formal parameter of the method. Therefore, changes made to the
parameter in the called method have no effect on the argument in the calling
method. When you pass a primitive type to a method, it is call by value.
call-by-reference: In call-by-reference approach, a reference to an argument
(not the value of the argument) is passed to the parameter. Inside the called
method, this reference is used to access the actual argument specified in the
call. This means that changes made to the parameter in the called method
will affect the argument in the calling method. When you pass objects to a
method, it is call by reference.
// Program to demonstrate call by value technique.
import java.util.Scanner;
class Test
{
void swap(float i, float j)
{
float temp;
temp=i;
i=j;
j=temp;
}
}
class CallByValue
{
float a , b;
public static void main(String args[])
{
Test ob = new Test();
CallByValue cbr = new CallByValue();
Scanner input = new Scanner(System.in);
System.out.println("Enter any two numbers : ");
cbr.a = input.nextFloat();
cbr.b = input.nextFloat();
System.out.println("a and b before swaping: " + cbr.a + " " + cbr.b);
ob.swap(cbr.a, cbr.b);
System.out.println("a and b after swaping: " + cbr.a + " " + cbr.b);
}
}
Static Fields and Methods : Class variables and methods will be used
independently of any object of that class. These are called as static variables
and methods.
static variable:
It is a variable which belongs to the class and not to object(instance)
Static variables are initialized only once , at the start of the execution .
These variables will be initialized first, before the initialization of any
instance variables
A single copy to be shared by all instances of the class
A static variable can be accessed directly by the class name and
doesn‘t need any object
Syntax : <class-name>.<variable-name>
void printDet()
{
System.out.println("The Student Details are as follows : ");
System.out.println("Roll Number : "+studno);
System.out.println("Name : "+name);
System.out.println("Number of Objects Created : "+cnt);
}
}
public class StudentStatic
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter Student no and name : ");
int sno = input.nextInt();
String sname = input.next();
StudDet s1=new StudDet();
s1.getData(sno,sname);
s1.printDet();
System.out.println("Enter Student no and name : ");
sno = input.nextInt();
sname = input.next();
StudDet s2=new StudDet();
s2.getData(sno,sname);
s2.printDet();
}
}
Static Method:
It is a method which belongs to the class and not to the
object(instance)
A static method can access only static data. It can not access non-static
data (instance variables)
A static method can call only other static methods and can not call a
non-static method from it.
A static method can be accessed directly by the class name and doesn‘t
need any object
Syntax : <class-name>.<method-name>
A static method cannot refer to "this" or "super" keywords in anyway
s1.getDet(sno,sname);
s1.printDet();
System.out.println("Enter Student no and name : ");
sno = input.nextInt();
sname = input.next();
StudDet5 s2=new StudDet5();
s2.getDet(sno,sname);
s2.printDet();
StudDet5.printCnt();
}
}
Static Block: Static block is mostly used for changing the default values of
static variables. This block gets executed when the class is loaded in the
memory. A class can have multiple Static blocks, which will execute in the
same sequence in which they have been written into the program.
class StaticBlock
{
static int num;
static String mystr;
static
{
num = 97;
mystr = "Static Block in Java";
}
public static void main(String args[])
{
System.out.println("Value of num="+num);
System.out.println("Value of mystr="+mystr);
}
}
Java "THIS" Keyword: Sometimes a method will need to refer to the object
that invoked it. To allow this, Java defines the this keyword. this can be used
inside any method to refer to the current object. That is, this is always a
reference to the object on which the method was invoked. when a local
variable has the same name as an instance variable, the local variable hides
the instance variable. To avoid this problem this keyword can be used.
Keyword 'THIS' in Java is a reference variable that refers to the current object.
The various usage of keyword Java 'THIS' in Java is as per the below.
It can be used to refer current class instance variable
It can be used to invoke or initiate current class constructor
It can be passed as an argument in the method call
It can be passed as argument in the constructor call
It can be used to return the current class instance
Types of Inheritance: Depending upon how many super classes are used
to derive subclasses and how many sub classes are derived the inheritance
is classified into 4 categories. They are
1). Single Inheritance
2) Multilevel Inheritance
3) Hierarchical Inheritance
4). Multiple Inheritance
5) Hybrid Inheritence
Single Inheritance: Inheritance which uses one super class to derive new sub
class is said to be Single Inheritance.
Multilevel Inheritance: Inheritance which uses one derived class as super
class to derive new subclass is said to be Multilevel Inheritance.
Hierarchical Inheritance: Inheritance which uses one super class to derive
more than one sub class is said to be Hierarchical Inheritance.
Multiple Inheritance: Inheritance which uses more than one super class to
derive new subclass is said to be Multiple Inheritance. Java doesnot directly
implement multiple interfaces. It can be done by using interfaces.
Hierarchical Inheritance: Inheritance which uses one super class to derive
more than one sub class is said to be Hierarchical Inheritance.
Hybrid Inheritnce: In Java, the hybrid inheritance is the composition of two or
more types of inheritance. The above hybrid inheritance is the composition
of Hierarchical and Multiple Inheritence.
}
class BedRoom extends Room
{
float height;
void getlbh(float l, float b, float h)
{
getlb(l,b);
height=h;
}
float volume()
{
return length*breadth*height;
}
}
public class SingleInher
{
public static void main(String args[])
{
Scanner input1 = new Scanner(System.in);
System.out.print("Enter the length of the room: ");
float l1=input1.nextFloat();
System.out.print("Enter the breadth of the room: ");
float b1=input1.nextFloat();
System.out.print("Enter the height of the room: ");
float h1=input1.nextFloat();
BedRoom room1 = new BedRoom();
room1.getlbh(l1,b1,h1);
float area1 = room1.area();
float vol1=room1.volume();
System.out.println("Area of the room: "+area1);
System.out.println("Volume of the room: "+vol1);
}
}
// Program to demonstrate Hirarchical Inheritance
import java.util.Scanner;
class Figure
{
double dim1;
}
class Circle extends Figure
{
void getdim()
{
Scanner input = new Scanner(System.in);
System.out.print("Enter any radius: ");
dim1=input.nextDouble();
}
double area()
{
return dim1*dim1*3.1415;
}
}
class Rectangle extends Figure
{
double dim2;
void getdim()
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the length and breadth of the Rectangle: ");
dim1=input.nextDouble();
dim2=input.nextDouble();
}
double area()
{
return dim1*dim2;
}
}
class Triangle extends Figure
{
double dim2,dim3;
void getdim()
{
{
Scanner input = new Scanner(System.in);
System.out.print("Enter any radius: ");
dim1=input.nextDouble();
}
double area()
{
return dim1*dim1*3.1415;
}
}
class Rec extends Cir
{
double dim2;
void getdim()
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the length and breadth: ");
dim1=input.nextDouble();
dim2=input.nextDouble();
}
double area()
{
return dim1*dim2;
}
}
public class MultiLevelInher
{
public static void main(String args[])
{
Circle c = new Circle();
c.getdim();
System.out.println("Area of circle is " + c.area());
Rectangle r = new Rectangle();
r.getdim();
System.out.println("Area of rectangle is " + r.area());
}
}
}
class Rec2 extends Cir2
{
double dim2;
Rec2()
{
super();
dim2=input.nextDouble();
}
double area()
{
return dim1*dim2;
}
}
public class SuperEx2
{
public static void main(String args[])
{
System.out.print("Enter any radius: ");
Cir2 c = new Cir2();
System.out.println("Area of circle is " + c.area());
System.out.print("Enter the length and breadth of rectangle : ");
Rec2 r = new Rec2();
System.out.println("Area of rectangle is " + r.area());
}
}
//Program to use super to refer immediate parent class method.
import java.util.Scanner;
class Cir1
{
Scanner input = new Scanner(System.in);
double dim1;
void getdim()
{
dim1=input.nextDouble();
}
double area()
{
return dim1*dim1*3.1415;
}
}
class Rec1 extends Cir1
{
double dim2;
void getdim()
{
super.getdim();
dim2=input.nextDouble();
}
double area()
{
return dim1*dim2;
}
}
public class SuperEx
{
public static void main(String args[])
{
Circle c = new Circle();
System.out.print("Enter any radius: ");
c.getdim();
System.out.println("Area of circle is " + c.area());
Rectangle r = new Rectangle();
System.out.print("Enter the length and breadth: ");
r.getdim();
System.out.println("Area of rectangle is " + r.area());
}
}
Final Keyword In Java: The final keyword in java is used to restrict the user
for preventing its contents from being modified.. The java final keyword can
be used with the following components. They are
1. variable
2. method
3. class
The meaning of final varies from context to context, but the essential idea is
the same.
A final variable becomes a constant and its value can not be changed.
A final method may not be overridden.
A final class can not be inherited
Object Class: t is a superclass of all other classes. Object defines the methods
which are available to every object.
Method Description
boolean equals(Object object) Returns true if the invoking
object is equivalent to object.
final Class<?>getClass() Obtains the class object that
describes the invoking object.
int hashCode( ) Returns the hash code associated
with the invoking object.
}
}
class Rectangle extends Circle
{
double dim2;
void getdim()
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the length and breadth of the Rectangle: ");
dim1=input.nextDouble();
dim2=input.nextDouble();
}
double area()
{
return dim1*dim2;
}
}
public class MethodOverrideEx
{
public static void main(String args[])
{
Circle c = new Circle();
c.getdim();
System.out.println("Area of circle is " + c.area());
Rectangle r = new Rectangle();
r.getdim();
System.out.println("Area of rectangle is " + r.area());
}
}
Abstract class: A class which contains the abstract keyword in its declaration
is known as abstract class. Abstract classes may or may not contain abstract
methods, i.e., methods without body ( public void get(); ) But, if a class has at
least one abstract method, then the class must be declared abstract. If a class
is declared abstract, it cannot be instantiated i.e object cant be created for
}
}
class AbstractAreas
{
public static void main(String args[])
{
Rectang r = new Rectang(9, 5);
System.out.println("Area of Rectangle is " + r.area());
Triang t = new Triang(10, 8);
System.out.println("Area of triangle is " + t.area());
}
}
Interfaces VS Abstract classes: Abstract class and interface both are used
to achieve abstraction where we can declare the abstract methods. Abstract
Krishnaveni Degree College: Narasaraopet Page No.: 79
Object Oriented Programming using Java UNIT - III
class and interface both can't be instantiated. But there are many differences
between abstract class and interface that are given below.
S.No Interface Abstract class
1) Interface can have only abstract Abstract class can have abstract
methods. Since Java 8, it can and non-abstract methods.
have default and static methods
also.
2) Interface supports multiple Abstract class doesn't support
inheritance. multiple inheritance.
3) Interface has only static and final Abstract class can have final,
variables. non-final, static and non-static
variables.
4) Interface can't provide the Abstract class can provide the
implementation of abstract class. implementation of interface.
by the interface. The general form of a class that includes the implements
clause looks like this:
class classname [extends superclass] [implements interface [,interface...]]
{
// class-body
}
If a class implements more than one interface, the interfaces are separated
with a comma. If a class implements two interfaces that declare the same
method, then the same method will be used by clients of either interface. The
methods that implement an interface must be declared public. Also, the type
signature of the implementing method must match exactly the type
signature specified in the interface definition.
// Java program to implement interface
import java.io.*;
interface In1
{
final int a = 10;
void display();
}
class TestClass implements In1
{
public void display()
{
System.out.println("Geek");
}
public static void main(String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(t.a);
}
}
Interfaces Can Be Extended: One interface can inherit another by use of the
keyword extends. The syntax is the same as for inheriting classes. When a
class implements an interface that inherits another interface, it must provide
implementations for all methods defined within the interface inheritance
chain. // Program to demonstrate one interface extending another interface.
import java.util.Scanner;
interface DimInter2
{
void getDim();
}
interface AreaInter2 extends DimInter2
{
double areas();
}
class ExtendInter implements AreaInter2
{
double dim1;
double dim2;
public void getDim()
{
Scanner input = new Scanner(System.in);
System.out.print("Enter any two dimensions: ");
dim1=input.nextDouble();
dim2=input.nextDouble();
}
public double areas()
{
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
public static void main(String args[])
{
ExtendInter r = new ExtendInter();
r.getDim();
System.out.println("Area is " + r.areas());
}
}
Packages: Packages are containers for classes that are used to keep the class
name space compartmentalized.
within that file will belong to the specified package. The package statement
defines a name space in which classes are stored. If the package statement
is omitted, the class names are put into the default package, which has no
name. The general form of the package statement is
Syntax: package pkg;
Here, pkg is the name of the package.
Ex: package MyPackage;
The above statement creates a package called MyPackage.
creating and accessing a package: Java uses file system directories to store
packages. For example, the .class files for any classes to be part of MyPackage
must be stored in a directory called MyPackage. Remember the directory
name must match the package name exactly. More than one file can include
the same package statement. The package statement simply specifies to
which package the classes defined in a file belong. To create a hierarchy of
packages simply separate each package name from the one above it by use
of a period. The general form of a multileveled package statement is
Syntax: package pkg1[.pkg2[.pkg3]];
Ex: package java.awt.image;
A package hierarchy must be reflected in the file system of the computer. For
example, a package declared as
package java.awt.image;
needs to be stored in java\awt\image in a Windows environment. Be sure to
choose your package names carefully. Package name cannot be renamed
without renaming the directory in which the classes are stored.
// Program to demonstrate Simple Package
package MyPack1;
import java.util.Scanner;
class Balance
{
String name;
double bal;
Balance(String n, double b)
{
name = n;
bal = b;
}
void show()
{
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
class AccountBalance1
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the name and balance: ");
String name=input.next();
float bal =input.nextFloat();
Balance current = new Balance(name, bal);
current.show();
}
}
To compile java program which contains package statement
javac –d . demo.java
To
java -cp . MyPack1/AccountBalance1
Built-in Exceptions: Built-in exceptions are the exceptions that are available
in Java libraries. These exceptions are suitable to explain certain error
situations.
User-Defined Exceptions: Sometimes, the built-in exceptions in Java are not
able to describe a certain situation. In such cases, the user can also create
exceptions which are called ‘user-defined Exceptions’. The following steps
are followed for the creation of a user-defined Exception.
1. The user should create an exception class as a subclass of the Exception
class. Since all the exceptions are subclasses of the Exception class, the
user should also make his class a subclass of it. This is done as:
class MyException extends Exception
2. We can write a default constructor in his own exception class.
MyException(){}
3. We can also create a parameterized constructor with a string as a
parameter. We can use this to store exception details. We can call the
superclass(Exception) constructor from this and send the string there.
MyException(String str)
{
super(str);
}
To raise an exception of a user-defined type, we need to create an object to
his exception class and throw it using the throw clause, as:
MyException me = new MyException(“Exception details”);
throw me;
from the Throwable class. Refer to the diagram given below to understand
the hierarchy of exceptions in Java along with their category of checked and
unchecked exceptions.
The exception handling mechanism should perform the following tasks. They
are
The above tasks are divided into segments., one to detect errors and throw
exceptions and the other to catch exceptions and to take appropriate actions.
The pictorial representation is shown below
try Block: The try block contains a block of program statements within which
an exception might occur. A try block is always followed by a catch block,
which handles the exception that occurs in associated try block. Syntax of try
block
try{
}
System.out.println("I'm out of try-catch block in Java.");
y=a/(b+c);
System.out.println("y=”+y ;
}
}
OUTPUT:
Error: Don't divide a number by zero
I'm out of try-catch block in Java.
y=1
Multiple catch blocks in Java: A try block can have any number of catch
blocks.
Syntax
try
{
// Protected code
}
catch(ExceptionType1 e1)
{
// Catch block of error e1
}
catch(ExceptionType2 e2)
{
// Catch block of error e2
}
catch(ExceptionType3 e3)
{
// Catch block of error e3
}
1. A catch block that is written for catching the class Exception can catch all
other exceptions.
Syntax:
catch(Exception e){
//This catch block catches all the exceptions
}
System.out.println("y="+y);
}
}
OUTPUT:
Division by Zero
exceptioon:java.lang.ArithmeticException: / by zero
y=2
Nested try catch: The try catch blocks can be nested. One try-catch block
can be present in the another try’s body. This is called Nesting of try catch
blocks. Each time a try block does not have a catch handler for a particular
exception, the parent try block’s catch handlers are inspected for a match. If
no catch block matches, then the java run-time system will handle the
exception.
//Program to demonstrate an example of nested Try catch in Java
class Example1
{
public static void main(String args[])
{
int a[] = {5,5 };
int x,y,z;
try
{
try
{
x=a[0]/(a[1]-a[2]);
System.out.println("x="+x);
System.out.println("Inner Try block message");
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Array elements out of bounds");
}
System.out.println("I am out of inner try-catch block ");
y=a[0]/(a[1]-a[0]);
System.out.println("y="+y);
System.out.println("Outer Try block message");
}
catch (ArithmeticException e)
{
System.out.println("Error: Don't divide a number by zero");
}
System.out.println("I am out of outer try-catch block");
z=a[0]/(a[0]+a[1]);
System.out.println("z="+z);
}
}
OUTPUT:
Array elements out of bounds
I am out of inner try-catch block
Error: Don't divide a number by zero
I am out of outer try-catch block
z=0
User defined exception in java: User defined exceptions in java are also
known as Custom exceptions. Most of the times when we are developing
an application in java, we often feel a need to create and throw our own
exceptions. These exceptions are known as User defined or Custom
exceptions.
//Program to demonstate user defined exception
class MyException extends Exception
{
public MyException(String s)
{
super(s);
}
}
class CustomException
{
public static void main(String args[])
{
int x=5, y=1000;
try
{
float z = (float)x/(float)y;
if (z<0.01)
throw new MyException("Number is too small");
}
catch(MyException e)
{
System.out.println("Hi this is my custom catch block") ;
System.out.println(e) ;
}
}
}
throws clause in the method’s declaration. A throws clause lists the types of
exceptions that a method might throw. All other exceptions that a method
can throw must be declared in the throws clause. If they are not, a compile-
time error will result.
This is the general form of a method declaration that includes a throws
clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a
method can throw.
//Program to demonstrate checked exceptions
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class FileNotFound_Demo
{
public static void main(String args[]) throws FileNotFoundException
{
File file = new File("C:\\CallByValue.java");
FileReader fr = new FileReader(file);
}
}
//Program to demonstrate checked exceptions
public class Unchecked_Demo
{
public static void main(String args[])
{
int num[] = {1, 2, 3, 4};
System.out.println(num[5]);
}
}
finally: When an exception is thrown we teriminate the method abruptly
without completing it. For example, if a method opens a file upon entry and
closes it upon exit, then you will not want the code that closes the file to be
bypassed by the exception-handling mechanism. The finally keyword is
designed to address this problem. finally creates a block of code that will
be executed after a try/catch block has completed and before the code
following the try/catch block. The finally block will execute whether or not
an exception is thrown. If an exception is thrown, the finally block will
execute even if no catch statement matches the exception. The finally
clause is optional. However, each try statement requires at least one catch
or a finally clause.
try{
//block of statements
}
finally
{
}
Or
try
{
//block of statements
}
catch()
{
}
finally
{
}
// program used to show the use of finally block
public void division(int num1, int num2)
{
try
{
System.out.println(num1/num2);
}
catch(ArithmeticException e)
{
. System.out.println(e);
}
finally
{
Thread life cycle: The life cycle of a thread in Java refers to the various states
of a thread that a thread goes through. The figure below shows multiple
states of the thread t under goes during its lifecycle.
New Thread: When a new thread is created, it is in the new state. When a
thread lies in the new state, its code is yet to be run and hasn’t started to
execute.
Runnable State: A thread that is ready to run is moved to a runnable state. In
this state, a thread might actually be running or it might be ready to run at
any instant of time. It is the responsibility of the thread scheduler to give the
thread, time to run.
Blocked: The thread will be in blocked state when it is trying to acquire a lock
but currently the lock is acquired by the other thread. The thread will move
from the blocked state to runnable state when it acquires the lock.
Waiting state: The thread will be in waiting state when it calls wait() method
or join() method. It will move to the runnable state when other thread will
notify or that thread will be terminated.
Timed Waiting: A thread lies in a timed waiting state when it calls a method
with a time-out parameter. A thread lies in this state until the timeout is
completed or until a notification is received. For example, when a thread calls
sleep or a conditional wait, it is moved to a timed waiting state.
Terminated State: A thread terminates because of either of the following
reasons:
Because it exits normally. This happens when the code of the thread
has been entirely executed by the program.
Because there occurred some unusual erroneous event, like a
segmentation fault or an unhandled exception.
Creating a Thread: Java defines two ways by which new threads can be
created.
1. By extending the Thread class.
2. By implementing the Runnable interface.
Extending Thread class: A new Thread can be created by a new class that
extends Thread class and create an object of that class. The extending class
must override run() method which is the entry point of new thread.
// Program demonstrating creation of new thread by extending Thread class
class ExtendThread extends Thread
{
ExtendThread(String name)
{
super(name);
}
public void run()
{
System.out.println(this.getName()+" started running..");
}
}
class MyThreadDemo
{
public static void main( String args[] )
{
ExtendThread et = new ExtendThread("New Thread");
et.start();
}
}
Implementing the Runnable Interface: The easiest way to create a thread is
to create a class that implements the runnable interface. After implementing
runnable interface, the class needs to implement the run() method.
// Program demonstrating creation of new thread by implements Runnable
Interface
class RunnableThread implements Runnable
{
String thname;
RunnableThread(String name)
{
thname=name;
}
public void run()
{
System.out.println(thname+" started running..");
}
}
class MyThreadDemo
{
public static void main( String args[] )
{
RunnableThread rt = new RunnableThread("New Thread");
Thread t = new Thread(rt);
t.start();
}
}
}
catch(InterruptedException e)
{
throw new RuntimeException("Thread interrupted..."+e);
}
}
public static void main(String args[])
{
InterruptingThread t1=new InterruptingThread1();
t1.start();
try
{
t1.interrupt();
}
catch(Exception e)
{
System.out.println("Exception handled "+e);}
}
}
Thread Priorities: Thread priorities are used to decide which thread should
be allowed to run first. In theory, higher-priority threads get more CPU time
than lower-priority threads. In practice, the amount of CPU time that a thread
gets often depends on several factors besides its priority. To set a thread’s
priority, the setPriority( ) method is used and obtain the current priority
setting by calling the getPriority( ) method of Thread. The syntax of these
methods are
final void setPriority(int level)
final int getPriority( )
// Program demonstrating Setting and getting priorities of Threads
class MyThread extends Thread
{
MyThread(String name)
{
super(name);
System.out.println("Default Priority of "+this.getName() + ": " +
this.getPriority());
}
public void run()
{
System.out.println(this.getName()+" started running..");
System.out.println("Priority of "+this.getName() + "is set to: " +
this.getPriority());
System.out.println(this.getName() + " exiting.");
}
}
class MyThreadDemo
{
public static void main( String args[] )
{
MyThread et1 = new MyThread("Thread1");
et1.start();
et1.setPriority(10);
MyThread et2 = new MyThread("Thread2");
et2.start();
et2.setPriority(5);
MyThread et3 = new MyThread("Thread3");
et3.start();
et3.setPriority(1);
}
}
method, no other thread can call any other synchronized method on the
same object.
Synchronization of threads in java can be achieved in two ways. They are
1. Synchronized method.
2. Synchronized block.
Both of these ways use the synchronized keyword.
Synchronized method: If any method is prefixed with a word synchronized
then it is known as synchronized method. When a thread invokes a
synchronized method, it automatically calls its implicit monitor for that object
and releases it only when the thread completes its task.
// Program to demonstrate Synchronized method
import java.util.*;
class Reserve extends Thread
{
int available;
int wanted=1;
Reserve(int n)
{
available=n;
}
synchronized public void run()
{
String name= Thread.currentThread().getName();
System.out.println("Total no of seats available="+available);
if(available>=wanted)
{
System.out.println(wanted+ "breath is allocated to "+name);
available--;
}
else
System.out.println(wanted+ "breaths are not available for "+name);
}
}
public class SynMethod
{
public static void main(String args[]) throws Exception
{
int n;
Scanner input = new Scanner(System.in);
System.out.print ("Enter No of seats availalabe for reservation:");
n=input.nextInt();
Reserve obj=new Reserve(n);
Thread t1 =new Thread(obj,"A");
Thread t2 =new Thread(obj,"B");
t1.start();
t2.start();
}
}
Synchronized block: Synchronized block can be used only when part of the
method is to be synchronized. If all the code of a method is placed in the
synchronized block then it will work same as the synchronized method.
Scope of synchronized block is smaller than the method.
// Program to demonstrate Synchronized method
import java.util.*;
class Reserve extends Thread
{
int available;
int wanted=1;
Reserve(int n)
{
available=n;
}
synchronized public void run()
{
String name= Thread.currentThread().getName();
System.out.println("Total no of seats available="+available);
synchronized(this)
{
if(available>=wanted)
{
System.out.println(wanted+ "breath is allocated to "+name);
available--;
}
else
System.out.println(wanted+ "breaths are not available for "+name);
}
}
}
public class SynBlock
{
public static void main(String args[]) throws Exception
{
int n;
Scanner input = new Scanner(System.in);
System.out.print("Enter No of seats availalabe for reservation:");
n=input.nextInt();
Reserve obj=new Reserve(n);
Thread t1 =new Thread(obj,"A");
Thread t2 =new Thread(obj,"B");
t1.start();
t2.start();
}
}
Stream based I/O (java.io): A simple Java program uses variables, arrays or
objects for storing data. This approach works fine for small data. The
problems with this approach are
1. The data is lost when the program is terminated.
2. It is difficult to handle large amounts of data.
The solution to above two problems is to store large data in a file. File stores
the data permanently on a secondary storage device. Java provides a
standard way of reading data from file and writing data to files. The java.io
package contains all classes that are need to perform input and output
operations on files.
A file is a collection of related records on the disk. A record is a group
of logically related fields. A field is a group of characters. Characters in java
are Unicode characters which uses two bytes to store each character. Storing
and managing data on files is known as file processing.
Byte Streams: Byte streams provide a convenient means for handling input
and output of bytes. Byte streams are used while reading or writing binary
data. Byte Stream Classes are divided into InputStream and OutputStream.
These are defined as abstract classes and has several concrete subclasses.
The abstract classes InputStream and OutputStream define several key
methods that the other stream classes implement. Subclasses of InputStream
and OutputStream are
scanner.close();
}
}
File class: The File class in Java is used to handle operations related to files
and directories. It provides methods to create, delete, query, and manipulate
files and directories on the file system.
// Java Program to Demo File Class Usage
import java.io.File;
import java.io.IOException;
public class FileExample
{
public static void main(String[] args)
{
File file = new File("example.txt");
try
{
if (file.createNewFile())
System.out.println("File created: " + file.getName());
else
System.out.println("File already exists.");
System.out.println("Absolute path: " + file.getAbsolutePath());
System.out.println("File size: " + file.length() + " bytes");
}
catch (IOException e)
{
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Console class: In Java, the Console class provides methods for reading input
and writing output directly from the console, which is typically used in
import java.io.*;
class Employee implements Serializable
{
private String name;
private int age;
System.out.println(empFromFile);
}
catch (IOException | ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
Introduction: Java's original graphical user interface (GUI) system was called
the Abstract Window Toolkit (AWT). The main issue with AWT was that it
relied on platform-specific components. This approach led to several
problems. They are
1. Components looked and behaved differently on different platforms.
2. The appearance of components could not be easily changed.
3. Heavyweight components (those using native code) had limitations,
such as always being opaque.
Krishnaveni Degree College: Narasaraopet Page No.: 121
Object Oriented Programming using Java UNIT – V
These problems conflicted with Java's goal of "write once, run anywhere."
Swings was developed to overcome the deficiencies of AWT. It was
introduced in 1997 as part of the Java Foundation Classes (JFC). Swings
allowed more flexible and consistent GUIs in Java.
Event Classes: At the root of the Java event class hierarchy is EventObject,
which is in java.util. It is the superclass for all events. The class AWTEvent,
defined within the java.awt package, is a subclass of EventObject. It is the
superclass (either directly or indirectly) of all AWT-based events used by the
delegation event model.
Main Event Classes in java.awt.event are
1. KeyEvent Generated when input is received from the keyboard.
2. MouseEvent Generated when the mouse is dragged, moved, clicked,
pressed, or released also generated when the mouse enters or exits a
component
The KeyEvent Class: A KeyEvent is generated when keyboard input occurs.
There are three types of key events, which are identified by these integer
constants: KEY_PRESSED, KEY_RELEASED, and KEY_TYPED. The first two
events are generated when any key is pressed or released. The last event
occurs only when a character is generated. Remember, not all keypresses
msg = msg+k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, 20, 40);
}
}
{
showStatus("Mouse Pressed");
repaint();
}
public void mouseReleased(MouseEvent m)
{
showStatus("Mouse Released");
repaint();
}
public void mouseMoved(MouseEvent m)
{
showStatus("Mouse Moved");
repaint();
}
public void mouseDragged(MouseEvent m)
{
showStatus("Mouse Dragged to "+m.getX()+" "+m.getY());
repaint();
}
public void mouseClicked(MouseEvent m)
{
showStatus("Mouse Clicked");
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,20,20);
}
}
Adapter Classes: Java provides a special feature, called an adapter class, that
can simplifies the creation of eventhandlers. An adapter class provides an
empty implementation of all methods in an event listener interface. Adapter
classes are useful when the user want to receive and process only some of
the events that are handled by a particular event listener interface. For such
a case the user can define a new class to act as an event listener by extending
one of the adapter classes and implementing only those events in which user
is interested. The commonly used Adapter Classes along with its equivalent
Listener is given in the table below
Inner Classes: - An inner class is a class defined within another class, or even
within an expression. Inner classes can be used to simplify the code when
using event adapter classes.
// Program to demonstrste key Events using Inner Classes
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
/*< applet code="MyKeyEventsIner" width=300, height=100 > </applet> */
public class MyKeyEventsIner extends Applet
{
String msg="User Typed: ";
public void init()
{
addKeyListener(new MyKeyAdpIn());
}
public void paint(Graphics g)
{
g.drawString(msg,20,30);
}
class MyKeyAdpIn extends KeyAdapter
{
public void keyTyped(KeyEvent ke)
{
showStatus("Key Typed");
msg+=ke.getKeyChar();
repaint();
}
}
}