JavaRecrdupdated 1
JavaRecrdupdated 1
Java is a programming language and a platform. Java is a high level, robust, object-oriented and
secure programming language.
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.
Features of Java:-
Simple
Object-Oriented
Portable
Platform independent
Secured
Robust
Architecture neutral
Interpreted
High Performance
Multithreaded
Distributed
Dynamic
Application
According to Sun, 3 billion devices run Java. There are many devices where Java is currently used.
Some of them are as follows:
Mobile
Embedded System
Smart Card
Robotics
Games, etc.
There are mainly 4 types of applications that can be created using Java programming:
1) Standalone Application
Standalone applications are also known as desktop applications or window-based applications.
These are traditional software that we need to install on every machine. Examples of standalone
application are Media player, antivirus, etc. AWT and Swing are used in Java for creating
standalone applications.
2) Web Application
An application that runs on the server side and creates a dynamic page is called a web application.
Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for creating web
applications in Java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is called an enterprise
application. It has advantages like high-level security, load balancing, and clustering. In
Java, EJB is used for creating enterprise applications.
4) Mobile Application
An application which is created for mobile devices is called a mobile application. Currently, Android
and Java ME are used for creating mobile applications.
It is a Java programming platform. It includes Java programming APIs such as [Link], [Link],
[Link], [Link], [Link], [Link] etc. It includes core topics like OOPs, String, Regex,
Exception, Inner classes, Multithreading, I/O Stream, Networking, AWT, Swing, Reflection,
Collection, etc.
It is an enterprise platform that is mainly used to develop web and enterprise applications. It is built
on top of the Java SE platform. It includes topics like Servlet, JSP, Web Services, EJB, JPA, etc.
4) JavaFX
It is used to develop rich internet applications. It uses a lightweight user interface API
In this page, we will learn about the basics of OOPs. Object-Oriented Programming is a paradigm
that provides many concepts, such as inheritance, data binding, polymorphism, etc.
Simula is considered the first object-oriented programming language. The programming paradigm
where everything is represented as an object is known as a truly object-oriented programming
language.
The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.
The main aim of object-oriented programming is to implement real-world entities, for example,
object, classes, abstraction, inheritance, polymorphism, etc.
OOPs (Object-Oriented Programming System)
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects. It
simplifies software development and maintenance by providing some concepts:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
class Add {
[Link]("The sum of " + number1 + " and " + number2 + " is: " + sum);
o/p:
class Fact
int n=6;
int fact=1;
{
fact=fact*i;
O/P:
import [Link];
int rev=0,num,num1,rem;
[Link]("enter a number");
num=[Link]();
num1=num;
while(num>0)
rem=num%10;
rev=rev*10+rem;
num=num/10;
O/P
enter a number
689
class Fibo
{
int f=0,f1=1,f2,count=10;
[Link](f);
[Link](f1);
for(int i=2;i<count;i++)
f2=f+f1;
[Link](f2);
f=f1;
f1=f2; } } }
O/P:
0 1 1 2 3 5 8 13 21 34
class Multi
{ int n=4;
for(int i=1;i<=10;i++)
O/P:
4x1=4
4x2=8
4x3=12
4x4=16
4x5=20
4x6=24
4x7=28
4x8=32
4x9=36
4x10=40
Class: A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created. It is a logical entity. It can't be physical.
class <class_name>
field;
method;
Object: An entity that has state and behaviour is known as an object. It can be physical or logical
entity. An object can be defined as an instance of a class. An object contains an address and take
up some space to memory.
Syntax:
Keyword
class Student{
//defining fields
String name;
[Link]([Link]);
Output:
0
null
class Student
int id;
String name;
[Link]([Link]);
[Link]([Link]);
O/P
Null
class Student2
int id;
String name;
class Stud1
[Link]=100;
[Link]="Sandhya";
[Link]="Vanditha";
O/P
C:\Users\Student\Desktop\CSE-C>java Stud1
100 Sandhya
101 Vanditha
Data types specify the different sizes and values that can be stored in the variable or constants.
These are two types of datatypes in java. Each data type is predefined.
Primitive Datatype
Non-primitive Datatype
Primitive Datatype: In Java, primitive data types are the building blocks of data manipulation. These
are the basic data types.
In Java, there are mainly eight primitive data types which are as follows.
In Java, non-primitive data types are also known as reference data types. It is used to store
complex objects rather than simple values. Non-Primitive data types in java are user defined data
types & they can be easily created or modified by the user.
Class
String
Array
Interfaces
char ch = 'z';
byte size = 2;
O/P
C:\Users\Student\Desktop\CSE-C>javac [Link]
C:\Users\Student\Desktop\CSE-C>java Prdatatype
boolean: true
char: z
integer: 1234
byte: 2
short: 78
float: 2.4546778
double: 3.8
long: 1888889
Variables:
Variable are container used to store data values. They are fundamental elements for manipulating
and referencing information within a program.
int data=50;
A variable is assigned with a data type. Which determines the kind of data it can hold.
Types of Variables
local variable
instance variable
static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this variable
only within that method and the other methods in the class aren't even aware that the variable
exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared among
instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can create a
single copy of the static variable and share it among all the instances of the class. Memory
allocation for static variables happens only once when the class is loaded in the memory.
public class A
int insvar=25;
void someMethod()
{
A obj1=new A();
[Link]([Link]);
[Link]([Link]);
//[Link]();
O/P :
C:\Users\Student\Desktop\java programs>java A
30
25
Type Casting
Type casting is when you assign a value of one primitive data type to another type.
Widening Casting (automatically) - converting a smaller type to a larger type size is also called
Implicit conversion. byte -> short -> char -> int -> long -> float -> double
Narrowing Casting (manually) - converting a larger type to a smaller size type is also called Explicit
conversion. double -> float -> long -> int -> char -> short -> byte
class ITD
int num=12;
double data=num;
}
}
O/P:
C:\Users\Student\Desktop>java ITD
class DTI
double num=12.25;
int data=(int)num;
O/P:
C:\Users\Student\Desktop>java DTI
import [Link];
class Str
int num=13;
String data=[Link](num);
O/P:
C:\Users\Student\Desktop>java Str
import [Link];
class Str1
String data="13";
int num=[Link](data);
O/P:
C:\Users\Student\Desktop>java Str1
Arrays
Java array is an object which contains elements of a similar data type. Additionally, The elements of
an array are stored in a contiguous memory location. It is a data structure where we store similar
elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is
stored on 1st index and so on.
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
Disadvantages
Size Limit: Arrays have a fixed size and do not grow dynamically at runtime.
class TestArray
a[0]=10;
a[1]=20;
a[2]=25;
a[3]=30;
a[4]=40;
[Link](a[i]);
O/P :
10
20
25
30
40
class Testarray3{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
[Link](arr[i][j]+" ");
[Link]();
}}
123
245
445
Expierment-3
Use string and String Tokenizer classes and develop java programs
Java String: In Java, string is basically an object that represents sequence of char values.
An array of characters works as a string in Java.
Java String class provides a lot of methods to perform operations on strings such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
The [Link] class allows you to break a String into tokens. It is simple way to
break a String. It is a legacy class of Java.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.
In the StringTokenizer class, the delimiters can be provided at the time of creation or one by one to
the tokens.
import [Link];
char ch[]={'s','t','r','i','n','g','s'};
[Link](s1);
[Link](s2);
[Link](s3);
o/p:
D:\>javac [Link]
D:\>java StringExample
java
strings
example
import [Link];
String S1="Hello";
String S2="world";
[Link]([Link](S2));
String S3=[Link](S2);
[Link](S3);
[Link]([Link](S2));
String S4="Java,programming,Language";
String[] parts=[Link](",",3);
[Link](part);
[Link]([Link]());
String strrepl=[Link]("o","a");
[Link](strrepl);
String S6=[Link]();
[Link](S6);
//String c=[Link](S7);
[Link]([Link](3));
O/P
-47
Helloworld
false
Java
programming
Language
warld
Hello
lo world
import [Link];
while ([Link]())
[Link]([Link]());
}
}
o/p:
D:\>javac [Link]
D:\>java Simple
my
name
is
Sandhya
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of
a parent object. It is an important part of OOPs (Object Oriented programming system).
The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
//methods;
Fields;
//methods;
Fields;
The extends keyword indicates that you are making a new class that derives from an existing class.
The meaning of "extends" is to increase the functionality.
Class: A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created.
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived
class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is
also called a base class or a parent class.
Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the
fields and methods of the existing class when you create a new class. You can use the same fields
and methods already defined in the previous class.
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
Single Inheritance: When a class inherits another class, it is known as a single inheritance. In the
example given below, Dog class inherits the Animal class, so there is the single inheritance.
Example:
import [Link];
class Animal
void eat()
[Link]("eating...");
void bark()
[Link]("barking..");
[Link]();
[Link]();
}
Output:
barking...
eating...
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the
example given below, BabyDog class inherits the Dog class which again inherits the Animal class,
so there is a multilevel inheritance.
import [Link];
class Animal
void eat()
[Link]("eating...");
void bark()
[Link]("barking..");
}}
void weep()
[Link]("weeping...");
[Link]();
[Link]();
Output:
weeping...
barking...
eating…
When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance
//Hierarchical Inheritance
import [Link];
class Animal
void eat()
[Link]("eating...");
void bark()
[Link]("Barking..");
void meow()
{
[Link]("mewoing..");
class TestHier
[Link]();
[Link]();
Output:
meowing...
eating...
When one class inherits multiple classes, it is known as multiple inheritance. For Example:
class A{
void msg(){[Link]("Hello");}
class B{
void msg(){[Link]("Welcome");}
C obj=new C();
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A
and B classes have the same method and you call it from child class object, there will be ambiguity
to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time error.
To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Abstraction : Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
It cannot be instantiated.
It can have final methods which will force the subclass not to change the body of the method.
Example:
import [Link];
void Brand(String C)
class TestAbs
{
public static void main(String args[])
//Vehicle V=new Vehicle(); Abstract method will never instantiate the objects
B.s=65;
[Link]();
[Link]("Hero Honda");
Output:
Experiment :5
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in
the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in
Java.
In other words, you can say that interfaces can have abstract methods and variables. It cannot have
a method body.
There are mainly three reasons to use interface. They are given below.
Syntax:
interface <interface_name>
// by default.
Example :
import [Link];
interface printable
void print();
[Link]("Hello");
A6 obj=new A6();
[Link]();
Output:
Hello
import [Link];
interface Vehicle
}
public void Brand(String C)
class TestInterfa
//Vehicle V=new Vehicle(); Abstract method will never instantiate the objects
[Link](70);
[Link]("Pulsur");
[Link](45.25);
Output:
Java Package
built-in package
user-defined package
User defined package: These are designed by the developer to categorize classes and packages.
// save as [Link]
package mypack;
[Link](:welcome to package”);
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the
package within the same directory, you can use . (dot).
You need to use fully qualified name e.g. [Link] etc to run the class.
Output:Welcome to package
There are three ways to access the package from outside the package.
import package.*;
import [Link];
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to the
current package.
package pack;
public class A{
//save by [Link]
package mypack;
import pack.*;
class B{
[Link]();
Output:Hello
//save by [Link]
package pack;
public class A{
//save by [Link]
package mypack;
import pack.A;
class B{
[Link]();
Output:Hello
It is generally used when two packages have same class name e.g. [Link] and [Link] packages
contain Date class.
//save by [Link]
package pack;
public class A{
//save by [Link]
package mypack;
class B{
[Link]();
Output:Hello
Exp: [Link]: Develop Java programs using Method overloading and method overriding.
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading
If we have to perform only one operation, having same name of the methods increases the
readability of the program
In Java, Method Overloading is not possible by changing the return type of the method only.
class Adder
return a+b;
return a+b+c;
class TestOverloading1
[Link]([Link](11,11));
[Link]([Link](11,11,11));
Output
22
33
class Adder{
return a+b;}
return a+b;}
class TestOverloading2
[Link]([Link](11,11));
[Link]([Link](12.3,12.6));
Output:
22
24.9
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
In other words, 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.
class Vehicle{
//defining a method
void run()
[Link]("Vehicle is running");
void run()
[Link]();//calling method
Output:
There are mainly two types of exceptions: checked and unchecked. An error is considered as the
unchecked exception. However, according to Oracle, there are three types of exceptions namely:
Checked Exception
Unchecked Exception
Error
Let's see an example of Java Exception Handling in which we are using a try-catch statement to
handle the exception.
import [Link];
try
int d=0;
int data=100/d;
catch(ArithmeticException e)
[Link]("Division by Zero");
}
[Link]("Rest of the code...");
Output :
Exception Handling
[Link]: Develop java programs using Exception handling (using try, catch, throw, throws and finally).
The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application; that is why we need to handle
exceptions.
The [Link] class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:
There are mainly two types of exceptions: checked and unchecked. An error is considered as the
unchecked exception. However, according to Oracle, there are three types of exceptions namely:
Checked Exception
Unchecked Exception
Error
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are known
as checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are
checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
try
int d=0;
int data=15/d;
catch(ArithmeticException e)
[Link]("Division by Zero");
O/P:
D:\SW>javac [Link]
D:\SW>java ExceptionEx
Division by Zero
class MultiCatch
try
int a=[Link];
[Link]("a=" +a);
int b=42/a;
int c[]={1};
c[42]=99;
catch(ArithmeticException e)
catch(ArrayIndexOutOfBoundsException e)
[Link]("ArrayIndexOutOfBoundsException:" +e);
O/P
D:\SW>javac [Link]
D:\SW>java MultiCatch
a=0
We specify the exception object which is to be thrown. The Exception has some message with it
that provides the error description. These exceptions may be related to user inputs, server, etc.
We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used
to throw a custom exception. The syntax of the Java throw keyword is given below.
else {
//main method
validate(13);
Output:
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception. So, it is better for the programmer to provide the
exception handling code so that the normal flow of the program can be maintained.
//method code
import [Link];
class Testthrows1
m();
void p(){
try
n();
catch(Exception e)
[Link]("exception handled");
obj.p();
[Link]("normal flow...");
Output:
exception handled
normal flow...
Java finally block is a block used to execute important code such as closing the connection, etc.
Java finally block is always executed whether an exception is handled or not. Therefore, it contains
all the necessary statements that need to be printed regardless of the exception occurs or not.
[Link]
class TestFinallyBlock {
try{
int data=25/5;
[Link](data);
catch(NullPointerException e){
[Link](e);
finally {
Output:
Case 2: When an exception occur but not handled by the catch block
Let's see the the fillowing example. Here, the code throws an exception however the catch block
cannot handle it. Despite this, the finally block is executed after the try block and then the program
terminates abnormally.
[Link]
try
int data=25/0;
[Link](data);
catch(NullPointerException e){
[Link](e);
}
//executes regardless of exception occured or not
finally {
Exp: [Link]: Develop java programs using Multithreading (using Thread class and Runnable
interface, synchronization).
Thread class:
Thread class provide constructors and methods to create and perform operations on a
[Link] class extends Object class and implements Runnable interface.
Thread()
Thread(String name)
Thread(Runnable r)
1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.
{
[Link]("Thread is running....");
[Link]();
[Link]("hello");
for(int i=0;i<=5;i++)
[Link](i);
Output:
D:\java>javac [Link]
D:\java>java Multi1
hello
Thread is running....
[Link]("Thread");
{
Runnable r1=new TestThread1();
[Link]();
String str=[Link]();
[Link](str);
Output:
D:\java>javac [Link]
D:\java>java TestThread1
my new thread
Thread
Thread synchronization in Java is a mechanism to control the access of multiple threads to shared
resources, ensuring that only one thread can access a resource at a time. This prevents race
conditions, where unpredictable outcomes occur because multiple threads try to update shared
data simultaneously, and data inconsistency, where threads read outdated or corrupted values.
import [Link].*;
class Example
void display()
Thread g=[Link]();
synchronized(this)
for(int i=0;i<=5;i++)
try
[Link](2000);
[Link]([Link]()+" "+i);
catch(InterruptedException e)
{
[Link](e);
Example e;
T(Example e)
this.e=e;
[Link]();
class Tsynch
T t1=new T(ex);
T t2=new T(ex);
T t3=new T(ex);
[Link]();
[Link]();
[Link]();
Output:
javac [Link]
D:\java>java Tsynch
Thread-0 0
Thread-0 1
Thread-0 2
Thread-0 3
Thread-0 4
Thread-0 5
Thread-2 0
Thread-2 1
Thread-2 2
Thread-2 3
Thread-2 4
Thread-2 5
Thread-1 0
Thread-1 1
Thread-1 2
Thread-1 3
Thread-1 4
Thread-1 5
Exp:9 Aim: Develop java programs using collections (using list, set, Map and generics).
Collections in Java
The Collection in Java is a framework that provides an architecture to store and manipulate the
group of objects.
Java Collection means a single unit of objects. Java Collection framework provides many interfaces
(Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet,
LinkedHashSet, TreeSet)
Java Generics: The Java Generics programming is introduced in J2SE 5 to deal with type-safe
objects. It makes the code stable by detecting the bugs at compile time.
Before generics, we can store any type of objects in the collection, i.e., non-generic. Now generics
force the java programmer to store a specific type of objects.
Here, we are using the ArrayList class, but you can use any collection class such as ArrayList,
LinkedList, HashSet, TreeSet, HashMap, Comparator etc.
Algorithm
java List
List in Java provides the facility to maintain the ordered collection. It contains the index-based
methods to insert, update, delete and search the elements. It can have the duplicate elements also.
We can also store the null elements in the list.
The List interface is found in the [Link] package and inherits the Collection interface. It is a factory
of ListIterator interface. Through the ListIterator, we can iterate the list in forward and backward
directions. The implementation classes of List interface are ArrayList, LinkedList, Stack and Vector.
The ArrayList and LinkedList are widely used in Java programming. The Vector class is deprecated
since Java 5.
import [Link].*;
//Creating a List
[Link]("Mango");
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
for(String fruit:list)
[Link](fruit);
Output:
Mango
Apple
Banana
Grapes
Set in Java
The set is an interface available in the [Link] package. The set interface extends the Collection
interface. An unordered collection or list in which duplicates are not allowed is referred to as
a collection interface. The set interface is used to create the mathematical set. The set interface use
collection interface's methods to avoid the insertion of the same
elements. SortedSet and NavigableSet are two interfaces that extend the set implementation.
[Link]
import [Link].*;
[Link]("JavaTpoint");
[Link]("Set");
[Link]("Example");
[Link]("Set");
[Link](data);
Output:
A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is
known as an entry. A Map contains unique keys.
A Map is useful if you have to search, update or delete elements on the basis of a key.
There are two interfaces for implementing Map in java: Map and SortedMap, and three classes:
HashMap, LinkedHashMap, and TreeMap. The hierarchy of Java Map is given below:
A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and
LinkedHashMap allow null keys and values, but TreeMap doesn't allow any null key or value.
//Non-generic
import [Link].*;
[Link](5,"Rahul");
[Link](2,"Jai");
[Link](6,"Amit");
//Traversing Map
Iterator itr=[Link]();
while([Link]()){
[Link] entry=([Link])[Link]();
[Link]([Link]()+" "+[Link]());
} } }
Output:
1 Amit
2 Jai
5 Rahul
6 Amit
Here, we are using the ArrayList class, but you can use any collection class such as ArrayList,
LinkedList, HashSet, TreeSet, HashMap, Comparator etc.
import [Link].*;
class TestGenerics1{
[Link]("rahul");
[Link]("jai");
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
} }}
Output:
rahul
jai
Exp:10 write a java program that handles all mouse events and shows the event name at the center
of the window when a mouse event is fired,[Use adapter classes.]
import [Link].*;
import [Link].*;
import [Link];
import [Link];
public MouseEventDisplay() {
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
[Link]([Link]);
add(eventLabel, [Link]);
addMouseListener(new MouseAdapter() {
@Override
[Link]("Mouse Clicked");
@Override
[Link]("Mouse Pressed");
}
@Override
[Link]("Mouse Released");
@Override
[Link]("Mouse Entered");
@Override
[Link]("Mouse Exited");
});
setVisible(true);
[Link](MouseEventDisplay::new);
Output:
import [Link].*;
try{
catch (Exception e)
finally
if (conn != null) {
try {
[Link] ();
Output:
import [Link];
import [Link];
import [Link];
import [Link];
[Link](sql);
} catch (SQLException e) {
[Link]();
Output:
import [Link];
import [Link];
import [Link];
//stmt =[Link]();
String sql ="INSERT INTO Employees VALUES (10, 'Kriss', 'Kurian', 18)";
[Link](sql);
[Link](sql);
[Link](sql);
/*String sql = "INSERT INTO EMPLOYEES (id, first, last, age) " +
[Link](sql);
} catch (Exception e) {
[Link]();
Output:
import [Link];
import [Link];
import [Link];
String sql ="UPDATE EMPLOYEES SET age = 26, first ='Sireesha', last = 'paga' WHERE id =11";
[Link](sql);
} catch (Exception e) {
[Link]();
Output:
import [Link].*;
ResultSet rs = [Link](query)) {
while ([Link]()) {
int id = [Link]("id");
} catch (SQLException e) {
[Link]();
Output:
import [Link];
import [Link];
import [Link];
import [Link];
public class DeleteRecord {
// [Link](1, 13);
if (rowsDeleted > 0) {
} else {
} catch (SQLException e) {
[Link]();
Additional programs
this keyword
In Java, the this keyword is a reference variable that refers to the current object. It is primarily used
within instance methods or constructors to access members of the object that is currently being
executed.
int x;
public ThisEx(int x)
{
this.x=x;
Output:
D:\java>javac [Link]
D:\java>java ThisEx
value of x =4
super keywod
In Java, the super keyword is a reference variable used by a subclass to refer to its immediate
parent class. It serves as a bridge to access members (fields, methods, and constructors) of the
superclass that might be hidden or overridden
class Bike
void display()
void display()
class TestSuper
[Link]();
Output:
D:\java>javac [Link]
D:\java>java TestSuper
it is a four wheeler
class Bike
void display()
String name="KIA";
void display()
[Link]();
[Link]("\n it is a four wheeler");
class TestSuper1
[Link]();
Output:
D:\java>javac [Link]
D:\java>java TestSuper1
it is a two wheeler
it is a four wheeler
class Bike
Bike()
Car(String n, String B)
{
super(); //it is called super class constructor
void display()
class TestSuper2
[Link]();
D:\java>javac [Link]
D:\java>java TestSuper2
/*constructor
cannot be inherited by subclass , but they cannot be accessed using the super key word
they can use acess modifiers (public, private, protection or default )but cannot be abstract,final
static or synchronized.
Type of constructors
Default constructor(Implicit):- if we do not define any constructors in our class the java compiler
automatically provides a public no-argument constructor. this implicit constructor initializes instance
variales with default values(ex: 0 for int, null for objects, false for boolean)
no argument constructor(Explicit):-
Parameterized constructor
//default constructor
class Rectangle
double length;
double breadth;
length=20;
breadth=35;
double area()
return length*breadth;
Output:
D:\java>javac [Link]
D:\java>java Rectangle
//Parameterized constructor
class Rectangle1
double length;
double breadth;
length=l;
breadth=b;
double area()
return length*breadth;
//No constructor
class Rectangle2
double length;
double breadth;
double area()
return length*breadth;
Output:
import [Link].*;
import [Link].*;
int bytesRead;
[Link](buffer, 0, bytesRead);
[Link]();
[Link]();
[Link]();
} catch (IOException e) {
[Link]();
}
Client program
import [Link].*;
import [Link].*;
if (![Link]()) {
return;
int bytesRead;
[Link](buffer, 0, bytesRead);
[Link]();
[Link]();
} catch (IOException e) {
[Link]();
}