JAVA Data
JAVA Data
object
• Object is an instance of a class • Class is a blueprint or template from which
• Object is a real world entity such as a pen, a objects are created
laptop, a keyboard, etc. • Class is a group of similar type objects.
• Object is a physical entity. • Class is a logical entity.
• Mainly Object is created through new • Class is declared using class keyword like
keyword like class Student{ … }
Student s1=new Student();
Advantages of OOP: 1. Software is easily developed for complex problems. 2. Using OOP, software reuse is
enhanced. 3. Using OOP, software maintenance cost can be reduced. 4. Modularity is achieved using OOP.
5. Software has improved performance. 6. Software quality is improved. 7. Data access is restricted
providing better data security. Disadvantages of OOP: 1. OOP requires intensive testing procedures. 2.
Solving a problem using OOP approach consumes more time than the time taken by structured
FEATURES OR BUZZWORDS OF JAVA, JAVA ENVIRONMENT, Java Virtual Machine (JVM),JAVA API , SIMPLE
JAVA PROGRAM, Compiling the Program
FEATURES OR BUZZWORDS OF JAVA Simple: Java is a simple language. There are various concepts that
make the Java as a simple language. Java is designed to be easy to learn Object-oriented: Java is object-
oriented language like C++, Python etc. Almost everything in Java language is an object based. All program
code and data in Java reside within objects and classes based on the Object model. Platform Independent
Java Language is platform independent language. A platform is the hardware or software environment in
which a program runs. Java code/program can be run on multiple platforms like Windows, Linux, Sun
Solaris, and Mac Os Interpreted: Java is an interpreted language, i.e. programs run directly from the
source code. Java interpreter can execute Java bytecode directly on any computer machine. This machine
should have the interpreter ported on it. Distributed: Java facilitates the building of distributed application
by a collection of classes for use in networked applications.
JAVA ENVIRONMENT • Java environment includes a large number of development tools [part of system
known as JDK (Java Development Kit)] and hundreds of classes and methods [(part of the JSL (Java Standard
Library) The Java Development Kit (JDK) is a software development environment which is used to develop
Java applications.
Java Virtual Machine (JVM): • A JVM is a virtual machine that enables a computer to run Java programs as
well as programs written in other languages that are also compiled to Java bytecode. • A Java virtual
machine’s main job is to load class files and execute the byte codes they contain. Java virtual machine
contains a class loader, which loads class files from both the program and the Java API. • Only those class
files from the Java API that are actually needed by a running program are loaded into the virtual machine.
The byte codes are executed in an execution engine
JAVA API • The Java API is set of runtime libraries that give us a standard way to access the system
resources of a host computer. • When we run a Java program, the virtual machine loads the Java API class
files that are referred to by the program’s class files.
Compiling the Program:To compile the HelloWorld program, execute the compiler, javac specifying the
name of the source file on the command line. This is shown below: $ javac HelloJavaWorld.java Javac
compiler creates a file named 'HelloJavaWorld.class' which contains the byte code version of the program.
It is an intermediate representation of the program
ADAPTERS • Adapter pattern is frequently used in modern Java frameworks. It comes into place when we
want to use an existing class, and its interface does not match the one we need, or we want to create a
reusable class that cooperates with unrelated classes with incompatible interfaces. • Adapter pattern works
as a bridge between two incompatible interfaces. This type of design pattern comes under structural
pattern as this pattern combines the capability of two independent interfaces.
ANONYMOUS INNER CLASSES • Anonymous classes of Java are called anonymous because they have no
name. • A class that have no name is known as anonymous inner class in Java. An anonymous class is a
local class without a name. • An anonymous class is defined and instantiated in a single succinct expression
using the new operator.
AppletViewer, Javadoc, JDB, javap, JAR, data type, Primitive Data Types, Tokens Java Identifiers,
AppletViewer An Applet is a Java program that runs in a Web browser. Java AppletViewer is the utility
which runs Applets outside the web browser. • AppletViewer is a standard JDK tool which has following
facilities: 1. To create dynamic applet, and 2. To view java applet. • A Java applet is a Java program designed
to be included in a HyperText Markup Language (HTML) document and run inside a web browser.
jdb • The Java debugger (jdb) is a tool for Java classes to debug a program in command line. jdb helps us to
find and fix bugs in Java language programs. • Debugging is a technical procedure to find and remove bugs
or defects in a program and get expected results. • A debugger allows us to step through every aspect of a
code, inspect all the elements, and remove errors, if any. • jdb helps in detecting and fixing bugs in a Java
program using Java Debug Interface (JDI)
javadoc • The javadoc tool is a document generator tool in Java for generating standard documentation in
HTML format. • javadoc is a tool which comes with JDK and it is used for generating Java code
documentation in HTML format from Java source code, which requires documentation in a predefined
format. • The javadoc is a documentation generator created by Sun Microsystems for the Java language
generating API documentation in HTML format from Java source code
javap • The javap tool of Java is used to get the information of any class. In Java the javap command
disassembles a class file. • The javap command (also known as the Java Disassembler) disassembles one or
more class files. • The javap tool disassemblies compiled Java files and prints out a representation of the
Java program. This may be helpful when the original source code is no longer available on a system.
JAR jar stands for Java archive. The jar tool is a java application that combines multiple files into a single JAR
archive file. • jar is a general-purpose archiving and compression tool based on ZIP and the ZLIB
compression format. • However, jar was designed mainly to facilitate the packaging of java applets or
applications into a single archive. Syntax: jar option destinationfile_list
Data Types Data types specify the different values that can be stored in the variable. Variables are nothing
but reserved memory locations to store values. • The type of value that a variable can hold is called as data
type. The main purpose of data types in Java is to determine what kind of value we can store into the
variable. • The data type of a variable determines the value which a variable can contain and the
operations that can be performed on it. Every variable must have a data type.
Primitive Data Types • Primitive data types also known as built-in data types, are the fundamental data
types provided by a programming language. • In Java language primitive data types include integer, floating
point, character and Boolean. byte: The byte data type is an 8-bit signed two’s complement integer. It has a
maximum value of −128 and a maximum value of 127 (inclusive). float: The float data type is a single-
precision 32-byte IEEE 754 Floating point. double: The float data type is a double-precision 64-byte IEEE
754 Floating point boolean: The Boolean data type has only two possible values namely, True and False.
Use this data type for simple flags that track true/false conditions. viii) char: The char data type is single
16-bit Unicode character. It has a maximum value of ‘\u0000’(or 0) and a maximum value of ‘\uffff’(or
65,535 inclusive).
Tokens Java Identifiers: • Identifiers are used for naming classes, methods, variables, objects, labels,
packages and interfaces in a program. • In Java, there are several rules for identifiers. They are as follows: 1.
All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_). 2.
After the first character, identifiers can have any combination of characters. 3. A keyword cannot be used as
an identifier. 4. Identifiers are case sensitive so Amar and amar has different meaning
Variable Declaration, Final Variable, Final Variable, ACCEPTING INPUT, Defining Classes, array object,
CONSTRUCTORS, uses of key word, STATIC BLOCK, STATIC FIELDS AND METHODS, statics method
Variable Declaration: • In Java, all the variables must be declared before use. A variable declaration, in its
simplest form, includes the name and the data type of variables. • Declaration does following three things:
1. It tells variable name to the compiler. 2. It specifies the data type of the data hold by variable. 3. The
place of declaration in the program decided the scope of the variable.
Final Variable • Variables are useful when we need to store information that can be changed as program
runs. • However, there may be certain situations in the program in which the value of variable should not
be allowed to modify or change. This is accomplished using a special type of variable known as final
variable. • The final variable also called constant variable. Final variable is a variable with a value that
cannot be modified during the execution of the program
Final Variable • Variables are useful when we need to store information that can be changed as program
runs. • However, there may be certain situations in the program in which the value of variable should not
be allowed to modify or change. This is accomplished using a special type of variable known as final
variable. • The final variable also called constant variable. Final variable is a variable with a value that
cannot be modified during the execution of the program
ACCEPTING INPUT Java provides different ways to get or accept input from the user. In Java, there are
different ways for reading input from the user in the command line environment (console). • The three
common techniques for accepting input in Java are using BufferedReader class, Scanner class and
Command line arguments
Defining Classes: • A class is the basic building block of Java language. A class is a template (or blueprint)
that describes the state and behavior associated with instances (objects) of that class
ARRAY OF OBJECTS • In java, rather than creating object of a particular or class, we can also create array of
objects. • In Java, an array of objects can also be created to store and process the objects. The process to
declare and create an array of objects is similar to the process of declaring and creating an array of simple
data types
CONSTRUCTORS • A constructor is a special method of a class in Java programming that initializes an object
of that type. • Constructors have the same name as the class itself. A constructor is automatically called
when an object is created
USE OF 'this' KEYWORD • Many times it is necessary to refer to its own object in a method or a constructor.
To allow this Java defines the ‘this’ keyword. • As we know in C++, sometimes a method will need to refer
to the object that invoked it. To do so, Java also has a 'this' keyword. • The 'this' can be used inside any
method to refer to the current object. It means that 'this' is always a reference to the object on which the
method was invoked.
STATIC BLOCK, STATIC FIELDS AND METHODS • In Java basically, class contains variables called instance
variables and methods called instance method. • When we create an object the memory gets allocated for
the variables and methods also. If we create one more object, same thing happens again.
Static Methods • It is possible to have static methods in a class in the same way as we have static fields. If
you apply static keyword with any method, it is known as static method. • A static method belongs to the
class rather than object of a class. A static method can be invoked without the need for creating an instance
of a class.
Object Class , String class, StringBuffer Class , Difference between String and StringBuffer, WRAPPER
CLASSES, PACKAGES, Creating Packages, Accessing Packages, User Defined Packages
Object Class • The object class is the parent class of all the classes in Java by default. In other words, it is
the topmost class of java. • The java.lang.Object class is the root of the class hierarchy. Every class has
Object as a superclass. All objects, including arrays, implement the methods of this class. • Following is the
declaration for java.lang.Object class: public class Object
String class • The strings in Java are treated as objects of type 'String' class. This class is present in the
package java.lang. • This package contains two string classes: 1. String class, and 2. StringBuffer class. • The
string class is used when we work with the string which cannot change whereas StringBuffer class is used
when we want to manipulate the contents of the string.
StringBuffer Class • It is a peer class which provides the functionality of strings. The string generally
represents fixed length, immutable character sequence whereas StringBuffer represents growable and
writeable character sequences. StringBuffer may have some characters and if needed substring can be
inserted in the middle or appended at the end. StringBuffer automatically provides a room to grow such
additions
Difference between String and StringBuffer • String objects are constants and immutable whereas
StringBuffer objects are not. • StringBuffer Class supports growable and modifiable string whereas String
class supports constant strings. • Strings once created we cannot modify them. Any such attempt will lead
to the creation of new strings. Whereas StingBuffer objects after creation also can be able to delete or
append any characteres to it. • String values are resolved at run time whereas StringBuffer values are
resolved at compile time.
WRAPPER CLASSES] • The primitive data types are not objects; they do not belong to any class; they are
defined in the language itself. Sometimes, it is required to convert data types into objects in Java language.
A data type is to be converted into an object and then added to a Stack or Vector etc. For this conversion,
the designers introduced wrapper classes.
PACKAGES• Java is an object oriented programming language. Any Java programmer will quickly build a
large number of different classes for use in each application that they develop. • Initially it may be tempting
to store the classes in the same directory as the end application, but as the complexity of applications
grows so will the number of classes. The answer is to organize the classes into packages.
Creating Packages • To create a package is quite easy, simply include a package command as the first
statement in a Java source file. • Following is the general form/syntax of the package statement: package
pkg_name; Here, pkg_name is the name of the package. For example, the following statement creates a
package called MyPackage.
Accessing Packages (Import a Package) • There are three ways to access the package from outside the
package i.e., import package.*; import package.classname; fully qualified name. 1. Using packagename: • If
we 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
User Defined Packages • The packages credited by user are called as user defined package. • User defined
packages generally represent programs data. Creating Own Packages: • We should first declare our own
package. This has to be first statement in Java source file. We can have comments and spaces at the top.
And then define the class in the same program.
Types of Inheritance Single Inheritance , Superclass and Subclass, Use of 'super' Keyword, METHOD
OVERRIDING AND RUNTIME POLYMORPHISM, USAGE OF 'final' KEYWORD, INTERFACE ,
Types of Inheritance Single Inheritance: Hierarchical inheritance • When a class extends another one class
only then we call it a single inheritance. • In case of single inheritance there is only a sub class and it's
parent class. It is also called simple inheritance or one level inheritance. Multilevel Inheritance We can
create any layers in the inheritance as we want, this is called Multilevel Inheritance. This hierarchy can be
created at any level of inheritance
Superclass and Subclass • Object-oriented programming allows classes to inherit commonly used state and
behavior from other classes. • The idea of inheritance is simple but powerful i.e., when we want to create a
new class and there is already a class that includes some of the code that we want, we can derive our new
class from the existing class
Use of 'super' Keyword • A subclass inherits the accessible data fields and methods from its superclass, but
the constructors of the superclass are not inherited in the subclass. • They can only be invoked from
constructors of the subclass(es) using the keyword 'super'. • The 'super' keyword is used by subclass to
refer its immediate superclass. There are two different forms of using super: 1. 'super' calls the superclass
constructor.
METHOD OVERRIDING AND RUNTIME POLYMORPHISM • If the same method is defined in both the
superclass and the subclass, then the method of the subclass class overrides the method of the superclass.
This is known as method overriding. • Runtime polymorphism is a process in which a call to an overridden
method is resolved at runtime rather than compile-time. Method overriding is one of the ways in which
Java supports Runtime Polymorphism ‘
USAGE OF 'final' KEYWORD • The "final" is a keyword in Java which generally means, cannot be changed
once created. • The "final" keyword when declared with variables, methods and classes specifically means:
1. The final variables cannot be modified. 2. The final method cannot be overridden. 3. The final class
cannot be inherited or extended
class Subclass
Object of class can be created. Object of abstract class cannot be created.
It contains non abstract methods (methods with It can have abstract and non abstract methods
their definitions). Extension of abstract class is compulsory.
Extension of class is not mandatory.
INTERFACE • An interface in Java is a blueprint of a class. It has static constants and abstract methods only.
• An interface is a way of describing what classes should do, without specifying how they should do it. •
There are mainly following reasons to use interface: 1. It is used to achieve fully abstraction. 2. By interface,
we can support the functionality of multiple inheritance.
Class interface
It can contain abstract methods along with method It can contain only declarations definitions and
definition not method method
Classes are extended by another class. Interfaces are implemented by classes.
Methods of objects can be called using the object Methods of interfaces should be defined in the
of the class class which implements the interface.
t he variables of the class can be final/not final. The variables of the interfaces are by default final.
Nested Interfaces • An interface declared within another interface or class is known as Nested Interface. •
The nested interfaces are used to group related interfaces so that they can be easy to maintain. The nested
interface must be referred by the outer interface or class. It cannot be accessed directly.
Types of Exceptions , Unchecked Exceptions, Exception Handling , throws and throw Keywords,
CREATING USER DEFINED EXCEPTIONS, INTRODUCTION TO FILES AND STREAMS,
Types of Exceptions StringIndexOutOf BoundsException StringIndexOutOf BoundsException • The
categories of Exceptions are explained below: 1. Checked Exceptions: [Oct. 18] • A checked exception is an
exception that is checked (notified) by the compiler at compilation-time, these are also called as compile
time exceptions. • These exceptions cannot simply be ignored, the programmer should take care of
(handle) these exceptions
Unchecked Exceptions An unchecked exception is an exception that occurs at the time of execution. These
are also called as Runtime Exceptions. • These include programming bugs, such as logic errors or improper
use of an API. Runtime exceptions are ignored at the time of compilation
Exception Handling • A Java exception is an object that describes an exceptional (that is, error) condition
that has occurred in a program code. • When an exceptional condition arises, an object representing that
exception is created and thrown in the method that caused the error. That method may choose to handle
the exception itself, or pass it on.
throws and throw Keywords • If a method does not handle a checked exception, the method must declare
it using the throws keyword. • We can throw an exception, either a newly instantiated one or an exception
that we just caught, by using the throw keyword.
Throw throws
Java, throw keyword is used to explicitly throw an Java, throws keyword is used to declare an
exception exception.
Checked exception cannot be propagated using Checked exception can be propagated with throws.
throw only. Throws is followed by class.
Throw is followed by an instance
CREATING USER DEFINED EXCEPTIONS • Though Java provides an extensive set of in-built exceptions, there
are cases in which we may need to define our own exceptions in order to handle the various application
specific errors that we might encounter. • If a user is creating his/her own Exception is known as user
defined exception (or custom exception). Java user defined exceptions are used to customize the exception
according to user need
INTRODUCTION TO FILES AND STREAMS • A file is a named location that can be used to store related
information. The File class from the java.io package (java.io.File), allows us to work with files. • The java.io
package provides an extensive library of classes for dealing with Input and Output (I/O). • Java provides
streams as a general mechanism for dealing with data I/O. Java uses the concept of a stream to make I/O
operation fast. The java.io package contains all the classes required for input and output operations.
2 Streams • All the input and output operation of file uses streams. A stream is an abstraction of I/O
devices. o A stream is a sequence of data. Stream represents flow of data. o Stream is a logical entity that
will be tied up with a data source or destination. • The stream presents an object oriented and uniform
interface between the program and the input/output devices. • Every Java program has a source and
destination. Source is in the form of keyboard, mouse, memory, disk, etc. Destination is screen, printer,
memory, disk etc. There is an input and output streams
Awt , swing , LAYOUTS AND LAYOUT MANAGERS, menu, LAYOUTS AND LAYOUT MANAGERS,
To delete a file in Java, use the delete() method
import java.io.File; // Import the File class
public class DeleteFile {
public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.delete()) {
System.out.println("Deleted the file: " + myObj.getName());
} else {
System.out.println("Failed to delete the file.");
} } }
Reader Inputstream
Reads into a char array. Reads in a single byte
Subclass must implements the abstract close Close() is usually overridden.
method. It has available method which tells us how much
It has a ready method which tells us if there is any data is available to read.
data
FileReader • FileReader class is used to read data from the file. It translates bytes from a file into a
character stream. • Constructors are: 1. FileReader(String path) 2. FileReader(File obj)
What is AWT? • The Java programming language class library provides a user interface toolkit called the
Abstract Window Toolkit, or the AWT. Java AWT is an API to develop GUI or window-based application in
Java. • Java AWT components are platform-dependent i.e. components are displayed according to the view
of operating system. AWT is heavy weight i.e. its components uses the resources of system.
What is Swing? • Swing is a GUI widget toolkit for Java. It is part of Oracle's Java Foundation Classes (JFC) -
an API for providing a Graphical User Interface (GUI) for Java programs. • Swing was developed to provide a
more sophisticated set of GUI components than the earlier Abstract Window Toolkit (AWT)
awt Swing
AWT components are platform dependent. Java swing components are platform independent.
AWT components are heavy weight. Swing components are light weight.
AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.
AWT provides less components than Swing. Swing provides more powerful com ponents such
AWT components require java.awt package as tables, lists, scrollpanes, colorchooser,
tabbedpane etc.
Swing components require javax.swing package.
Menu • Menu components in Swing are subclasses of JComponent so they have all functionality of a
normal Swing component.
LAYOUTS AND LAYOUT MANAGERS• Layout means the arrangement of components within the container.
In other way we can say that placing the components at a particular position within the container. • The
task of layouting the controls are done automatically by the Layout Manager
FlowLayout Manager , AWT HIERARCHY / AWT CONTROLS , Check Box , Menus, TextField, ScrollBars,
Lists, SWING (CONTAINERS AND COMPONENTS , Swing Components, DIALOGS,
FlowLayout Manager • The FlowLayout is one the most popular and simplest layout manager. FlowLayout
manager places components in a container from left to right in the order in which they were added to the
container. • When one row is filled, layout advances to the next row. It is analogous to lines of text in a
paragraph.
AWT HIERARCHY / AWT CONTROLS • Window is a rectangular area which is displayed on the screen. In
different window we can execute different program and display different data. • Window provides us with
multitasking environment. A window must have a frame, dialog or another window defined as its owner
when it's constructed. • Different windows classes are defined by AWT which adds functionality
Check Box: • A check box is a control that is used to turn an option on (true) or off (false). It consists of a
small box that can either contain a check mark or not. • Check boxes can be used individually or as part of a
group. Check boxes are objects of the Checkbox class. • Checkbox class supports following constructors: (i)
Checkbox(): Creates checkbox without label. Initial state is unchecked. (ii) Checkbox(String): Creates a
checkbox with label specified Initial state is unchecked
Menus• A top-level window can have a menu bar associated with it. A menu bar displays a list of top-level
menu choices. Each choice is associated with a drop down menu.
TextField: • The TextField class implements a single-line text-entry area, usually called an edit control. •
Text fields allow the user to enter strings and to edit the text using the arrow keys, cut and paste keys, and
mouse selections. • It defines following constructors: (i) Textfield(): Creates a default textfield. (ii)
Textfield(int): Creates a textfield with specified number of characters. (iii) TextField(String): Creates a
textfield with a specified string initially.
ScrollBars: • Scrollbar control represents a scroll bar component in order to enable user to select from
range of values. • Scroll bars may be oriented horizontally or vertically
Lists: • List class provides a list of items, which can be scrolled. From list of items, single or multiple items
can be selected. • It provides three constructors: (i) List() : Creates a list box in which single selection is
possible. (ii) List(int) : Creates a list-box, specified number of items will always be visible selection. Selection
is possible. (iii) List(int, boolean) : Creates a list box, first parameter specifies number of items to be visible.
Second parameter specifies whether multiple selection of item is allowed. True indicates multiple selection.
SWING (CONTAINERS AND COMPONENTS ) • The swing components are defined in the package
javax.swing. This package provides more powerful and flexible components. • Swing is a Java foundation
classes, library and it is an extension to do Abstract Window Toolkit (AWT). • Swing is an extension to the
AWT components which provides feature of pluggable look and feel for the components. It provides classes
to design lightweight components.
Swing Components • Swing components are not implemented by platform specific code. Instead they are
written entirely in Java and therefore, are platform independent. • Swing component is called light weight,
as it does not depend on any non-java system classes. Swing components have their own view supported
by java's look and feel classes.
DIALOGS • Dialog windows or dialogs are an indispensable part of most modern GUI applications. • A
dialog is defined as a conversation between two or more persons. In a computer application a dialog is a
window which is used to "talk" to the application.