2 PDF
2 PDF
(1) Packages
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
For example
1. javac -d . Simple.java
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. mypack.Simple etc to run the class.
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents
the current folder.
1. import package.*;
2. import package.classname;
3. fully qualified name.
3 |M.sc sem I OOPs USING JAVA
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.
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello
It is generally used when two packages have same class name e.g. java.util and java.sql packages contain
Date class.
If you import a package, all the classes and interface of that package will be imported excluding the classes
and interfaces of the subpackages. Hence, you need to import the subpackage as well.
5 |M.sc sem I OOPs USING JAVA
Note: Sequence of the program must be package then import then class.
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the package
further.
Let's take an example, Sun Microsystem has definded a package named java that contains many classes
like System, String, Reader, Writer, Socket etc. These classes represent a particular group e.g. Reader and
Writer classes are for Input/Output operation, Socket and ServerSocket classes are for networking etc and
so on. So, Sun has subcategorized the java package into subpackages such as lang, net, io etc. and put the
Input/Output related classes in io package, Server and ServerSocket classes in net packages and so on.
Example of Subpackage
1. package com.javatpoint.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
To Compile: javac -d . Simple.java
Output:Hello subpackage
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
To Compile:
To Run:
To run this program from e:\source directory, you need to set classpath of the directory where the class file resides.
To run this program from e:\source directory, you can use -classpath switch of java that tells where to look
for class file. For example:
o Temporary
o By setting the classpath in the command prompt
o By -classpath switch
o Permanent
o By setting the classpath in the environment variables
o By creating the jar file, that contains all the class files, and copying the jar file in the jre/lib/ext folder.
Rule: There can be only one public class in a java source file and it must be saved by the public class
name.
1. //save as C.java otherwise Compilte Time Error
2.
3. class A{}
4. class B{}
5. public class C{}
1. //save as A.java
2.
3. package javatpoint;
4. public class A{}
1. //save as B.java
2.
3. package javatpoint;
4. public class B{}
(2) interfaces
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
8 |M.sc sem I OOPs USING JAVA
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.
Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }
In other words, Interface fields are public, static and final by default, and the methods are public and
abstract.
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
10 |M.sc sem I OOPs USING JAVA
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }
Test it Now
Output:
Hello
File: TestInterface1.java
(3) ENCAPSULATION
11 |M.sc sem I OOPs USING JAVA
Encapsulation in Java
Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a
capsule which is mixed of several medicines.
We can create a fully encapsulated class in Java by making all the data members of the class private. Now
we can use setter and getter methods to set and get the data in it.
It provides you the control over the data. Suppose you want to set the value of id which should be greater
than 100 only, you can write the logic inside the setter method. You can write the logic not to store the
negative numbers in the setter methods.
It is a way to achieve data hiding in Java because other class will not be able to access the data through
the private data members.
The encapsulate class is easy to test. So, it is better for unit testing.
The standard IDE's are providing the facility to generate the getters and setters. So, it is easy and fast to
create an encapsulated class in Java.
File: Student.java
14. }
15. }
File: Test.java
Output:
vijay
Read-Only class
Now, you can't change the value of the college data member which is "AKG".
Write-Only class
Now, you can't get the value of the college, you can only change the value of college data member.
File: Account.java
23. }
24. public void setEmail(String email) {
25. this.email = email;
26. }
27. public float getAmount() {
28. return amount;
29. }
30. public void setAmount(float amount) {
31. this.amount = amount;
32. }
33.
34. }
File: TestAccount.java
Before learning the Java abstract class, let's understand the abstraction in Java first.
Abstraction in Java
15 |M.sc sem I OOPs USING 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, for example, sending
SMS where you type the text and send the message. You don't know the internal processing about the
message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the method.
In this example, Bike is an abstract class that contains only one abstract method run. Its implementation is
provided by the Honda class.
Mostly, we don't know about the implementation class (which is hidden to the end user), and an object of
the implementation class is provided by the factory method.
A factory method is a method that returns the instance of the class. We will learn about the factory method
later.
In this example, if you create the instance of Rectangle class, draw() method of Rectangle class will be
invoked.
File: TestAbstraction1.java
File: TestAbstraction2.java
18 |M.sc sem I OOPs USING JAVA
Note: If you are beginner to java, learn interface first and skip this example.
1. interface A{
2. void a();
3. void b();
4. void c();
19 |M.sc sem I OOPs USING JAVA
5. void d();
6. }
7.
8. abstract class B implements A{
9. public void c(){System.out.println("I am c");}
10. }
11.
12. class M extends B{
13. public void a(){System.out.println("I am a");}
14. public void b(){System.out.println("I am b");}
15. public void d(){System.out.println("I am d");}
16. }
17.
18. class Test5{
19. public static void main(String args[]){
20. A a=new M();
21. a.a();
22. a.b();
23. a.c();
24. a.d();
25. }}
The programs which run under a GUI has a specific set of graphic elements so that after learning a specific
interface, a user can use these programs without learning new commands.
Xerox 8010 Information system was the first GUI-centric computer operating model. It was developed at
Xerox PARC by Alan Kay, Douglas Engelbart and their associates.
As of 2014, the most popular GUIs are Microsoft Windows and Mac OS X. And, if we talk about mobile
devices, the Apple's IOS and Google's Android Interface are the widely used GUIs.
o Pointing device: It allows you move the pointer and select objects on the screen, e.g. mouse or trackball.
o Icons: It refers to small images on the display screen that represent commands, files, windows etc. Using
pointer and pointing device, you can execute these commands.
o Desktop: It is the display screen that contains the icons.
1. import java.applet.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class EventApplet extends Applet implements ActionListener{
5. Button b;
6. TextField tf;
7.
8. public void init(){
9. tf=new TextField();
10. tf.setBounds(30,40,150,20);
11.
12. b=new Button("Click");
13. b.setBounds(80,150,60,50);
14.
15. add(b);add(tf);
16. b.addActionListener(this);
17.
21 |M.sc sem I OOPs USING JAVA
18. setLayout(null);
19. }
20.
21. public void actionPerformed(ActionEvent e){
22. tf.setText("Welcome");
23. }
24. }
In the above example, we have created all the controls in init() method because it is invoked only once.
myapplet.html
1. <html>
2. <body>
3. <applet code="EventApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
22 |M.sc sem I OOPs USING JAVA
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Registration Methods
For registering the component with the Listener, many classes provide the registration methods. For
example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
1. Within class
2. Other class
3. Anonymous class
1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent extends Frame implements ActionListener{
4. TextField tf;
5. AEvent(){
6.
7. //create components
8. tf=new TextField();
9. tf.setBounds(60,50,170,20);
10. Button b=new Button("click me");
11. b.setBounds(100,120,80,30);
12.
13. //register listener
14. b.addActionListener(this);//passing current instance
15.
16. //add components and set size, layout and visibility
17. add(b);add(tf);
18. setSize(300,300);
19. setLayout(null);
20. setVisible(true);
21. }
22. public void actionPerformed(ActionEvent e){
23. tf.setText("Welcome");
24. }
25. public static void main(String args[]){
26. new AEvent();
27. }
28. }
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above example
that sets the position of the component it may be button, textfield etc.
1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent2 extends Frame{
4. TextField tf;
5. AEvent2(){
6. //create components
7. tf=new TextField();
8. tf.setBounds(60,50,170,20);
9. Button b=new Button("click me");
10. b.setBounds(100,120,80,30);
11. //register listener
12. Outer o=new Outer(this);
13. b.addActionListener(o);//passing outer class instance
14. //add components and set size, layout and visibility
15. add(b);add(tf);
16. setSize(300,300);
17. setLayout(null);
18. setVisible(true);
19. }
20. public static void main(String args[]){
21. new AEvent2();
22. }
23. }
1. import java.awt.event.*;
2. class Outer implements ActionListener{
3. AEvent2 obj;
4. Outer(AEvent2 obj){
5. this.obj=obj;
6. }
7. public void actionPerformed(ActionEvent e){
8. obj.tf.setText("welcome");
9. }
10. }
1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent3 extends Frame{
4. TextField tf;
25 |M.sc sem I OOPs USING JAVA
5. AEvent3(){
6. tf=new TextField();
7. tf.setBounds(60,50,170,20);
8. Button b=new Button("click me");
9. b.setBounds(50,120,80,30);
10.
11. b.addActionListener(new ActionListener(){
12. public void actionPerformed(){
13. tf.setText("hello");
14. }
15. });
16. add(b);add(tf);
17. setSize(300,300);
18. setLayout(null);
19. setVisible(true);
20. }
21. public static void main(String args[]){
22. new AEvent3();
23. }
24. }
Advantage of Applet
There are many advantages of applet. They are as follows:
Drawback of Applet
Do You Know
o Who is responsible to manage the life cycle of an applet ?
o How to perform animation in applet ?
o How to paint like paint brush in applet ?
o How to display digital clock in applet ?
o How to display analog clock in applet ?
o How to communicate two applets ?
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is the subclass
of Component.
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
27 |M.sc sem I OOPs USING JAVA
4. Applet is stopped.
5. Applet is destroyed.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
1. 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.
1. By html file.
2. By appletViewer tool (for testing purpose).
To execute the applet by html file, create an applet and compile it. After that create an html file and place
the applet code in html file. Now click the html file.
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome",150,150);
8. }
9.
10. }
Note: class must be public because its object is created by Java Plugin software that resides on the
browser.
myapplet.html
1. <html>
2. <body>
3. <applet code="First.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome to applet",150,150);
8. }
9.
10. }
11. /*
29 |M.sc sem I OOPs USING JAVA
The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.
3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.
4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser, tabbedpane etc.
5) AWT doesn't follows MVC(Model View Controller) where Swing follows MVC.
model represents data, view represents presentation and
controller acts as an interface between model and view.
What is JFC
30 |M.sc sem I OOPs USING JAVA
The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop
applications.
Do You Know
The methods of Component class are widely used in java swing that are given below.
Method Description
public void setLayout(LayoutManager m) sets the layout manager for the component.
public void setVisible(boolean b) sets the visibility of the component. It is by default false.
We can write the code of swing inside the main(), constructor or any other method.
File: FirstSwingExample.java
1. import javax.swing.*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFrame
5.
6. JButton b=new JButton("click");//creating instance of JButton
7. b.setBounds(130,100,100, 40);//x axis, y axis, width, height
8.
9. f.add(b);//adding button in JFrame
10.
11. f.setSize(400,500);//400 width and 500 height
12. f.setLayout(null);//using no layout managers
13. f.setVisible(true);//making the frame visible
32 |M.sc sem I OOPs USING JAVA
14. }
15. }
File: Simple.java
1. import javax.swing.*;
2. public class Simple {
3. JFrame f;
4. Simple(){
5. f=new JFrame();//creating instance of JFrame
6.
7. JButton b=new JButton("click");//creating instance of JButton
8. b.setBounds(130,100,100, 40);
9.
10. f.add(b);//adding button in JFrame
11.
12. f.setSize(400,500);//400 width and 500 height
13. f.setLayout(null);//using no layout managers
14. f.setVisible(true);//making the frame visible
15. }
16.
17. public static void main(String[] args) {
18. new Simple();
19. }
20. }
The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that sets the position
of the button.
File: Simple2.java
1. import javax.swing.*;
2. public class Simple2 extends JFrame{//inheriting JFrame
33 |M.sc sem I OOPs USING JAVA
3. JFrame f;
4. Simple2(){
5. JButton b=new JButton("click");//create button
6. b.setBounds(130,100,100, 40);
7.
8. add(b);//adding button on frame
9. setSize(400,500);
10. setLayout(null);
11. setVisible(true);
12. }
13. public static void main(String[] args) {
14. new Simple2();
15. }}
download this example
What we will learn in Swing Tutorial
o JButton class
o JRadioButton class
o JTextArea class
o JComboBox class
o JTable class
o JColorChooser class
o JProgressBar class
o JSlider class
o Digital Watch
o Graphics in swing
o Displaying image
o Edit menu code for Notepad
o OpenDialog Box
o Notepad
o Puzzle Game
o Pic Puzzle Game
o Tic Tac Toe Game
o BorderLayout
o GridLayout
o FlowLayout
o CardLayout
34 |M.sc sem I OOPs USING JAVA
Error handling let us handle these errors by taking appropriate action and run program smoothly. Various types of
errors can be handled by error handling.
You need to catch the error and run your program smoothly by rectifying the error. Perl provides a number of ways
to do so which are illustrated below.
1. use strict;
2. use warnings;
3. open(my $fh, '>', 'sssit/javatpoint/file1.txt');
4. print $fh "Example to show Error Handling\n";
5. close $fh;
6. print "done\n";
Output:
Look at the above output, the script keeps on running on encountering error printing 'done'.
In 'open or die' function, on left side we have open() function. On right side we have die() function.
If open() function returns true, then script goes on next line and die() function doesn't execute.
If open() function returns false, then script goes on die() function which throws an exception and exit the script.
Here, in this example we have given the wrong path of the file due to which die() function will execute and exit the
script.
1. use strict;
2. use warnings;
35 |M.sc sem I OOPs USING JAVA
Output:
Died at script.pl
In the output, as we use die() function script exit on encountering error. Hence, 'done' is not printed.
1. use strict;
2. use warnings;
3. open(my $fh, '>', 'sssit/javatpoint/report.txt')
4. or die "Could not open file due to 'sssit/javatpoint/report.txt'";
5. close $fh;
6. print "done\n";
Output:
Look at the above output, we got an explanation about the error in our script.
1. use strict;
2. use warnings;
3. my $filename = 'sssit/javatpoint/file1.txt';
4. open(my $fh, '>', $filename) or die "Could not open file '$filename' $!";
5. close $fh;
6. print "done\n";
Output:
36 |M.sc sem I OOPs USING JAVA
Could not open file 'sssit/javatpoint/file1.txt' No such file or directory
1. use strict;
2. use warnings;
3. my $filename = 'sssit/javatpoint/file1.txt';
4. open(my $fh, '>', $filename) or warn "Can't open file";
5. print "done\n";
Output:
Look at the above output, we have printed 'done' to show that execution continues even after printing warning
message.
1. use strict;
2. use warnings;
3. use Carp;
4. my $filename = 'sssit/javatpoint/file1.txt';
5. open(my $fh, '>', $filename) or confess($!);
6. print "done\n";
Output:
If there are syntax errors, eval block will fail. But if a runtime error occurs, the script carries on running.
use strict; use warnings; my $result = eval { my $x = 10; my $y = 0; my $result2 = $x/$y; print "$result2"; }; print "Script is still
running!\n"; unless($result) { print $@; }
Output:
37 |M.sc sem I OOPs USING JAVA
Script is still running!
Illegal division by zero
Look at the above output, script keeps on running as their is no syntax error.
The confess() function is used inside carp package. For a larger script, it is better to use confess function.
In this tutorial, we will learn about Java exceptions, it's types, and the difference between checked and
unchecked exceptions.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
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.
Let's consider a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
38 |M.sc sem I OOPs USING JAVA
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the rest of the
code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we perform
exception handling, the rest of the statements will be executed. That is why we use exception handling
in Java.
Do You Know?
1. Checked Exception
2. Unchecked Exception
3. Error
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.
39 |M.sc sem I OOPs USING JAVA
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
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception code. It means we
can't use try block alone. The try block must be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block which means
we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is executed whether an
exception is handled or not.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception
in the method. It doesn't throw an exception. It is always used with method signature.
JavaExceptionExample.java
Output:
In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.
1. int a=50/0;//ArithmeticException
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
1. String s=null;
2. System.out.println(s.length());//NullPointerException
If the formatting of any variable or number is mismatched, it may result into NumberFormatException.
Suppose we have a string variable that has characters; converting this variable into digit will cause
NumberFormatException.
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other
reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you use JDBC drivers
provided by the vendor of your database instead of the JDBC-ODBC Bridge.
Advantages:
o easy to use.
o can be easily connected to any database.
Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC function calls.
42 |M.sc sem I OOPs USING JAVA
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into
native calls of the database API. It is not written entirely in java.
Advantage:
Disadvantage:
Advantage:
o No client side library is required because of application server that can perform many tasks like auditing, load
balancing, logging etc.
Disadvantages:
4) Thin diver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as
thin driver. It is fully written in Java language.
44 |M.sc sem I OOPs USING JAVA
Advantage:
1. Class.forName("oracle.jdbc.driver.OracleDriver");
1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");
1. Statement stmt=con.createStatement();
1. con.close();
Note: Since Java 7, JDBC has ability to use try-with-resources statement to automatically close
resources of type Connection, ResultSet, and Statement.
(14)