JAVA (III Sem) Total Notes
JAVA (III Sem) Total Notes
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.
Datatypes in java
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
4.Logical Operator:The Logical Operator is used to form compound conditions by combining two or more
relations.
Java Constants
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:
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( )
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;
}
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
These statements create a two-dimensional array as having different length for each row.
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( );
}
}
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!");
}
}
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.
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( );
}
}
1) Abstract class can have abstract and non- Interface can have only
abstract methods. abstract methods.
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
}
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:
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.
Parallel Multiple processes are executed in a Multiple threads are executed in a parallel
Action parallel fashion. fashion.
Time Process creation is time-consuming. Thread creation is easy and is time savvy.
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.
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.
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.
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.
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: