Java Complete Reference (2023)
Java Complete Reference (2023)
Lecturer Notes
S. No Contents Page No
1 Academic Calendar 2
2 Syllabus , OOPJ COs , PEOs and JNTUA Approved Textbooks and Reference 3-4
Text Books
3 Theory Syllabus 5-8
4 Laboratory Syllabus 8-9
5 Assignment Questions 287-288
6 Old Question Papers (JNTUA-R20) 289-292
Syllabus & OOPJ COs, PEOs and PSOs
Course Code Object Oriented Programming Through Java L T P C
20A05302T (Common to CSE, IT, CSE (AI), CSE (AI & ML) and AI& 3 0 0 3
DS)
Pre-requisite Fundamental Programming Semester III
Course Objectives:
To understand object oriented concepts and problem solving techniques
To obtain knowledge about the principles of inheritance and polymorphism
To implement the concept of packages, interfaces, exception handling and concurrency
mechanism.
To design the GUIs using applets and swing controls.
To understand the Java Database Connectivity Architecture
Course Outcomes (CO):
After completion of the course, students will be able to
Solve real-world problems using OOP techniques.
Apply code reusability through inheritance, packages and interfaces
Solve problems using java collection framework and I/O classes.
Develop applications by using parallel streams for better performance.
Develop applets for web applications.
Build GUIs and handle events generated by user interactions.
Use the JDBC API to access the database
COURSE OUTCOMES (CO) : At the end of the course, the student will be able to :
CO3: Solve problems using java collection framework and I/O classes.
CO4: Develop applications by using parallel streams for better performance and Develop applets for
web applications
CO5: Build GUIs and handle events generated by user interactions and Use the JDBC API to access
the database
PEO III: Ability to understand and analyze engineering issues in a broader perspective with ethical
responsibility towards sustainable development.
PEO IV: To empower the student with the qualities of effective communication, team work, continues learning
attitude, leadership needed for a successful computer professional.
Index
Unit-I
Unit-II
Unit-III
Laboratory Syllabus
S. Exp Name of the experiment Page Date signature
no no No
1 I a) Installation of Java software, Use Eclipse IDE with the various 220-
menus. 221
Write a java program to find prime numbers between 1 to n.
I b) Write a Java program that prints all real solutions to the quadratic 222
equation ax2+bx+c=0
I c) Write a Java application to generate Electricity bills 224
I d) Write a Java program to multiply two given matrices 228
2 II a) Write Java program on use of inheritance, preventing inheritance 230
using final, abstract classes
II b) Write Java program on dynamic binding, differentiating method 233
overloading and overriding
II c) Develop a java application to implement currency converter 235
Java is a high level, object-oriented and a secure and stable programming language but it is not a pure
object-oriented language because it supports primitive data types like int, char etc.
Java is a platform-independent language because it has runtime environment i.e JRE and API.
Here platform means a hardware or software environment in which an application runs.
Java codes are compiled into byte code or machine-independent code.
This byte code is run on JVM (Java Virtual Machine).
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year
1995. James Gosling is known as the father of Java.
Before Java, its name was Oak. Since Oak was already a registered company, so James Gosling and
his team changed the name from Oak to Java.
HISTORY OF JAVA
James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991.
The small team of sun engineers called Green Team.
Originally designed for small, embedded systems in electronic appliances like set-top boxes.
Firstly, it was called "Greentalk" by James Gosling.After that, it was called Oak
Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like U.S.A.,
France, Germany, Romania etc.
In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
Java is an island of Indonesia where first coffee was produced (called java coffee).
Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle
Corporation) and released in 1995.
Application of Java
Java is not only used in softwares but is also widely used in designing hardware
There are more than 930 million JRE downloads each year and 3 billion mobile phones run java.
Following are some other usage of Java :
1. Developing Desktop Applications
2. Web Applications like Linkedin.com, Snapdeal.com etc
3. Mobile Operating System like Android
4. Robotics and games etc.
Following are different types of applications that we can develop using Java:
1. Standalone Applications
The standalone application is also known as Java GUI Applications or Desktop Applications which uses
some standard GUI components such as AWT(Abstract Windowing Toolkit), swing and JavaFX and this
component are deployed to the desktop.
These components have buttons, menu, tables, GUI widget toolkit, 3D graphics etc.
Example: Media player, antivirus, Paint, POS (point of sale) Billing software, etc.
2. Web Applications
Web Applications are the client-server software application which is run by the client.
Servlets, JSP, Spring, hibernate etc. are used for the development of a client-server application.
eCommerce application is also developed in java using eCommerce platform
3. Enterprise Application
4. Mobile Application
5) Secure
When it comes to security, Java is always the first choice.
With java secure features it enable us to develop virus free, temper free system.
6) Multi Threading
Java multithreading feature makes it possible to write program that can do many tasks simultaneously.
Benefit of multithreading is that it utilizes same memory and other resources to execute multiple threads
at the same time, like While typing, grammatical errors are checked along.
7) Portable
Java Byte code can be carried to any platform and no implementation dependent features.
Everything related to storage is predefined, example: size of primitive data types
8) High Performance
Java is an interpreted language, so it will never be as fast as a compiled language like C or C++.
But, Java enables high performance with the use of just-in-time compiler.
9) Distributed
Java is also a distributed language. Programs can be designed to run on computer networks.
Java has a special class library for communicating using TCP/IP protocols.
Creating network connections is very much easy in Java as compared to C/C++.
10. Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on
demand. It also supports functions from its native languages, i.e., C and C++.
Java supports dynamic compilation and automatic memory management (garbage collection).
int nextInt() It is used to scan the next token of the input as an integer.
float nextFloat() It is used to scan the next token of the input as a float.
double nextDouble() It is used to scan the next token of the input as a double.
byte nextByte() It is used to scan the next token of the input as a byte.
boolean nextBoolean() It is used to scan the next token of the input into a boolean value.
long nextLong() It is used to scan the next token of the input as a long.
short nextShort() It is used to scan the next token of the input as a Short.
BigInteger nextBigInteger() It is used to scan the next token of the input as a BigInteger.
BigDecimal nextBigDecimal() It is used to scan the next token of the input as a BigDecimal.
Simple Example
class Ex1
{
int a;
public static void main(String args[])
{
Ex1 e = new Ex1();
e.a = 10;
System.out.println(" number= "+e.a);
}
}
Output: number=10
Difference between Class and Object
Class Object
No memory is allocated at the time of Sufficient memory space will be allocated for all
2
declaration the variables of class at the time of declaration.
Method Declaration
Method Signature:
Every method has a method signature. It is a part of the method declaration.
It includes the method name and parameter list.
Return Type:
Return type is a data type that the method returns.
It may have a primitive data type, object, collection, void, etc.
If the method does not return anything, we use void keyword.
Method Name:
It is a unique name that is used to define the name of a method.
Parameter List:
It is the list of parameters separated by a comma and enclosed in the pair of parentheses.
It contains the data type and variable name.
If the method has no parameter, left the parentheses blank.
Method Body:
It is a part of the method declaration.
It contains all the actions to be performed. It is enclosed within the pair of curly braces.
User-defined Method
Predefined Methods
As the name gives it, predefined methods in Java are the ones that the Java class libraries already define.
This means that they can be called and used anywhere in our program without defining them.
There are many predefined methods, such as length(), sqrt(), max(), and print(), and each of them is
defined inside their respective classes.
Output:
The Square root is : 5
Demo.java
public class Demo
{
public static void main(String[] args)
{
System.out.print("The maximum number is: " + Math.max(9,7)); // using max() method of Math class
}
}
Output: The maximum number is: 9
//Example1
class A
{
int a,b,c;
void sum()
{
a=10;
b=20;
c=a+b;
System.out.println(" c= "+c);
}
}
class B
{
public static void main(String ars[])
{
A e = new A();
e.sum();
}
}
Output: c=30
Methods in Java can also be classified into the following types:
Static Method
Instance Method
Abstract Method
Factory Method
Native method
public int add(int a, int b) //user-defined method because we have not used static keyword
{
s = a+b; //returning the sum
return s;
}
}
Output: The sum is: 25
The method that does not has method body is known as abstract method.
In other words, without an implementation is known as abstract method.
It always declares in the abstract class. It means the class itself must be abstract if it has abstract
method.
To create an abstract method, we use the keyword abstract.
Syntax
abstract void method_name();
Factory method
It is a method that returns an object to the class to which it belongs. All static methods are factory methods.
NumberFormat obj = NumberFormat.getNumberInstance();
Native method
A native method in Java is used to merge the efficiency and functions of C and C++ in the Java
program.
When the Java compiler did not implement or support some function, then, in that case, to increase the
performance of the Java application, the native methods are used.
Constructors
Constructor is a special type of method and Constructor name must be same as its class name
Constructor is used to initialize the object.
constructor is invoked (called) automatically when we create the object creation.
It constructs the values i.e. provides data for the object that is why it is known as constructor.
Rules for creating java constructor
There are basically two rules defined for the constructor.
Constructor name must be same as its class name
Constructor must have no explicit return type
Types of java constructors
There are two types of constructors:
Default constructor (no-arg constructor)
Parameterized constructor
You may invoke the method of the current class by using the this keyword.
If you don't use the this keyword, compiler automatically adds this keyword while invoking the method.
class A
{
void m()
{
System.out.println("hello m");
}
void n()
{
System.out.println("hello n");
//m(); //same as this.m()
this.m();
}
}
class TestThis4
{
public static void main(String args[])
{
A a=new A();
a.n();
}
}
Output:
hello n
hello m
The this() constructor call can be used to invoke the current class constructor.
It is used to reuse the constructor. In other words, it is used for constructor chaining.
Rule: Call to this() must be the first statement in constructor.
class A
{
A()
{
this(5);
System.out.println("hello a");
}
A(int x)
{
System.out.println(x);
}
}
class TestThis6
{
public static void main(String args[])
{
A a=new A();
}
}
Output:
5
hello a
1) By nulling a reference:
Employee e = new Employee();
e = null;
2) By assigning a reference to another:
D:\ACEM\java23batch\cse_a>java Main2
5 5.99 D true 'Hello
Local Variable
A variable that is declared inside the method is called local variable.
//local Variable Example
class LocalVariable
{
public static void main(String args[])
{
int a=10;
System.out.println(a);
}
}
Instance Variable
A variable that is declared inside the class but outside the method is called instance variable . It is not
declared as static.
//Instance variable Example
class InstanceVariable
{
int a=10;
byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean is not done automatically.
Also, the char and Boolean data types are not compatible with each other.
WideningTypeCastingExample.java
public class WideningTypeCastingExample
{
public static void main(String[] args)
{
int x = 7;
long y = x; //automatically converts the integer type into long type
float z = y; //automatically converts the long type into float type
Converting a higher data type into a lower one is called narrowing type casting.
It is also known as explicit conversion or casting up and it is done manually by the programmer.
If we do not perform casting then the compiler reports a compile-time error.
double -> float -> long -> int -> char -> short -> byte
In the following example, we have performed the narrowing type casting two times. First, we have
converted the double type into long data type after that long data type is converted into int type.
NarrowingTypeCastingExample.java
public class NarrowingTypeCastingExample
{
public static void main(String args[])
{
double d = 166.66;
long l = (long)d; //converting double data type into long data type
int I = (int)l; //converting long data type into int data type
}
}
Output
Before conversion: 166.66
After conversion into long type: 166
After conversion into int type: 166
When we create a two-dimensional array, it created with a separate index for rows and columns.
The individual element is accessed using the respective row index followed by the column index.
Syntax
When an array is initialized at the time of declaration, it need not specify the size of the array and use of the
new operator. Here, the size is automatically decided based on the number of values that are initialized.
Example
Example:
class TwoDimwntinalArrays
{
public static void main(String[] args)
{
int[][] arr = {
{ 1, 2 },
{ 3, 4 }
};
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
Unary Operator,
Arithmetic Operator,
Shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator,
Ternary Operator and
Assignment Operator.
Arithmetic Multiplicative / %
Additive + -
Equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary Ternary ?:
Assignment Assignment = += -= *= /= %=
The Java unary operators require only one operand. Unary operators are used to perform various operations i.e.:
incrementing/decrementing a value by one
negating an expression
inverting the value of a Boolean
The Java right shift operator >> is used to move the value of the left operand to right by the number of bits
specified by the right operand.
The logical && operator doesn't check the second condition if the first condition is false. It checks the
second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.
public class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c); //false && true = false
System.out.println(a<b&a<c); //false & true = false
}
}
Output:
false
false
Java Ternary Operator
Java Ternary operator is used as one line replacement for if-then-else statement and used a lot in Java
programming. It is the only conditional operator which takes three operands.
Java Ternary Operator Example
public class OperatorExample
{
public static void main(String args[])
{
int a=2;
int b=5;
int min = (a<b) ? a : b;
System.out.println(min);
}
}
Output:
2
Object Oriented Programming Through Java Page 42
java Control Statements | Control Flow in Java
In java, the control statements are the statements which will tell us that in which order the instructions
are getting executed.
The control statements are used to control the order of execution according to our requirements.
The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
Syntax:
if(condition)
{
//code if condition is true
}
else
{
//code if condition is false
}
Output:
NEGATIVE
if(condition)
{
//code to be executed
if(condition)
{
//code to be executed
}
}
SwitchExample.java
public class SwitchExample
{
public static void main(String[] args)
{
int number=20; //Declaring a variable for switch expression
switch(number) //Switch expression
{
case 10:
System.out.println("10");
break;
case 20:
System.out.println("20");
break;
case 30:
System.out.println("30");
break;
default:
System.out.println("Not in 10, 20 or 30");
}
}
}
Output: 20
We can initialize the variable, check condition and increment/decrement value. It consists of four parts:
1. Initialization: It is the initial condition which is executed once when the loop starts. Here, we can
initialize the variable, or we can use an already initialized variable. It is an optional condition.
2. Condition: It is the second condition which is executed each time to test the condition of the loop. It
continues execution until the condition is false. It must return boolean value either true or false. It is an
optional condition.
3. Increment/Decrement: It increments or decrements the variable value. It is an optional condition.
4. Statement: The statement of the loop is executed each time until the second condition is false.
Syntax:
for(initialization; condition; increment/decrement)
{
//statement or code to be executed
}
ForExample.java ///which prints table of 1
public class ForExample
{
public static void main(String[] args)
{
for(int i=1;i<=5;i++)
{
System.out.print(i);
}
}
}
Output: 1 2 3 4 5
Jump statements are used to transfer the control of the program to the specific statements.
In other words, jump statements transfer the execution control to the other part of the program.
There are two types of jump statements in Java, i.e., break and continue.
Java Break Statement
When a break statement is encountered inside a loop, the loop is immediately terminated and the
program control resumes at the next statement following the loop.
The Java break statement is used to break loop or switch statement. It breaks the current flow of the
program at specified condition. In case of inner loop, it breaks only inner loop.
We can use Java break statement in all types of loops such as for loop, while loop and do-while loop.
Syntax:
jump-statement;
break;
BreakExample.java //Java Program to demonstrate the use of break statement inside the for loop.
public class BreakExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++) //using for loop
{
if(i==5) //breaking the loop
{
break;
}
System.out.println(i);
}
}
}
Output:
1
2
3
4
Java Continue Statement
The continue statement is used in loop control structure when you need to jump to the next iteration of
the loop immediately.
The Java continue statement is used to continue the loop.
It continues the current flow of the program and skips the remaining code at the specified condition.
In case of an inner loop, it continues the inner loop only.
We can use Java continue statement in all types of loops such as for loop, while loop and do-while loop.
Syntax:
jump-statement;
continue;
Constructor overloading is a technique in Java in which a class can have any number of constructors that
differ in parameter lists.
The compiler differentiates these constructors by taking the number of parameters, and their type.
In other words whenever same constructor is existing multiple times in the same class with different
number of parameters or order of parameters or type of parameters is known asConstructor overloading.
Syntax
class ClassName
{
ClassName()
{
..........
}
ClassName(datatype1 value1)
{
.......
}
ClassName(datatype1 value1, datatype2 value2)
{
.......
}
ClassName(datatype2 variable2)
{
.......
}
}
Example
class Student5
{
int id;
String name;
int age;
Student5(int i,String n)
{
id = i;
name = n;
}
Student5(int i, String n, int a)
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
In the pass by reference concept, the method is called using a reference of the actual parameter.
So, it is called pass by reference.
It forwards the unique identifier of the object to the method.
If we made changes to the parameter's instance member, it would affect the original value.
Please note that when we pass a reference, a new reference variable to the same object is created.
So we can only change members of the object whose reference is passed.
We cannot change the reference to refer to some other object as the received reference is a copy of the original
reference.
The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called as recursive function.
A function fun is called direct recursive if it calls the same function fun.
A function fun is called indirect recursive if it calls another function say fun_new and fun_new calls fun
directly or indirectly.
Direct recursion:
void directRecFun()
{
// Some code....
directRecFun();
// Some code...
}
Indirect recursion:
void indirectRecFun1()
{
// Some code...
indirectRecFun2();
// Some code...
}
void indirectRecFun2()
{
// Some code...
indirectRecFun1();
// Some code...
}
Syntax:
returntype methodname()
{
//code to be executed
methodname();//calling same method
}
As you can see in the above figure that two objects are created but s reference variable still refers to "Sachin"
not to "Sachin Tendulkar".
But if we explicitly assign it to the reference variable, it will refer to "Sachin Tendulkar" object.
Testimmutablestring1.java
class Testimmutablestring1
{
public static void main(String args[])
{
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
Output:
Sachin Tendulkar
In such a case, s points to the "Sachin Tendulkar". Please notice that still Sachin object is not modified.
endsWith() Checks whether a string ends with the specified character(s) Boolean
equals() Compares two strings. Returns true if the strings are equal, and false if not Boolean
indexOf() Returns the position of the first found occurrence of specified characters Int
lastIndexOf() Returns the position of the last found occurrence of specified characters Int
System.out.println(s3.charAt(2)); //N
System.out.println(s1.compareTo(s2)); //0 because both are equal
System.out.println(s1.compareTo(s4)); //-3 because "s" is 1x greater than "r"
System.out.println(s5.compareTo(s1)); // 1
System.out.println(s1.equals(s2)); //true because both are equal
System.out.println(s1.length()); // 6
System.out.println( s4.replace("w","p")); //sping
System.out.println(s3.toLowerCase()); //ring
System.out.println(s1.concat(s2)); // stringstring
}
}
/* output
N
0
-3
1
true
6
sping
ring
stringstring */
When one class extends another class(Only one class) then we call it as Single inheritance.
The below diagram represents single inheritance in java where Class B extends only one class Class A.
Here Class B will be the Sub class and Class A will be one and only Super class.
class A
{
public void dispA()
{
System.out.println(" disp() method of Class A ");
}
}
Output :
class A
{
public void dispA()
{
System.out.println(" disp() method of ClassA ");
}
}
class B extends A
{
public void dispB()
{
System.out.println(" disp() method of ClassB ");
}
}
public class C extends B
{
public void dispC()
{
System.out.println(" disp() method of ClassC ");
}
HIERARCHICAL INHERITANCE
In Hierarchical inheritance one parent class will be inherited by many sub classes.
As per the below example ClassA will be inherited by ClassB, ClassC and ClassD.
ClassA will be acting as a parent class for ClassB, ClassC and ClassD.
class HierarchicalInheritanceTest
{
public static void main(String args[])
{
B b = new B();
b.dispB();
b.dispA();
Note:
Multiple inheritance is not supported in java through class but multiple and hybrid inheritance is supported
through interface only. When a class extends multiple classes i.e. known as multiple inheritance.
interface Printable
{
public void print();
}
interface Showable
{
public void show();
}
Output:
Hello
Welcome
HYBRID INHERITANCE
class Supercons
{
public static void main(String[] args)
{
HR obj=new HR();
}
}
Output
Employee class Constructor
HR class Constructor
class Vehicle
{
void run()
{
System.out.println(" Vehicle is running ");
}
}
Problem is that I have to provide my own implementation for run() method in subclass that is why we use
method overriding.
The name and parameter of the method are the same, and there is IS-A relationship between the classes, so there
is method overriding.
1) Method overloading is used to increase the Method overriding is used to provide the specific
readability of the program. implementation of the method that is already provided by
its super class.
2) Method overloading is performed within Method overriding occurs in two classesthat have IS-A
class. (inheritance) relationship.
3) In method overloading, parameter must be In case of method overriding, parameter must be same.
different.
4) Method overloading is the example Method overriding is the example of run time
of compile time polymorphism. polymorphism.
5) In java, method overloading can't be Return type must be same or covariant in method
performed by changing return type of the overriding.
Upcasting
If the reference variable of Parent class refers to the object of Child class, it is known as upcasting.
class A
{
}
class B extends A
{
}
A a=new B(); //upcasting
For upcasting, we can use the reference variable of class type or an interface type.
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
}
}
Output:
drawing rectangle...
drawing circle...
drawing triangle...
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only essential things to the user and hides the internal details.
Abstraction lets you focus on what the object does instead of how it does it.
Example: Sending SMS where you type the text and send the message.
You don't know the internal processing about the message delivery.
There are two ways to achieve abstraction in java
Abstract class (0 to 100%)
Interface (100%)
class TestAbstraction1
{
public static void main(String args[])
{
Shape s = new Circle1();
s.draw();
}
}
Output:
drawing circle
There is a final variable speedlimit, we are going to change the value of this variable, but It can't be
changed because final variable once assigned a value can never be changed.
Java final method
Example :
class Bike
{
final void run()
{
System.out.println("running");
}
}
Method Description
public final Class getClass() Returns the class object of “this” object and used to get actual runtime class of
the object. It can also be used to get metadata of this class.
public int hashCode() Returns the hashcode number for this object. For every object, JVM generates a
unique number which is hashcode. It returns distinct integers for distinct objects.
public final void notify() wakes up single thread, waiting on this object's monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's monitor.
public final void wait(long causes the current thread to wait for the specified milliseconds, until another
timeout)throws thread notifies (invokes notify() or notifyAll() method).
public final void wait(long causes the current thread to wait for the specified milliseconds and nanoseconds,
timeout,int nanos)throws until another thread notifies (invokes notify() or notifyAll() method).
InterruptedException
public final void wait()throws causes the current thread to wait, until another thread notifies (invokes notify() or
InterruptedException notifyAll() method).
protected void finalize()throws is invoked by the garbage collector before object is being garbage collected.
Throwable
if(a.equals(b))
{
System.out.println(" a and b are equal " );
}
if(!a.equals(c))
{
System.out.println(" a and b are not equal " );
}
}
}
Output:
a and b are equal
a and b are not equal
toString() Method
If you want to represent any object as a string, toString() method comes into existence.
The toString() method returns the String representation of the object.
If you print any object, Java compiler internally invokes the toString() method on the object. So
overriding the toString() method, returns the desired output it can be the state of an object etc.
Advantage of Java toString() method
By overriding the toString() method ,we can return values of the object, so we don't need to write much code.
class Student
{
int rollno;
String name;
String city;
Student(int rollno, String name, String city)
{
this.rollno = rollno;
this.name = name;
this.city = city;
}
Note: To compile and run the program we should follow the following format
To Compile: javac -d . directory.javafilename
The -d switch specifies the destination where to put the generated class file.
To Run: java packagename.filename
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
package mypack; (//save by B.java )
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output: Hello
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output: Hello
obj_1.outerMethod();
obj_2.innerMethod();
}
}
Output:
This is OuterInterface method
This is InnerInterface method
An exception is a problem or an abnormal condition that arises during the program execution (at run
time).
In other words an exception is a run time error.
When an Exception occurs the normal flow of the program is interrupts the flow and the program
terminates abnormally, therefore these exceptions are to be handled.
An exception can occur for many different reasons, including the following:
Some of these exceptions are caused by user error, others by programmer error, and others by physical
resources that have failed in some manner.
Errors
No matter how good a program we write it may cause the following types of errors.
Syntax Errors:
It is an error which occurs when the rules of language are violated .
If we are not following the rules, those cause the error. It can be easily detected and corrected by compilers.
Logical Error:
It is an error caused due to manual mistake in the logical expressions. These errors cannot be detected by the
compiler.
Eg. Current_balance = old_balance*cash_deposit
Runtime Error:
It is an Error, which occurs after executing the program at runtime.
Eg. Divide by zero.
File not found
No disc in the drive etc.
Exception Handling
Unchecked Exception
2. User-Defined Exceptions
import java.io.*;
import java.util.Scanner;
class CheckedDemo
{
public static void main(String args[])
{
FileInputStream mydata = new FileInputStream("G:/soft wares/names.txt");
Scanner myReader = new Scanner(mydata);
while (myReader.hasNextLine())
{
String data = myReader.nextLine();
System.out.println(data);
}
}
}
Output:
In the above code, we are trying to read the names.txt file and display its data or content on the screen.
D:\ACEM\II CSE Bsection>javac CheckedDemo.java
CheckedDemo.java:9: error: unreported exception FileNotFoundException; must be caught or declared
to be thrown
FileInputStream mydata = new FileInputStream("G:/soft wares/names.txt");
^
1 error
How to resolve the error?
There are basically two ways through which we can solve these errors.
The exceptions occur in the main method. We can get clear from these compilation errors by declaring
the exception in the main method using the throws . We only declare the IOException, not
FileNotFoundException, because of the child-parent relationship.
The IOException class is the parent class of FileNotFoundException, so this exception will
automatically cover by IOException. We will declare the exception in the following way:
class CheckedDemo
{
public static void main(String args[]) throws IOException
{
FileInputStream mydata = new FileInputStream("G:/soft wares/names.txt");
Scanner myReader = new Scanner(mydata);
while (myReader.hasNextLine())
{
String data = myReader.nextLine();
System.out.println(data);
}
}
}
Output:
D:\ACEM\II CSE Bsection>javac CheckedDemo.java
D:\ACEM\II CSE Bsection>java CheckedDemo
raja
ram
raghavan
2) We can also handle these exception using try-catch However, the way which we have used above is not
correct. We have to a give meaningful message for each exception type.
By doing that it would be easy to understand the error. We will use the try-catch block in the following way:
Exception.java
import java.io.*;
import java.util.Scanner;
class CheckedDemo
{
public static void main(String args[])
{
try
{
FileInputStream mydata = new FileInputStream("G:/soft wares/names.txt");
Scanner myReader = new Scanner(mydata);
while (myReader.hasNextLine())
{
String data = myReader.nextLine();
System.out.println(data);
}
}
UncheckedExceptionExample1.java
class UncheckedExceptionExample1
{
public static void main(String args[])
{
int positive = 35;
int zero = 0;
int result = positive/zero; //Give Unchecked Exception here.
System.out.println(result);
}
}
Output:
D:\sasi>javac UncheckedExceptionExample1.java
D:\sasi>java UncheckedExceptionExample1
Exception in thread "main" java.lang.ArithmeticException: / by zero
at UncheckedExceptionExample1.main(UncheckedExceptionExample1.java:6)
1. These exceptions are checked at compile time. These exceptions are just opposite to the checked
These exceptions are handled at compile time exceptions. These exceptions are not checked and
too. handled at compile time.
2. These exceptions are direct subclasses of They are the direct subclasses of the
Exception RuntimeException class.
3. The code gives a compilation error in the case The code compiles without any error because the
when a method throws a checked exception. The exceptions escape the notice of the compiler. These
compiler is not able to handle the exception on its exceptions are the results of user-created errors in
own. programming logic.
5. These exceptions are propagated using the throws These are automatically propagated.
keyword
6. It is required to provide the try-catch and try- In the case of unchecked exception it is not
finally block to handle the checked exception. mandatory.
try-catch block
In java, the try and catch, both are the keywords used for exception handling.
The keyword try is used to define a block of code that will be tests the occurrence of an exception.
The keyword catch is used to define a block of code that handles the exception occurred in the
respective try block.
Both try and catch are used as a pair. Every try block must have one or more catch blocks.
We can not use try without at least one catch, and catch alone can be used (catch without try is not
allowed).
Syntax
try
{
code to be tested
}
catch(ExceptionType object)
{
code for handling the exception
}
Example 1 MultipleCatchBlock1.java
public class MultipleCatchBlock1
{
public static void main(String[] args)
{
try
{
int a[] = new int[5];
a[5] = 30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Output:
Arithmetic Exception occurs
rest of the code
Object Oriented Programming Through Java Page 110
Java Nested try block
In Java, using a try block inside another try block is permitted. It is called as nested try block.
Every statement that we enter a statement in try block, context of that exception is pushed onto the stack.
For example, the inner try block can be used to handle ArrayIndexOutOfBoundsException while
the outer try block can handle the ArithemeticException (division by zero).
Sometimes a situation may arise where a part of a block may cause one error and the entire block
itself may cause another error. In such cases, exception handlers have to be nested.
Syntax:
try
{
statement 1;
statement 2;
try //try catch block within another try block
{
statement 3;
statement 4;
}
catch(Exception e1)
{
//exception message
}
}
catch(Exception e2) //catch block of parent (outer) try block
{
//exception message
}
Ans: Checked exception only, because unchecked exception is under our control so we can correct our code.
error is beyond our control. For example, we are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.
Advantage of Java throws keyword
Now Checked Exception can be propagated (forwarded in call stack).
It provides information to the caller of the method about the exception.
Java throws Example
import java.io.IOException;
class Testthrows1
{
void m() throws IOException
{
throw new IOException("device error"); //checked exception
}
void n() throws IOException
{
m();
}
void p()
{
try
{
n();
}
catch(Exception e)
{
System.out.println("exception handled");
}
}
Object Oriented Programming Through Java Page 114
public static void main(String args[])
{
Testthrows1 obj = new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...
Rules:
If we are calling a method that declares an exception, we must either caught or declare the exception.
1. Case 1: We have caught the exception i.e. we have handled the exception using try/catch block.
2. Case 2: We have declared the exception i.e. specified throws keyword with the method.
1. Definition throw keyword is used throw an Java throws keyword is used in the method
exception explicitly from inside the signature.
function .
2. Type of Using throw keyword, we can only Using throws keyword, we can declare both
exception propagate unchecked exception i.e., the checked and unchecked exceptions. However,
checked exception cannot be propagated the throws keyword can be used to propagate
using throw only. checked exceptions only.
3. Syntax The throw keyword is followed by an The throws keyword is followed by class
instance of Exception to be thrown. names of Exceptions to be thrown.
4. Declaration throw is used within the method. throws is used with the method signature.
Note:
If you don't handle the exception, before terminating the program, JVM executes finally block (if any).
Why use Java finally block?
finally block in Java can be used to put "cleanup" code such as closing a file, closing connection, etc.
Uses:
Case 1: When an exception does not occur
Case 2: When an exception occurs but not handled by the catch block
Case 3: When an exception occurs and is handled by the catch block
The code throws an exception however the catch block cannot handle it.
Even though, the finally block is executed after the try block and then the program terminates abnormally.
TestFinallyBlock1.java
class TestFinallyBlock
{
public static void main(String args[])
{
try
{
int data = 25/0;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
Example where the Java code throws an exception and the catch block handles the exception.
Later the finally block is executed after the try-catch block.
Further, the rest of the code is also executed normally.
class TestFinallyBlock
{
public static void main(String args[])
{
try
{
int data = 25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{
System.out.println(" Exception handled ");
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:
D:\ACEM\II CSE Bsection>javac TestFinallyBlock.java
D:\ACEM\II CSE Bsection>java TestFinallyBlock
Exception handled
finally block is always executed
rest of the code...
Note:
For each try block there can be zero or more catch blocks, but only one finally block.
The finally block will not be executed if the program exits ( by calling System.exit())
1. Definition final is the keyword and finally is the block in Java finalize is the method in Java
access modifier which is Exception Handling to which is used to perform
used to apply restrictions on execute the important code clean up processing just
a class, method or variable. whether the exception occurs before object is garbage
or not. collected.
2. Applicable Final keyword is used with Finally block is always finalize() method is used with
to the classes, methods and related to the try and catch the objects.
variables. block in exception handling.
3. Execution Final method is executed Finally block is executed as finalize method is executed
only when we call it. soon as the try-catch block is just before the object is
executed.. destroyed.
In Java, we can create our own exceptions that are derived classes of the Exception class.
User Defined Exception or custom exception is creating your own exception class and throws that
exception using ‘throw’ keyword. This can be done by extending the class Exception class that belongs
to java.lang package.
Basically, Java custom exceptions are used to customize the exception according to user need.
Using the custom exception, we can have your own exception and message.
Example 1:
In the following code, constructor of InvalidAgeException takes a string as an argument.
This string is passed to constructor of parent class Exception using the super() method.
Also the constructor of Exception class can be called without using a parameter and calling super()
method is not mandatory.
TestCustomException1.java
class InvalidAgeException extends Exception // class representing custom exception
{
public InvalidAgeException (String str)
{
super(str); // calling the constructor of parent Exception
}
}
Output:
The stream-based IO operations are performed using two separate streams input stream and output
stream.
The input stream is used for input operations, and the output stream is used for output operations.
The java stream is composed of bytes.
In Java, every program creates 3 streams automatically, and these streams are attached to the console.
System.out: standard output stream for console output operations.
System.in: standard input stream for console input operations.
System.err: standard error stream for console error output operations.
The Java streams support many different kinds of data, including simple bytes, primitive data types,
localized characters, and objects.
Java provides two types of streams, and they are as follows.
Byte Stream
Character Stream
The below picture shows how streams are categorized, and various built-in classes used by the java IO system.
Both character and byte streams essentially provides a convenient and efficient way to handle data streams
InputStream class
The InputStream class has defined as an abstract class, and it has the following methods which have
implemented by its concrete classes.
S.No. Method with Description
1 int available()
It returns the number of bytes that can be read from the input stream.
2 int read()
It reads the next byte from the input stream.
3 int read(byte[] b)
It reads a chunk of bytes from the input stream and store them in its byte array, b.
4 void close()
It closes the input stream and also frees any resources connected with this input stream.
The Reader class has defined as an abstract class, and it has the following methods which have implemented by
its concrete classes.
S.No. Method with Description
1 int read()
It reads the next character from the input stream.
2 String readLine()
It reads a line of text. A line is considered to be terminated by any one of a line feed ('\n')
a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
3 boolean ready()
It tells whether the stream is ready to be read.
4 void close()
It closes the input stream and also frees any resources connected with this input stream.
Writer class
The Writer class has defined as an abstract class, and it has the following methods which have implemented by
its concrete classes.
S.No. Method with Description
1 void flush()
It flushes the output steam by forcing out buffered bytes to be written out.
2 void write(char[] cbuf)
It writes a whole array(cbuf) to the output stream.
3 void write(int c)
It writes single character.
4 void write(String str)
It writes a string.
5 void write(String str, int off, int len)
It writes a portion of a string.
6 Writer append(char c)
It appends the specified character to the writer.
7 Writer append(CharSequence csq)
It appends the specified character sequence to the writer
8 Writer append(CharSequence csq, int start, int end)
It appends a subsequence of the specified character sequence to the writer.
9 void close()
It closes the output stream and also frees any resources connected with this output stream.
In java, there are two methods to write console output. Using the 2 following methods, we can write output
data to the console.
Using print() and println() methods
Using write() method
Example
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileReadingTest
{
public static void main(String args[]) throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;
try
{
in = new FileInputStream("D:\\ACEM\\II AI DS\\Input-File.txt");
out = new FileOutputStream("D:\\ACEM\\II AI DS\\Output-File.txt");
int c;
Note: The above program will read data from one file and writes data to another file by creating new file
In java, we can use a character stream to handle files. The character stream has the following built-in classes to
perform various operations on a file.
FileReader - It is a built-in class in java that allows reading data from a file. This class has implemented
based on the character stream. The FileReader class provides a method read() to read data from a file
character by character.
FileWriter - It is a built-in class in java that allows writing data to a file. This class has implemented
based on the character stream. The FileWriter class provides a method write() to write data to a file
character by character.
Example program that reads data from a file and writes the same to another file using FIleReader and FileWriter
classes.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileReadingTest1
{
public static void main(String args[]) throws IOException
{
FileReader in = null;
FileWriter out = null;
try
{
in = new FileReader("D:\\ACEM\\II AI DS\\Input-File1.txt");
out = new FileWriter("D:\\ACEM\\II AI DS\\Output-File1.txt");
int c;
The java.io package has a built-in class RandomAccessFile that enables a file to be accessed randomly.
The RandomAccessFile class has several methods used to move the cursor position in a file.
A random access file behaves like a large array of bytes stored in a file.
RandomAccessFile Constructors
The RandomAccessFile class in java has the following constructors.
Access Modes
Using the RandomAccessFile, a file may created in th following modes.
r - Creates the file with read mode; Calling write methods will result in an IOException.
rw - Creates the file with read and write mode.
rwd - Creates the file with read and write mode - synchronously. All updates to file content is written to
the disk synchronously.
rws - Creates the file with read and write mode - synchronously. All updates to file content or meta data
is written to the disk synchronously.
RandomAccessFile methods
ref.seek(0);
byte[] b = {1, 2, 3};
System.out.println("Use of .read(byte[] b) : " +ref.read(b)); // Use of .read(byte[] b) method :
In java, the java.io package has a built-in class Console used to read from and write to the console, if
one exists.
The Console class implements the Flushable interface.
In java, most the input functionalities of Console class available through System.in, and the output
functionalities available through System.out.
Console class Constructors
The Console class does not have any constructor.
We can obtain the Console class object by calling System.console()
Console class methods
Step 1 - Define the class whose object needs to be serialized; it must implement Serializable interface.
Step 2 - Create a file reference with file path using FileOutputStream class.
Step 3 - Create reference to ObjectOutputStream object with file reference.
Step 4 - Use writeObject(object) method by passing the object that wants to be serialized.
Step 5 - Close the FileOutputStream and ObjectOutputStream.
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Student implements Serializable
{
int id;
String name;
Step 1 - Create a file reference with file path in which serialized object is available using
FileInputStream class.
Step 2 - Create reference to ObjectInputStream object with file reference.
Step 3 - Use readObject() method to access serialized object, and typecaste it to destination type.
An enum is a special "class" that represents a group of constants (unchangeable variables, like final
variables).
This concept enables the java enum to have constructors, methods, and instance variables.
All the constants of an enum are public, static, and final.
As they are static, we can access directly using enum name.
The main objective of enum is to define our own data types in Java, and they are said to be enumeration
data types.
Creating enum in Java
In java, an enum can be defined outside a class, inside a class, but not inside a method.
To create an enum, use the enum keyword , and separate the constants with a comma.
Note that they should be in uppercase letters:
Access enum constants with the dot syntax
Enum is short for "enumerations", which means "specifically listed".
Every constant of an enum is defined as an object and enum does not allow to create an object of it.
As an enum represents a class, it can have methods, constructors. It also gets a few extra methods from
the Enum class, and one of them is the values() method.
Enum using values() method
The enum type has a values() method, which returns an array of all enum constants. This method is
useful when you want to loop through the constants of an enum:
Example
enum WeekDay
{
MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
public class EnumerationExample
{
public static void main(String[] args)
{
WeekDay day = WeekDay.FRIDAY;
System.out.println(" Today is " + day);
System.out.println("\n All WeekDays: ");
for(WeekDay d : WeekDay.values())
{
System.out.println(d);
}
}
}
All WeekDays:
MONDAY
TUESDAY
WEDNESSDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY
Java Enum ordinal() Method
The ordinal() method of Enum class returns the ordinal of this enumeration constant.
This method is designed to be used by sophisticated enum-based data structures, like EnumSet and EnumMap.
Syntax
public final int ordinal()
Return Value
The ordinal() method returns this enumeration constant's ordinal.
Example
public class Enum_ordinalMethodExample1
{
enum Colours
{
Red,Green,Brown,Yellow;
}
public static void main(String[] args)
{
Colours Red = Colours.Red;
Colours Green = Colours.Green;
Colours Brown = Colours.Brown;
Colours Yellow = Colours.Yellow;
System.out.println(" Red ordinal = "+Red.ordinal());
System.out.println(" Green Ordinal = "+Green.ordinal());
System.out.println(" Brown Ordinal = "+Brown.ordinal());
System.out.println(" Yellow Ordinal = "+Yellow.ordinal());
}
}
Output:
Red ordinal = 0
Green Ordinal = 1
Brown Ordinal = 2
Yellow Ordinal = 3
Object Oriented Programming Through Java Page 141
Autoboxing and Unboxing in Java
All the primitive data types have defined using the class concept, these classes known as wrapper
classes.
In java, every primitive type has its corresponding wrapper class.
All the wrapper classes in Java were defined in the java.lang package.
The following table shows the primitive type and its corresponding wrapper class.
1 byte Byte
2 short Short
3 int Interger
4 long Long
5 float Float
6 double Double
7 char Character
8 boolean Boolean
The Java 1.5 version introduced a concept that converts primitive type to corresponding wrapper type and
reverses of it.
Autoboxing in Java
In java, the process of converting a primitive type value into its corresponding wrapper class object is
called autoboxing or simply boxing.
For example, converting an int value to an Integer class object.
The compiler automatically performs the autoboxing when a primitive type value has assigned to an
object of the corresponding wrapper class.
We can also perform autoboxing manually using the method valueOf( ), which is provided by every
wrapper class.
In the above example code, the method printArray ( ) is a generic method that allows a different type of
parameter values for every function call.
Generic Class
In java, a class can be defined as a generic class that allows creating a class that can work with different types.
A generic class declaration looks like a non-generic class declaration, except that the class name is followed by
a type parameter section.
Example - Generic class
public class GenericClass <T1,T2>
{
public void display(T1 var1,T2 var2)
{
System.out.println("Name:"+var1+", ID:"+var2);
}
The java programming language allows us to create a program that contains one or more parts that can
run simultaneously at the same time. This type of program is known as a multithreading program.
Each part of this program is called a thread. Every thread defines a separate path of execution in java.
A thread is explained in different ways, and a few of them are as specified below.
A thread is a light weight process. (or) A thread is a subpart of a process that can run individually.
In java, multiple threads can run at a time, which enables the java to write multitasking programs.
Process requires separate address space for each. Threads share same address space.
Process never gain access over idle time of CPU. Thread gain access over idle time of CPU.
start( ) It moves there thread from Ready state to Running state by calling Void
run( ) method.
currentThread( ) Returns the reference of the thread that currently in running state. Void
sleep( long ) moves the thread to blocked state till the specified number of milliseconds. Void
yield( ) Tells to the scheduler that the current thread is willing to yield its current use Void
of a processor.
New
When a thread object is created using new, then the thread is said to be in the New state.
This state is also known as Born state.
Example
Thread t1 = new Thread();
When a thread calls start( ) method, then the thread is said to be in the Runnable state.
This state is also known as a Ready state.
Example
t1.start( );
Running
When a thread calls run( ) method, then the thread is said to be Running.
The run( ) method of a thread called automatically by the start( ) method.
Blocked / Waiting
A thread in the Running state may move into the blocked state due to various reasons like sleep( ) method
called, wait( ) method called, suspend( ) method called, and join( ) method called, etc.
When a thread is in the blocked or waiting state, it may move to Runnable state due to reasons like sleep time
completed, waiting time completed, notify( ) or notifyAll( ) method called, resume( ) method called, etc.
Example
Thread.sleep(1000);
wait(1000);
wait();
suspend();
notify();
notifyAll();
resume();
Dead / Terminated
A thread in the Running state may move into the dead state due to either its execution completed or the stop( )
method called. The dead state is also known as the terminated state.
Creating Threads
In java, a thread is a lightweight process.
Every java program executes by a thread called the main thread. When a java program gets executed, the
main thread created automatically. All other threads called from the main thread.
The java programming language provides two methods to create threads listed below.
Using Thread class (by extending Thread class)
Step-2: Override the run( ) method with the code that is to be executed by the thread. The run( ) method
Step-4: Call the start( ) method on the object created in the above step.
Example
class SampleThread extends Thread
{
public void run()
{
for(int i= 1; i<=4; i++)
{
try
{
System.out.println("i = " + i);
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
Step-2: Override the run( ) method with the code that is to be executed by the thread. The run( ) method
Step-4: Create the Thread class object by passing above created object as parameter to the Thread class
constructor.
Step-5: Call the start( ) method on the Thread class object created in the above step.
Example
class SampleThread implements Runnable
{
public void run()
{
for(int i= 1; i<=4; i++)
{
try
{
System.out.println("i = " + i);
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
The Thread class also contains three constants that are used to set the thread priority, and they are
MAX_PRIORITY - It has the value 10 and indicates highest priority.
NORM_PRIORITY - It has the value 5 and indicates normal priority.
MIN_PRIORITY - It has the value 1 and indicates lowest priority.
The synchronization is the process of allowing only one thread to access a shared resource at a time.
When a method created using a synchronized keyword, it allows only one object to access it at a time.
When an object calls a synchronized method, it put a lock on that method so that other objects or thread
that are trying to call the same method must wait, until the lock is released.
Once the lock is released on the shared resource, one of the threads among the waiting threads will be
allocated to the shared resource.
Thread2(Table t)
{
this.t = t;
}
Method Description
void wait( ) It makes the current thread to pause its execution until other thread in the same monitor calls notify( )
void notify( ) It wakes up the thread that called wait( ) on the same object.
void notifyAll() It wakes up all the threads that called wait( ) on the same object.
The producer produces the item and the consumer consumes the same. But here, the consumer can not consume
until the producer produces the item, and producer can not produce until the consumer consumes the item that
already been produced.
So here, the consumer has to wait until the producer produces the item, and the producer also needs to wait until
the consumer consumes the same. Here we use the inter-thread communication to implement the producer and
consumer problem.
class ProducerConsumer
{
LinkedList<Integer> list = new LinkedList<>();
public void produce() throws InterruptedException
{
int value=0;
while(true)
{
synchronized(this)
{
while(list.size()>0)
wait();
value++;
notify();
}
}
}
int value=list.removeFirst();
Thread.sleep(2000);
}
}
}
}
t1.start();
t2.start();
t1.join();
t2.join();
}
}
producer data 0
Consumer data 0
producer data 1
Consumer data 1
producer data 2
Consumer data 2
producer data 3
Consumer data 3
Note: while running this program press CTRL+C to break the execution
Before the collection framework in java (before java 1.2 version), there was a set of classes
like Array, Vector, Stack, HashTable. These classes are known as legacy classes.
The java collection framework contains List, Queue, Set, and Map as top-level interfaces.
The List, Queue, and Set stores single value as its element, whereas Map stores a pair of a key and value
Operations on ArrayList
The ArrayList class allow us to perform several operations like adding, accessing, deleting, updating, etc.
Adding Items
The ArrayList class has the following methods to add items.
boolean add(E element) - Appends given element to the ArrayList.
void add(int index, E element) - Inserts the given element at specified index.
Accessing Items
The ArrayList class has the following methods to access items.
E get(int index) - Returns element at specified index from the ArrayList.
ArrayList subList(int startIndex, int lastIndex) - Returns an ArrayList that contains elements from
invoking ArrayList.
boolean remove(Object element) - Removes the first occurrence of the given element from the invoking
ArrayList.
boolean removeAll(Collection c) - Removes the given collection of elements from the invoking
ArrayList.
void retainAll(Collection c) - Removes all the elements except the given collection of elements from the
invoking ArrayList..
void clear( ) - Removes all the elements from the ArrayList.
Example
import java.util.ArrayList;
class JavaExample1
{
public static void main(String args[])
{
ArrayList<String> arrList=new ArrayList<>();
linkList.add("Apple"); //["Apple"]
linkList.add("Orange"); //["Apple", "Orange"]
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
Output:
D:\ACEM\II AI DS>javac JavaExample2.java
D:\ACEM\II AI DS>java JavaExample2
LinkedList elements:
Banana
Apple
Orange
Object Oriented Programming Through Java Page 164
Hash Set
The HashSet class extends AbstractSet class and implements Set interface.
The elements of HashSet are organized using a mechanism called hashing.
The HashSet is used to create hash table for storing set of elements.
The HashSet class is used to create a collection that uses a hash table for storing set of elements.
The HashSet does not allows to store duplicate data values, but null values are allowed.
The HashSet does not maintains the order of insertion.
The HashSet initial capacity is 16 elements.
The HashSet is best suitable for search operations.
HashSet class declaration
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable
Program:
import java.util.HashSet;
import java.util.Iterator;
public class JavaExample3
{
public static void main(String args[])
{
HashSet<String> set=new HashSet<>();
set.add("honey cake");
set.add("stawberry");
set.add("vennela cake");
set.add("ice cake");
Iterator<String> it=set.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
Output:
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
Output:
D:\ACEM\II AI DS>javac JavaExample4.java
D:\ACEM\II AI DS>java JavaExample4
airtel
idea
jio
voda phone
queue.add(10);
queue.add(20);
queue.add(15);
Example:
import java.util.Deque;
import java.util.ArrayDeque;
public class TestJavaCollection6
{
public static void main(String[] args)
{
//Creating Deque and adding elements
deque.add("Gautam");
deque.add("Karan");
deque.add("Ajay");
//Traversing elements
hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
for(Map.Entry m:hm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
D:\ACEM\II AI DS>javac Hashtable1.java
D:\ACEM\II AI DS>java Hashtable1
103 Rahul
102 Ravi
101 Vijay
100 Amit
D:\SASI\sasijava>java StackClassExample
Stack elements => [14, 42, 15, 14, 19]
Top element is 19
Removed element is 19
Element 50 availability => -1
Stack is empty? – false
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}
Output:
D:\ACEM\II AI DS>javac StringTokenizerExample.java
D:\ACEM\II AI DS>java StringTokenizerExample
my
name
is
sachin
Bit Set
The BitSet is a built-in class in java used to create a dynamic array of bits represented by boolean
values. The BitSet class is available inside the java.util package.
The BitSet array can increase in size as needed. This feature makes the BitSet similar to a Vector of bits.
The bit values can be accessed by non-negative integers as an index.
The size of the array is flexible and can grow to accommodate additional bit as needed.
The default value of the BitSet is boolean false with a representation as 0 (off).
BitSet uses 1 bit of memory per each boolean value.
bitset1.and(bitset2);
The Calendar is a built-in abstract class in java used to convert date between a specific instant in time
and a set of calendar fields such as MONTH, YEAR, HOUR, etc.
The Calendar class is available inside the java.util package.
The Calendar class implements Serializable, Cloneable and Comparable interface.
As the Calendar class is an abstract class, we can not create an object using it.
We will use the static method Calendar.getInstance() to instantiate and implement a sub-class.
calendar.add(Calendar.DATE, -15);
System.out.println("15 days ago: " + calendar.getTime());
calendar.add(Calendar.MONTH, 4);
System.out.println("4 months later: " + calendar.getTime());
calendar.add(Calendar.YEAR, 2);
System.out.println("2 years later: " + calendar.getTime());
}
}
Output:
D:\ACEM\II AI DS>javac CalendarExample1.java
D:\ACEM\II AI DS>java CalendarExample1
The current date is : Sun Dec 25 22:08:47 IST 2022
15 days ago: Sat Dec 10 22:08:47 IST 2022
4 months later: Mon Apr 10 22:08:47 IST 2023
2 years later: Thu Apr 10 22:08:47 IST 2025
Random
The Random is a built-in class in java used to generate a stream of pseudo-random numbers in java
programming. The Random class is available inside the java.util package.
The Random class implements Serializable, Cloneable and Comparable interface.
The Random class is a part of java.util package.
The Random class provides several methods to generate random numbers of type integer, double, long,
float etc.
The Random class is thread-safe.
Random number generation algorithm works on the seed value. If not provided, seed value is created
from system nano time.
// setting seed
}
Output:
D:\ACEM\II AI DS>javac JavaRandomExample.java
D:\ACEM\II AI DS>java JavaRandomExample
Random Integer value : -1652727993
Seed value : -1150867590
Random Long value : -7322354119883315205
Formatter class
The Formatter is a built-in class in java used for layout justification and alignment, common formats
for numeric, string, and date/time data, and locale-specific output in java programming.
The Formatter class is defined as final class inside the java.util package.
The Formatter class implements Cloneable and Flushable interface.
The Formatter class in java has the following constructors.
Example:
import java.util.*;
public class ScannerClassExample1
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
in.close();
}
}
Output:
D:\ACEM\II AI DS>javac ScannerClassExample1.java
D:\ACEM\II AI DS>java ScannerClassExample1
Enter your name: Aditya
Name: Aditya
Enter your age: 32
Age: 32
Enter your salary: 35000
Salary: 35000.0
This comment contains an APPLET tag that will run an applet called MyApplet in a window that is 200 pixels
wide and 60 pixels high.
stop() : stop() method is called to suspend thread that does not need to run when applet is not visible.
destroy() : destroy() method is called when your applet needs to be removed completely from memory.
public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be
used for drawing oval, rectangle, arc etc.
Note:
Four methods—init( ), start( ), stop( ), and destroy( )—are defined by Applet.
Another, paint( ), is defined by the AWT Component class.
<html>
<applet code = "HelloWorldApplet.class" width = "320" height = "120">
</applet>
</html>
OUTPUT:
javac HelloWorldApplet.java
appletviewer HelloWorldApplet.html
Requesting Repainting:
Whenever applet needs to update the information displayed in its window, it simply calls repaint( ).
The repaint( ) method is defined by the AWT. It causes the AWT run-time system to execute a call to
your applet’s update( ) method, which, in its default implementation, calls paint( ).
Syntax:
void repaint( )
Here, the coordinates of the upper-left corner of the region are specified by left and top, and the width
and height of the region are passed in width and height.
These dimensions are specified in pixels. You save time by specifying a region to repaint.
Here, maxDelay specifies the maximum number of milliseconds that can elapse before update( ) is called.
In addition to displaying information in its window, an applet can also output a message to the
status window of the browser or applet viewer on which it is running.
To do so, call showStatus( ) with the string that you want displayed.
It is used to give the user feedback about what is occurring in the applet ,suggest options
import java.awt.*;
import java.applet.*;
public class StatusWindow extends Applet
{
public void init()
{
setBackground(Color.cyan);
}
/*
<applet code="StatusWindow.class" width=300 height=300>
</applet>
*/
Output:
The APPLET tag in HTML allows you to pass parameters to your applet.
To retrieve a parameter, use the getParameter( ) method.
It returns the value of the specified parameter in the form of a String object.
ParamDemo.java
import java.awt.*;
import java.applet.*;
Swing in Java is a lightweight GUI toolkit which has a wide variety of components for building
optimized window based applications.
It is a part of the JFC( Java Foundation Classes). It is build on top of the AWT API and entirely written
in java. It is platform independent unlike AWT and has lightweight components.
It is easier to build applications since we already have GUI components like button, checkbox etc.
Difference Between AWT and Swing
AWT SWING
Platform Dependent Platform Independent
Lesser Components More powerful components
Does not support pluggable look and feel Supports pluggable look and feel
Heavyweight Lightweight
components and containers
Component
A component is an independent visual control and Java Swing Framework contains a large set of these
components which provide rich functionalities and allow high level of customization.
They all are derived from JComponent class. All these components are lightweight components.
This class provides some common functionality like pluggable look and feel, support for accessibility,
drag and drop, layout, etc.
Container Class
Any class which has other components in it is called as a container class.
For building GUI applications at least one container class is necessary.
Following are the three types of container classes:
1. Panel – It is used to organize components on to a window
2. Frame – A fully functioning window with icons and titles
3. Dialog – It is like a pop up window but not fully functional like the frame
Heavyweight.
Example: JPanel
Explanation:
All the components in swing like JButton, JComboBox, JList, JLabel are inherited from the JComponent
class which can be added to the container classes.
Containers are the windows like frame and dialog boxes.
Methods like setLayout override the default layout in each container.
layout managers
Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner.
The LayoutManagers facilitates us to control the positioning and size of the components in GUI forms.
LayoutManager is an interface that is implemented by all the classes of layout managers.
There are the following classes that represent the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.GridBagLayout
.
Constructors of BorderLayout class:
1. BorderLayout(): creates a border layout but with no gaps between the components.
2. BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps
between the components.
FlowLayout:
It arranges the components in a container like the words on a page and
It fills the top line from left to right and top to bottom.
The components are arranged in the order as they are added i.e. first components appears at top left, if
the container is not wide enough to display all the components, it is wrapped around the line.
Vertical and horizontal gap between components can be controlled. The components can be left, center
or right aligned.
Constructor
1. GridBagLayout(): The parameterless constructor is used to create a grid bag layout manager.
An event can be defined as changing the state of an object or behavior by performing actions.
Actions can be a button click, cursor movement, key press through keyboard or page scrolling, etc.
The java.awt.event package can be used to provide various event classes.
Event Handling
It is a mechanism to control the events and to decide what should happen after an event occur. To handle
the events, Java follows the Delegation Event model.
Different interfaces consists of different methods which are specified below.
ActionListener actionPerformed()
MouseWheelListener mouseWheelMoved()
Example:
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener
{
Label b;
MouseListenerExample()
{
addMouseListener(this);
b = new Label();
b.setBounds(20,50,100,20);
add(b);
setSize(300,300);
Object Oriented Programming Through Java Page 190
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e)
{
b.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e)
{
b.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e)
{
b.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e)
{
b.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e)
{
b.setText("Mouse Released");
}
JTextField(String text) Creates a new TextField initialized with the specified text.
Commonly used Methods:
Methods Description
void addActionListener(ActionListener l) It is used to add the specified action listener to receive action events
from this textfield.
Action getAction() It returns the currently set Action for this ActionEvent source, or null
if no Action is set.
Java JLabel
The object of JLabel class is a component for placing text in a container.
It is used to display a single line of read only text and It inherits JComponent class.
import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f = new JFrame("TextField Example");
JTextField t1,t2;
f.add(t1);
f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
JLabel() Creates a JLabel instance with no image and with an empty string for the title.
void setText(String text) It defines the single line of text this component will display.
void setHorizontalAlignment(int alignment) It sets the alignment of the label's contents along the X axis.
Example:
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f = new JFrame("Label Example");
JLabel l1,l2;
f.add(l1);
f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
ImageIcon
The class ImageIcon is an implementation of the Icon interface that paints Icons from Images.
Class Declaration
public class ImageIcon extends Object implements Icon, Serializable, AccessibleField
Class Constructors
ImageIcon()
1
Creates an uninitialized image icon.
ImageIcon(byte[] imageData)
2 Creates an ImageIcon from an array of bytes which were read from an image file containing a supported
image format, such as GIF, JPEG
Constructor Description
JTextField(String text) Creates a new TextField initialized with the specified text.
Commonly used Methods:
Methods Description
void addActionListener(ActionListener l) It is used to add the specified action listener to receive action events
from this textfield.
Action getAction() It returns the currently set Action for this ActionEvent source, or null
if no Action is set.
Example:
import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f = new JFrame("TextField Example");
JTextField t1,t2;
f.add(t1);
f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java JScrollPane
A JscrollPane is used to make scrollable view of a component.
When screen size is limited, we use a scroll pane to display a large component or a component whose
size can change dynamically.
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
frame.getContentPane().add(scrollableTextArea);
}
Java JList
The object of JList class represents a list of text items.
The list of text items can be set up so that the user can choose either one item or multiple items.
JList class declaration
public class JList extends JComponent implements Scrollable, Accessible
Commonly used Constructors:
Constructor Description
JList(ary[] listData) Creates a JList that displays the elements in the specified array.
Methods Description
l1.addElement("mango ");
l1.addElement("apple");
l1.addElement("banana");
l1.addElement("orange");
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}
}
Output:
Constructor Description
JComboBox(Object[] items) Creates a JComboBox that contains the elements in the specified array.
Commonly used Methods:
Methods Description
Example:
import javax.swing.*;
public class ComboBoxExample
{
JFrame f;
ComboBoxExample()
{
f =new JFrame("ComboBox Example");
String country[] = { "India","Aus","U.S.A","England","Newzealand" };
JComboBox cb = new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args)
{
new ComboBoxExample();
}
}
JTree
The JTree class is used to display the tree structured data or hierarchical data.
It has a 'root node' at the top most which is a parent for all nodes in the tree.
JTree(Object[] value) Creates a JTree with every element of the specified array as the child of a new root node.
JTree(TreeNode root) Creates a JTree with the specified TreeNode as its root, which displays the root node.
Example:
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
TreeExample()
{
f = new JFrame();
DefaultMutableTreeNode style = new DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color = new DefaultMutableTreeNode("color");
DefaultMutableTreeNode font = new DefaultMutableTreeNode("font");
style.add(color);
style.add(font);
color.add(red);
color.add(blue);
color.add(black);
color.add(green);
f.add(jt);
f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] args)
{
new TreeExample();
}
}
Output:
The JTable class is used to display data in tabular form. It is composed of rows and columns.
Constructor Description
JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.
Example:
import javax.swing.*;
public class TableExample
{
JFrame f;
TableExample()
{
f = new JFrame();
String data[][] = {
{"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}
};
jt.setBounds(30,40,200,300);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args)
{
new TableExample();
}
}
The JMenuBar class is used to display menubar on the window or frame. It may have several menus.
The object of JMenu class is a pull down menu component which is displayed from the menu bar. It
inherits the JMenuItem class.
The object of JMenuItem class adds a simple labeled menu item. The items used in a menu must belong
to the JMenuItem or any of its subclass.
JMenuBar class declaration
public class JMenuBar extends JComponent implements MenuElement, Accessible
JMenu class declaration
public class JMenu extends JMenuItem implements MenuElement, Accessible
JMenuItem class declaration
public class JMenuItem extends AbstractButton implements Accessible, MenuElement
Creating a main menu
Create a Main Menu
Constructing the main menu requires several steps.
First, create the JMenuBar object that will hold the menus. Next, construct each menu that will be in the
menu bar.
In general, a menu is constructed by first creating a JMenu object and then adding JMenuItems to it.
After the menus have been created, add them to the menu bar.
The menu bar, itself, must then be added to the frame by calling setJMenuBar( ).
Finally, for each menu item, you must add an action listener that handles the action event fired when the
menu item is selected.
cut.addActionListener(this);
copy.addActionListener(this);
paste.addActionListener(this);
selectAll.addActionListener(this);
mb = new JMenuBar();
file = new JMenu("File");
edit = new JMenu("Edit");
help = new JMenu("Help");
edit.add(cut);
edit.add(copy);
edit.add(paste);
edit.add(selectAll);
mb.add(file);
mb.add(edit);
mb.add(help);
ta = new JTextArea();
ta.setBounds(5,5,360,320);
f.add(mb);
f.add(ta);
f.setJMenuBar(mb);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
}
Output:
Java JOptionPane
The JOptionPane class is used to provide standard dialog boxes such as message dialog box, confirm
dialog box and input dialog box.
These dialog boxes are used to display information or get input from the user.
The JOptionPane class inherits JComponent class.
JOptionPane class declaration
public class JOptionPane extends JComponent implements Accessible
Constructor Description
JDialog createDialog(String title) It is used to create and return a new parentless JDialog with the
specified title.
Example:
import javax.swing.*;
public class OptionPaneExample
{
JFrame f;
OptionPaneExample()
{
f = new JFrame();
JOptionPane.showMessageDialog(f,"Hello, Welcome to Aditya Engineering college students");
}
public static void main(String[] args)
{
new OptionPaneExample();
}
}
Output:
showOptionDialog
import javax.swing.JOptionPane;
import javax.swing.JFrame;
public class ShowOptionDialogExample
{
public static void main(String[] args)
{
Object[] options = {"java","python"};
int n = JOptionPane.showOptionDialog(null, "A Message", "A Title",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.DEFAULT_OPTION,
null,
options,
options[1] );
System.out.println(n);
Java JDialog
The JDialog control represents a top level window with a border and a title used to take some form of
input from the user. It inherits the Dialog class.
Unlike JFrame, it doesn't have maximize and minimize buttons.
JDialog class declaration
public class JDialog extends Dialog implements WindowConstants, Accessible, RootPaneContainer
Commonly used Constructors:
Constructor Description
JDialog() It is used to create a modeless dialog without a title and without a specified Frame owner.
JDialog(Frame It is used to create a modeless dialog with specified Frame as its owner and an empty title.
owner)
Advantage
Better performance as compared to Type 1 driver.
Disadvantage
Driver is platform dependent.
The vendor client library needs to be installed.
Native driver needs to be installed on each machine.
3. Network Protocol Driver (Type 3/Fully Java Driver)
Uses middleware that convert JDBC call directly or indirectly into vendor specific database protocol.
Fully written in Java.
Database specific coding to be done in middle tier.
Advantage :
No client side library is required.
Disadvantage
Network support is required on client machine.
Database specific coding is done in middleware.
Advantage
Performance is good as compared to other drivers.
No software is required for client or server side.
Disadvantage
Different types of drivers required for different database.
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access.
Two tier architecture
In the two-tier model, a Java applet or application talks directly to the data source.
This requires a JDBC driver that can communicate with the particular data source being accessed.
A user's commands are delivered to the database or other data source, and the results of those statements
are sent back to the user.
The data source may be located on another machine to which the user is connected via a network.
This is referred to as a client/server configuration, with the user's machine as the client, and the machine
housing the data source as the server.
The JDBC API is comprised of two Java packages: java.sql and javax.sql.
The following are core JDBC classes, interfaces, and exceptions in the java.sql package:
DriverManager
The DriverManager class (java.sql.DriverManager) is one of main components of JDBC.
DriverManager manages database drivers, load database specific drivers and select the most
appropriate database specific driver from the previously loaded drivers when a new connection is
established.
Connection
Connection interface provides a standard abstraction to access the session established with a database
server.
JDBC driver provider should implement the connection interface. We can obtain a Connection object
using the getConnection() method of the DriverManager as:
Connection con = DriverManager.getConnection(url, username, password);
Example 1:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
stmt.executeUpdate(sql);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
Output
Created table in given database...
Example 2:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
public class Insert99
{
static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:XE";
static final String USER = "system";
static final String PASS = "acem";
int i = ps.executeUpdate();
Example 3:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
PreparedStatement ps = null;
String qry = "select * from results";
ps = conn.prepareStatement(qry);
ResultSet rs = ps.executeQuery(qry);
while (rs.next())
{
String name = rs.getString("name");
int htno = rs.getInt("htno");
int marks1 = rs.getInt("marks1");
int marks2 = rs.getInt("marks2");
int marks3 = rs.getInt("marks3");
catch (SQLException e)
{
System.out.println(e);
}
}
}
Output:
D:\ACEM\II AI DS>javac GettingResults.java
D:\ACEM\II AI DS>java GettingResults
stu name : charan
studtno : 2001
sub1 : 88
sub2 : 99
sub3 : 95
Object Oriented Programming Through Java Page 219
Object Oriented Programming Through Java Lab -- (20A05302P)
Week 1
A)
Installation of Java software, study of any Integrated development environment, Use Eclipse or Netbeans
platform and acquaint with the various menus.
See how you can use auto suggestions, auto fill. Try code formatter and code refactoring like renaming
variables, methods and classes. Try debug step by step with java program to find prime numbers between 1 to n.
Description:
Prime number in Java: Prime number is a number that is greater than 1 and divided by 1 or itself only.
In other words, prime numbers can't be divided by other numbers than itself or 1.
For example 2, 3, 5, 7, 11, 13, 17 .... are the prime numbers.
Algorithm:
Get the upper limit from the user and store it in the variable “N”
Start the loop from 2 to N, for each iteration increment the loop by 1
In the checkPrime() method, we have used a boolean flag. It will be set to false when the number is less
than 1 or if the number is divisible by number/2.
Validate the boolean returned by the checkPrime() and print the number if the boolean returned
is true.
import java.util.Scanner;
for(j=2;j<=n;j++)
{
count=0;
for(i=1;i<=j;i++)
{
if(j%i==0)
{
count++;
}
}
if(count==2)
System.out.print(j+" ");
}
}
}
Output:
D:\ACEM\java23batch\cse_a>java PrimeNumbersPrint
Enter n value : 20
Prime numbers between 1 to 20
2 3 5 7 11 13 17 19
The standard form of a quadratic equation is ax2+bx+c=0. It is also known as the second-degree
equation.
In the equation ax2+bx+c=0, a, b, and c are unknown values and a cannot be 0. x is an unknown
variable.
The formula to find the roots of the quadratic equation is known as the quadratic formula.
A quadratic equation has two roots and the roots depend on the discriminant.
In the above formula, (b2-4ac) is called discriminant (d).
Algorithm :
Step 1: Start
Step 2: Read a, b, c
Step 3: initialize d<-(b*b)-(4*a*c)
Step 4: initialize r<- b/2*a
Step 5: if d>0 go to Step 6, else go to Step 8
Step 6: r1=r+(sqrt(d)/2*a) and r2=r-(sqrt(d)/2*a)
Step 7: prints roots are real and distinct, first root r1 second root r2
d= b * b - 4 * a * c;
if (d> 0.0)
{
double r1 = (-b + Math.pow(d, 0.5)) / (2 * a);
double r2 = (-b - Math.pow(d, 0.5)) / (2 * a);
System.out.println("The roots are " + r1 + " and " + r2);
}
else
if (d == 0)
{
double r1 = -b / (2 * a);
System.out.println("The root is " + r1);
}
else
{
System.out.println("Roots are not real.");
}
}
}
E:\AI>java QuadraticEquationExample
If the type of the EB connection is domestic, calculate the amount to be paid as follows:
Description:
import java.util.*;
void readData()
{
Scanner scan = new Scanner(System.in);
void caluclate_bill_amount()
{
if(Ebconn.equals("domestic"))
{
int units;
units=curr_reading-prev_reading;
if(units<=100)
{
bill=units*1;
}
else
{
int units;
units=curr_reading-prev_reading;
if(units<=100)
{
bill=units*2;
}
else
if(units>=101 && units<=200)
{
bill=units*4.50;
}
else
if(units>=201 && units<=500)
{
bill=units*6;
}
else
if(units>=501)
{
bill=units*7;
}
void displayData()
{
System.out.println(" consumer number = "+consumerno);
System.out.println(" consumer name = "+consumername);
System.out.println(" previous reading = "+prev_reading);
System.out.println(" current reading = "+curr_reading);
System.out.println(" Type of connection = "+ Ebconn);
System.out.println(" Bill amount = "+bill);
}
Algorithm:
Step 1: Declare two matrices and assign values and declare third matrix to store product
Step 2: Multiply two matrices and display output
Step 3: use inner loops to multiply matrices like below
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
System.out.print(c[i][j]+" "); //printing matrix element
}
System.out.println(); //new line
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
System.out.print(c[i][j]+" "); //printing matrix element
}
System.out.println(); //new line
}
}
}
Output :
E:\AI>javac MatrixMultiplicationExample.java
E:\AI>java MatrixMultiplicationExample
666
12 12 12
18 18 18
class MathOperations
{
public void addition(int x, int y)
{
System.out.println(" The sum of the given numbers ="+(x+y));
}
Description:
An abstract class can also have methods that are neither abstract nor final, just regular methods.
There may be "final" methods in "abstract" class. But, any "abstract" method in the class can't be
declared final. It will give "illegal combination of modifiers: abstract and final" error.
public abstract final void show(); // illegal combination of modifiers: abstract and final
Program:
D:\>javac Demo2.java
1 error
The key difference between overloading and overriding in Java is that the Overloading is the ability to
create multiple methods of the same name with different implementations and Overriding is to
provide an implementation for a subclass method that already exists in the superclass.
Procedure:
we have created two methods, first sum() method performs addition of two numbers and second sum
method performs addition of three numbers.
Create an object for that class and call both sum methods using period (.) operator
Output
30
60
Method overriding :
Description:
If a subclass provides the specific implementation of the method that has been declared by one of its
parent class, it is known as method overriding.
Method overriding is used to provide the specific implementation of a method which is already provided
by its superclass.
Program:
class Demo1
{
public void show(int a, int b , int c)
{
System.out.println("sum ="+(a+b+c));
}
}
Description:
INR is currency of INDIA
EURO is currency of European union
YEN is currency of Japan
Procedure:
import java.util.*;
interface converter
{
void dollar_rupee();
void rupee_dollar();
void euro_rupee();
void rupee_euro();
void yen_rupee();
void rupee_yen();
}
public class currency implements converter
{
double inr,usd;
double euro,yen;
inr=usd*67;
System.out.println("Dollar ="+usd+"equal to INR="+inr);
}
usd=inr/67;
System.out.println("Rupee ="+inr+"equal to Dollars="+usd);
}
inr=euro*79.50;
System.out.println("Euro ="+euro +"equal to INR="+inr);
}
euro=(inr/79.50);
System.out.println("Rupee ="+inr +"equal to Euro="+euro);
}
inr=yen*0.61;
System.out.println("YEN="+yen +"equal to INR="+inr);
}
yen=(inr/0.61);
System.out.println("INR="+inr +"equal to YEN"+yen);
}
int ch;
currency c = new currency();
switch(ch)
{
case 1:
{
c.dollar_rupee();
break;
}
case 2:
{
c.rupee_dollar();
break;
}
case 3:
{
c.euro_rupee();
break;
}
case 4:
{
c.rupee_euro();
break;
}
case 5:
{
c.yen_rupee();
break;
}
case 6:
{
c.rupee_yen();
D:\>java currency
1. dollar to rupee
2. rupee to dollar
3. Euro to rupee
4. .rupee to Euro
5. Yen to rupee
6. Rupee to Yen
Enter 0 to quit and 1 to continue
1
Enter dollars to convert into Rupees:
30
Dollar =30.0equal to INR=2010.0
1. dollar to rupee
2. rupee to dollar
3. Euro to rupee
4. .rupee to Euro
5. Yen to rupee
6. Rupee to Yen
Enter 0 to quit and 1 to continue
2
Enter Rupee to convert into Dollars:
10
Rupee =10.0equal to Dollars=0.14925373134328357
Program:
abstract class Shape
{
int a=3,b=4;
abstract public void print_area();
}
class Rectangle extends Shape
{
public double area_rect;
public void print_area()
{
area_rect=a*b;
System.out.println("The area of rectangle is:"+area_rect);
}
}
class Triangle extends Shape
{
double area_tri;
public void print_area()
{
area_tri= 0.5*a*b;
System.out.println("The area of triangle is:"+area_tri);
}
}
Output:
D:\ACEM>javac AreaCode.java
D:\ACEM>java AreaCode
The area of rectangle is:12.0
The area of triangle is:6.0
The area of circle is:28.259999999999998
Description:
Initially take the input interval of time in hours, minutes, and seconds.
The system time can be read as using the object of the class GregorianCalendar.
This GregorianCalendar class contains a method by name get which returns a required value from the
hour, minutes, and seconds of the system time.
Calendar class contains variables hour, minute, second which gives the system time through the object
of the class GregorianCalendar
Program:
import java.util.*;
import java.text.*;
class Tokenizer
{
static int[] cal(String y)
{
String a,b,x=":";
int i[] = {0,0};
i[0]=Integer.parseInt(a);
i[1]=Integer.parseInt(b);
return i;
}
}
while(true)
{
String x,t1,a,b;
int minute,hour;
int HH[]={0,0},MM[]={0,0};
t1=dateFormat.format(cal.getTime());
int time1[]=Tokenizer.cal(t1);
hour=time1[0];
minute=time1[1];
System.out.println("Enter the time intervels in HH:MM fommat");
Scanner z = new Scanner(System.in);
String t2=z.next();
String t3=z.next();
int time2[]=Tokenizer.cal(t2);
HH[0]=time2[0];
MM[0]=time2[1];
int time3[]=Tokenizer.cal(t3);
HH[1]=time3[0];
MM[1]=time3[1];
if(HH[0]>HH[1])
{
int t=HH[0];
HH[0]=HH[1];
HH[1]=t;
2:15
3:46
Try again
3:46
7:13
Current time is 6 : 23
}
catch (InvalidAmountException ex)
{
System.out.println("Caught the exception");
// printing the message from InvalidAmountException object
System.out.println("Exception occured: " + ex);
}
import java.awt.*;
import javax.swing.*;
import java.applet.*;
import java.awt.event.*;
TextField t1,t2,t3;
Button b;
Label L1,L2,L3,L4;
String s;
Division e;
b=new Button("Divide");
b.addActionListener(this);
t3.setText(s);
}
catch(ArithmeticException a)
{
JOptionPane.showMessageDialog(null,"Divide by zero");
}
catch(NumberFormatException b)
{
JOptionPane.showMessageDialog(null,"NumberFormateException");
}
}
}
Open notepad type below code and save with file name.html and open with appletviewer.html
<html>
</applet>
</html>
5 b) Aim:
Write a Java program that creates three threads. First thread displays Good Morning for every one second, the
second thread displays Hello for every two seconds and the third thread displays Welcome for every three
seconds.
Description:
The first thread displays Good Morning every one second, the second thread displays Hello every two
seconds and the third thread displays Welcome every three seconds.
The technique used to implement threads here is by extending the Thread class.
While executing a thread, if any interrupt occurs then there arises a java exception.
In such cases, to handle these exceptions thread statements are kept in try-catch blocks.
Program:
class A extends Thread
{
public void run()
{
try
{
for(int i=0;i<5;i++)
{
sleep(1000);
System.out.println("good morning");
}
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}
t1.start();
t2.start();
t3.start();
}
}
Week 6:
a) Aim: To write a java program to split a given text file into n parts. Name each part as the name of theoriginal
file followed by .part where n is the sequence number of the part file.
Description:
BufferedReader br = new BufferedReader(new FileReader(inputfile));
String strLine;
if (strLine!= null)
{
strLine=strLine+"\r\n";
fw.write(strLine);
}
}
}
Procedure:
Declare variables inputfile as String type nol as double type
Take File data type and file as object pass inputfile to File constructor
Create Scanner class object
Declare count variable and assign to zero
Count no. if lines using while loop ,hasNextLine() and nextLine() methods and print no.of lines
Find equals parts of file using double temp = (count/nol);
Declare temp1 variable and do typecasting
Find split files using BufferedReader
Object Oriented Programming Through Java Page 252
Program:
import java.io.*;
import java.util.Scanner;
double nol = 5.0; // No. of lines to be split and saved in each output file
int count = 0;
while (scanner.hasNextLine())
{
scanner.nextLine();
count++;
}
System.out.println("Lines in the file: " + count); // Displays no. of lines in the input file
double temp = (count/nol);
String strLine;
if (strLine != null)
{
strLine = strLine+"\r\n";
fw.write(strLine);
}
}
fw.close();
}
br.close();
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
}
Output:
D:\ACEM\II CSE Bsection>javac SplitFiles1.java
D:\ACEM\II CSE Bsection>java SplitFiles1
Lines in the file: 11
No. of files to be generated :3
File1,File2,File3
B) Aim: Write a Java program that reads a file name from the user, displays information about whether the
file exists, whether the file is readable, or writable and the length of the file in bytes.
Description:
A file is a named location that can be used to store related information.
For example, main.java is a Java file that contains information about the Java program.
Procedure:
Create a class FileDemo. Get the file name from the user .
Use the file functions and display the information about the file.
getName() displays the name of the file.
getPath() diplays the path name of the file.
if(f1.exists())
System.out.println(" THE FILE EXISTS ");
else
System.out.println(" THE FILE DOES NOT EXISTS ");
if(f1.canRead())
System.out.println(" THE FILE CAN BE READ ");
else
System.out.println(" THE FILE CANNOT BE READ ");
if(f1.canWrite())
System.out.println(" WRITE OPERATION IS PERMITTED ");
else
System.out.println(" WRITE OPERATION IS NOT PERMITTED ");
}
}
Object Oriented Programming Through Java Page 255
Output:
D:\ACEM\II CSE Bsection>javac FileDemo.java
D:\ACEM\II CSE Bsection>java FileDemo
Enter the file name
Test.txt
FILE INFORMATION
*****************
NAME OF THE FILE Test.txt
PATH OF THE FILE Test.txt
THE FILE EXISTS
THE FILE CAN BE READ
WRITE OPERATION IS PERMITTED
LENGTH OF THE FILE 102 bytes
Week 7
Aim: Write a java program that displays the number of characters, lines and words in a text file.
Description:
File(String pathname):
This function is present under the java.io.File package.
It creates a new File instance by converting the given pathname string into an abstract pathname.
FileInputStream(File file) :
This function is present under the java.io.FileInputStream package.
It creates a FileInputStream by opening a connection to an actual file named by the File object file in
the file system.
InputStreamReader(InputStream in):
This function is present under the java.io.InputStreamReader package.
It creates an InputStreamReader that uses the default charset.
BufferedReader(Reader in):
This function is present under the java.io.BufferedReader package.
It creates a buffering character-input stream that uses a default-sized input buffer.
Program:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
String line;
int lines=0;
int wordCount = 0;
int characterCount = 0;
b) Aim : Write a java program that reads a file and displays the file on the screen with line number beforeeach line.
Description:
import java packages
Create class ReadFileForLine
Create main function
public static void main( String[] args)throws IOException and write rest of the code
class ReadFileForLine
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of the file: ");
String file_name = input.nextLine();
File f = new File(file_name);
int i;
boolean wrong=true;
while(wrong)
{
try
{
FileReader finp = new FileReader(f);
LineNumberReader linereader = new LineNumberReader(finp);
while((i=linereader.read())!=-1)
{
System.out.print("Line #: "+(linereader.getLineNumber()+1));
System.out.println((char)i+linereader.readLine());
}
wrong=false;
}
catch(FileNotFoundException e)
{
System.out.println("File does not exist, ");
System.out.print("Enter another file name:");
file_name = input.nextLine();
f = new File(file_name);
}
catch(IOException e)
{
System.out.println("Cannot Read file:");
}
}
}
}
Object Oriented Programming Through Java Page 258
Output:
D:\ACEM\II CSE Bsection>javac ReadFileForLine.java
D:\ACEM\II CSE Bsection>java ReadFileForLine
Enter the name of the file: smilejava.txt
Line #: 1hello
Line #: 2keep
Line #: 3smiling
Line #: 4java
Line #: 5is
Line #: 6easy
Week 8
a) Aim:
Write a Java program that correctly implements the producer-consumer problem using the
concept of inter thread communication.
Description:
The producer produces the item and the consumer consumes the same. But here, the consumer can not
consume until the producer produces the item, and producer can not produce until the consumer
consumes the item that already been produced.
So here, the consumer has to wait until the producer produces the item, and the producer also needs to
wait until the consumer consumes the same.
Program:
import java.util.LinkedList;
public class ProduceConsumer
{
public static void main(String[] args) throws InterruptedException
{
final PC pc = new PC(); // Object of a class that has both produce() and consume() methods
b) Aim: Develop a Java application for stack operation using Buttons and JOptionPane input and
Message dialog box.
Description:
This dialogbox defined in JOptionPane class in Java is used when you wish to get some input from the
user.
Like if you want user to enter his bank account number to display his transaction details you can use
showInputDialog to prompt user.
After entering the value in the textbox when user presses OK button the input gets stored in a string
variable on left hand variable of the assignment operator.
num1=Integer.parseInt(JOptionPane.showInputDialog("Number1="));
num2=Integer.parseInt(JOptionPane.showInputDialog("Number2="));
sum=num1+num2;
sub=num1-num2;
mul=num1*num2;
div=num1/num2;
Description:
we can use Applet concepts for blinking eyes
we can use paint() method and drawstring() methods
we draw symbols like rectangle, oval like many for many operations in this code
Program:
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
try
{
Thread.sleep(900);
}
catch (Exception e)
{
System.out.println("killed while sleeping");
}
this.repaint(100);
}
}
public void init()
{
this.C = new MyCanvas();
this.setLayout(new BorderLayout());
this.add(C, BorderLayout.CENTER);
C.setBackground(Color.GRAY);
}
private MyCanvas C;
}
/* <applet code = "A.class" width=200 height=200>
</applet>
*/
add(redLight);
add(yellowLight);
add(greenLight);
add(msg);
msg.setFont(new Font("Serif", Font.BOLD, 20));
}
if(redLight.getState() == true)
{
redLight.setForeground(Color.RED);
msg.setForeground(Color.RED);
msg.setText("STOP");
}
else
if(yellowLight.getState() == true)
{
yellowLight.setForeground(Color.YELLOW);
msg.setForeground(Color.YELLOW);
msg.setText("READY");
}
else
{
greenLight.setForeground(Color.GREEN);
msg.setForeground(Color.GREEN);
msg.setText("GO");
}
}
}
10 a) Aim: Develop a Java application to implement the opening of a door while opening man should
present before hut and closing man should disappear
Description:
Use awt for applet classes
Use animation classes
ImageIcon for image in the below code
Program:
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
class Animation extends JFrame implements ActionListener
{
Container c;
JButton b1,b2;
JLabel lb1;
c.setLayout(null);
lb1.setBounds(50,10,500,500);
b1 = new JButton("Open");
b2 = new JButton("Close");
b1.addActionListener(this);
b2.addActionListener(this);
b1.setBounds(650,240,70,40);
b2.setBounds(650,320,70,40);
c.add(lb1);
c.add(b1);
c.add(b2);
}
lb1.setIcon(ii2);
else
lb1.setIcon(ii1);
ob.setSize(800,600);
ob.setVisible(true);
ob.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Output:
10 b) Aim: Develop a Java application by using JtextField to read decimal values and converting a decimal
number into a binary number then print the binary value in another JtextField.
Description:
Binary to decimal conversion is done to convert a number given in the binary system to its
equivalent in the decimal number system.
A number system is a format to represent numbers in a certain way.
Binary Number System – The binary number system is used in computers and electronic systems to
represent data, and it consists of only two digits which are 0 and 1.
Input: 33 Output: 100001
p1.add(q1);
p2.add(clickbutton);
p3.add(new JLabel("Decimal to Binary:"));
p3.add(q2);
clickbutton.addActionListener(this);
}
String[]conversion=new String[8];
String[]complete=new String[4];
counter=0;
complete[0]="";
do
{
dec=user%2;
conversion[counter]=String.valueOf(dec);
complete[0]=conversion[counter]+complete[0];
user=user/2;
counter=counter+1;
}
while(user !=0);
q2.setText(String.valueOf(complete[user]));
}
}
}
/*
<applet code="Rottenapplet.class" height=300 width=300>
</applet> */
Output:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
String msg="";
12 A) Aim: Develop a Java application to find the maximum value from the given type of elements using a
generic function
Description:
1. Create a class Myclass to implement generic class and generic methods.
2. Get the set of the values belonging to specific data type.
3. Create the objects of the class to hold integer,character and double values.
4. Create the method to compare the values and find the maximum value stored in the array.
5. Invoke the method with integer, character or double values . The output will be displayed based on the
data type passed to the method.
MyClass(T[] o)
{
vals = o;
}
public T min()
{
T v = vals[0];
public T max()
{
T v = vals[0];
for(int i=1; i < vals.length;i++)
if(vals[i].compareTo(v) > 0)
v = vals[i];
return v;
}
}
class MaxMinUseGeneric
{
public static void main(String args[])
{
int i;
12 b) Aim: Develop a Java application that works as a simple calculator. Use a grid layout to arrange buttonsfor the
digits and for the +, -,*, % operations. Add a text field to display the result
Description:
GridLayout is one of the Layout managers.
A layout manager automatically arranges your controls with in a window by using some type of algorithm.
Grid Layout lays out component in a two dimensional grid.
When you instantiate a GridLayout,you define the number of rows and columns
Program:
import javax.swing.*;
import java.awt.*;
import
java.awt.event.*;
public class Calculator extends JApplet
{
public void init()
{
CalculatorPanel calc=new CalculatorPanel();
getContentPane().add(calc);
}
}
JButton n1,n2,n3,n4,n5,n6,n7,n8,n9,n0,plus,minus,mul,div,dot,equal;
if((result.getText()).equals("0"))
result.setText(no);
else if(lastCommand=="=")
{
result.setText(no);
lastCommand=null;
}
else
result.setText(result.getText()+no);
}
public CalculatorPanel()
{
setLayout(new BorderLayout());
result.setEditable(false);
result.setSize(300,200);
add(result,BorderLayout.NORTH);
n7=new JButton("7");
panel.add(n7);
n7.addActionListener(this);
n8=new JButton("8");
panel.add(n8);
n8.addActionListener(this);
n9=new JButton("9");
panel.add(n9);
n9.addActionListener(this);
n4=new JButton("4");
panel.add(n4);
n4.addActionListener(this);
n5=new JButton("5");
panel.add(n5);
n5.addActionListener(this);
n6=new JButton("6");
panel.add(n6);
n6.addActionListener(this);
mul=new JButton("*");
panel.add(mul);
mul.addActionListener(this);
n1=new JButton("1");
panel.add(n1);
n1.addActionListener(this);
n2=new JButton("2");
panel.add(n2);
n2.addActionListener(this);
n3=new JButton("3");
panel.add(n3);
n3.addActionListener(this);
minus=new JButton("-");
panel.add(minus);
minus.addActionListener(this);
dot=new JButton(".");
panel.add(dot);
dot.addActionListener(this);
n0=new JButton("0");
panel.add(n0);
n0.addActionListener(this);
equal=new JButton("=");
panel.add(equal);
equal.addActionListener(this);
add(panel,BorderLayout.CENTER);
assign("3");
else if(ae.getSource()==n4)
assign("4");
else if(ae.getSource()==n5)
assign("5");
else if(ae.getSource()==n6)
assign("6");
else if(ae.getSource()==n7)
assign("7");
else if(ae.getSource()==n8)
assign("8");
else if(ae.getSource()==n9)
assign("9");
else if(ae.getSource()==n0)
assign("0");
else if(ae.getSource()==dot)
{
if(((result.getText()).indexOf("."))==-1)
result.setText(result.getText()+".");
}
else if(ae.getSource()==div)
{
preRes=Double.parseDouble(result.getText());
lastCommand="/";
result.setText("0");
}
else if(ae.getSource()==equal)
{
secVal=Double.parseDouble(result.getText());
if(lastCommand.equals("/"))
res=preRes/secVal;
else if(lastCommand.equals("*"))
res=preRes*secVal;
else if(lastCommand.equals("-"))
res=preRes-secVal;
else if(lastCommand.equals("+"))
res=preRes+secVal;
result.setText(" "+res);
lastCommand="=";
}
else
if(ae.getSource()==mul)
{
preRes=Double.parseDouble(result.getText());
lastCommand="*";
result.setText("0");
}
else
if(ae.getSource()==plus)
{
preRes=Double.parseDouble(result.getText());
lastCommand="+";
result.setText("0");
}
}
}
Object Oriented Programming Through Java Page 283
/*
<applet code="Calculator.class" height=300 width=200>
</applet>
*/
Output:
13 Aim: . Develop a Java application to establish a JDBC connection, create a table student with propertiesname,
register number, mark1, mark2, mark3. Insert the values into the table by using java and display the information
of the students at front end.
Description:
Steps For Connectivity Between Java Program and Database
1. Import the Packages
2. Load the drivers using the forName() method
3. Register the drivers using DriverManager
4. Establish a connection using the Connection class object
5. Create a statement
6. Execute the query
7. Close the connections
Program:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
stmt.executeUpdate(sql);
ps1 = conn.prepareStatement(qry);
ResultSet rs = ps1.executeQuery(qry);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
Output:
1 records inserted