Java Notes-1
Java Notes-1
UNIT 1
Introduction to OOPS: paradigm of programming language –Basic concepts of object oriented programming
language-difference between procedure oriented programming and object oriented programming –benefits if
OOPS-Application of OOPS. Java: History- Java features – Java Environment-JDK-API. Introduction to java:
types of java program-creating and executing a java program-java Tokens-java virtual machine (JVM)-
command line arguments-comments in java program.
Introduction to JAVA:
Java is a general purpose object-oriented programming language developed by sun Microsystems of
USA in 1991. It was originally called oak. James Gosling, one of the inventors of the language. It was
designed for the development of software for consumer electronic devices like TVs, VCRs.
Features of Java:
Java supports the following features. These features made java the first application language of World
Wide Web. The features are:
1. Compiled and Interpreted language
2. Platform-Independent and Portable
3. Object – Oriented
4. Robust and Secure
5. Distributed
6. Familiar, Simple and Small
7. Multithreaded and Interactive
8. High performance
9. Dynamic and Extensible
Compiled and Interpreted:
Usually a computer language is either compiled or interpreted. Java combines both these approaches
thus making java a two-stage system. Java compiler translates source code into byte codes. Byte codes are not
machine code, so in the second stage, java interpreter generates machine code that can be directly executed by
any machine.
Platform independent and Portable:
Java programs can be easily moved from one computer system to another, anywhere and anytime.
Changes and upgrades in operating systems, processors and system resources will not force any changes in java
program.
Java ensures portability in two ways. First, java compiler generates byte code instruction that can be
implemented on any machine.
Object Oriented:
Java is a true object oriented language. All program codes and data reside within objects and class.
Java comes with an extensive set of classes, arranged in package.
Robust and Secure:
Java is a robust language. It provides many safeguards to ensure reliable code. It has strict compile
time and run time checking for data types. It is designed as a garbage-collected language relieving the
programmer’s memory management problems.
Security becomes an important issue for a language that is used for programming on Internet. Java
systems not only verify all memory access but also ensure that no viruses are communicated with an applet.
The absence of pointers ensures that programs cannot access memory location without proper authorization.
Distributed:
Prof: Padmini. R Dept: BCA Programming in JAVA
Java is designed as a distributed language for creating applications on networks. It has the ability to
share both data and programs. Java application can easily open and access remote objects as then can do in a
local system.
Simple, small and familiar:
Java is a small and simple language: Many feature of C and C++ that are either redundant or sources of
unreliable code are not part of Java. Java does not use pointers, preprocessor header files, goto statement.
Familiar is another striking feature of java. Java uses many constructs of C and C++ and therefore, java
code “look like a C++” code. In fact java is a simplified version of C++.
Multithreaded and Interactive:
Multithreaded means handling multiple tasks simultaneously. This means we need not wait for the
completion of one application before the beginning of another application. Java supports multiple process
synchronization and running interactive systems.
High Performance:
Java performance is impressive for an interpreted language, mainly due to the use of intermediate byte
code. Java speed is comparable to the native C/C++.
Dynamic and Extensible:
Java is a dynamic language. Java is capable of dynamically linking in new class libraries, methods and
objects. Java programs support functions written in other languages such as C and C++. These functions are
known as native methods. Native methods are linked dynamically at runtime.
How JAVA differs from C:
• Java does not include the C unique keywords sizeof and typedef.
• Java does not contain the data type struct and union.
• Java does not define the type modifier keywords auto, extern, register, signed and unsigned.
• Java does not support pointer.
• Java required that the functions with no argument must be declared with empty parenthesis and not with
the void keyword.
• Java adds new operators such as instanceof and >>>
• Java adds labeled break and continue statements.
How JAVA differs from C++:
• Java does not support operator overloading
• Java does not have template classes.
• Java does not support multiple inheritance of classes.
• Java does not support global variables
• Java does not use pointer
• Java has replaced the destructor function with finalize().
• There are no header files.
Basic concepts of object-oriented programming:
Object-Oriented Programming (OOP) is an approach to program organization and development, which
attempt to eliminate some of the pitfalls (drawbacks) of conventional programming methods.
An object oriented language should support the following features.
Classes and Objects:
Class is used to create a new user defined data type. It is a user defined data type and behaves like the
built-in type of a programming language. In other words class is a collection of objects.
Prof: Padmini. R Dept: BCA Programming in JAVA
Once class has been created we can create variables of that type using the class name. These variables
are called objects. Objects are the basic runtime entity in an object oriented system. They may represent a
person, a place, a bank account or any item that the program may handle.
Data abstraction and encapsulation:
The wrapping (covering, binding or enclosing) up of data and methods into a single unit is known as
encapsulation. Data encapsulation is the most striking (outstanding) feature of a class. The data is not
accessible to the outside world and only those methods, which are wrapped in the class, can access it. This
insulation of the data is called data hiding.
Abstraction refers to the act of representing essential features without including the background details
or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes such as
size, weight and cost, and the methods operate on these attributes.
Inheritance:
Inheritance is the process of object of one class uses the properties of another class. This feature
increases the reusability of existing code. Once a method is declared and defined in a class, we don’t want to
declare and define the same method name for the same purpose. Just we can extend this class to another.
Polymorphism:
Polymorphism is another important OOP concept. Polymorphism means ability to take more than one
form.
Dynamic binding:
Binding refers to the linking of a procedure call to the procedure definition. Dynamic binding means
that the code associated with the procedure call does not known until the time of function call. It is only known
at run time.
Message passing:
An object-oriented program consists of a set of objects that communicate with each other. Therefore
the object-oriented programming language involves the following steps.
1. Creating classes
2. Creating the objects from the class definition
3. Establishing communication among objects.
Message passing involves specifying the name of the object, the name of the method and the information to
be sent. For example, consider the statement
Employee.salary(name)
Here Employee is an object, salary is a method and name is the information to be sent.
Java tokens:
Smallest individual units in a program are known as tokens. The compiler recognizes them for building
expression and statements. Java includes five types of tokens. They are:
Reserved words (Keywords)
Identifiers
Literals
Operators
Separators
Reserved words:
Prof: Padmini. R Dept: BCA Programming in JAVA
Reserved word or keywords are pre-defined words. Each keyword has the specific meaning, so we
can’t use them as an identifier (variable name, class name, function name, etc.,). Java has 50 keywords. All
keywords are to be written in lower-case letters.
Ex: break, float, for, double.
Identifiers:
Identifiers are user defined tokens. These tokens are used to naming classes, methods, variables,
objects, labels, packages and interfaces in a program. Java identifiers should follow the following rules:
1. They can have alphabet, digits, underscore and dollar sign characters.
2. They must not begin with a digit.
3. Uppercase and lowercase letter are distinct.
4. They can be any length.
Ex: average, sum, complex, roll_no
Literals:
Literals are sequence of characters (alphabets, digits and other characters) that represents the constant
value to be stored in the variables. Java includes five major types of literals. They are:
Integer literals
Floating-point literals
Character literals
String literals
Boolean literals
Integer literals:
Integer literals refer to the sequence of digits. It may be positive or negative, but it should be whole
number.
Ex: 123, -234, 0.
An octal integer constant consists of any combination of digits from 0 -7, with leading zero.
Ex: 037, 0, 0987
A sequence of digits preceded by 0x or 0X is considered as hexadecimal integer (hex integer). They
may also include alphabets from A to F.
Ex: 0X2, 0X9F, 0xabc.
Floating point literals (Real literals):
If a number has fractional part that number is called real number. It may be positive or negative but
should have fractional value.
Ex: 0.0, 23.789, -67.098.
A floating point constant includes four parts:
1. A whole number
2. A decimal point
3. A factional part
4. An exponent
Character literals:
A single character constant includes digits, alphabet or special character. But it should be enclosed
within a pair of single quotes.
Ex: ‘5’, ‘X’, ‘/’, ‘$’.
String Literals:
Prof: Padmini. R Dept: BCA Programming in JAVA
A string is a sequence of characters enclosed within pair of double quotes (“”). The characters in the
string may be alphabet, digits, blank spaces and special characters.
Ex: “hello”, “4567”, “@#$%”.
Boolean literals:
Boolean literals are Boolean values True or false.
Ex: boolean r;
r=true;
Operators:
An operator is a symbol that indicates which operation should perform on the operand. Operator may
be unary or binary operator.
Separators:
Separators are symbols used to indicate where the group of code are divided and arranged.
Name Use of the symbol
Parentheses
Used to enclose parameters in the functions definition, surrounding cast type (int).
()
Braces {} Used to define the block and array initialization.
Bracket [] Used in declaration of array and dereferencing array values in each location
Semicolon ; Used to separate statements
Comma , Used to separate consecutive identifiers in variable declaration.
Used to separate package name from the sub-package name and calling member variables and
Period .
functions of a class using objects.
Java statements:
A statement is an executable combination of tokens ending with semicolon (;). Statements are usually
executed in sequence order. However it is possible to control the flow of execution, if necessary using special
statement (branching, looping and jumping).
Empty statements: These statements do nothing and used as place holders
Labeled Statements: Any statement begins with label. Labels must not be a keyword, already declared local
variable or previously used label.
Expression: Most of the statements in java program are expression statements. Expression statements are:
assignment, pre-increment and method calling.
Selection statements: These statements select one of several control flow. It includes if, if-else, else-if, and
switch statements.
Iteration statements: These statements are used to execute set of line for n number of times. It includes for,
while and do-while statements.
Jump statements: Jump statements pass the control to the beginning or end of the current block.
Synchronization statements: These statements handling problem with multi thread programs.
Guarding statements: Guarding statements are used for safe handling of code. These statements use the
keywords try, catch and finally.
Prof: Padmini. R Dept: BCA Programming in JAVA
Some paradigms are concerned mainly with implications for the execution model of the language, such as
allowing side effects, or whether the sequence of operations is defined by the execution model. Other
paradigms are concerned mainly with the way that code is organized, such as grouping a code into units along
with the state that is modified by the code. Yet others are concerned mainly with the style of syntax and
grammar.
Common programming paradigms include:
imperative in which the programmer instructs the machine how to change its state,
o procedural which groups instructions into procedures,
o object-oriented which groups instructions with the part of the state they operate on,
declarative in which the programmer merely declares properties of the desired result, but not how to
compute it
o functional in which the desired result is declared as the value of a series of function applications,
o logic in which the desired result is declared as the answer to a question about a system of facts
and rules,
o mathematical in which the desired result is declared as the solution of an optimization problem
o reactive in which the desired result is declared with data streams and the propagation of change
Symbolic techniques such as reflection, which allow the program to refer to itself, might also be considered as
a programming paradigm. However, this is compatible with the major paradigms and thus is not a real
paradigm in its own right.
Procedural languages
The next advance was the development of procedural languages. These third-generation languages (the first
described as high-level languages) use vocabulary related to the problem being solved. For example,
COmmon Business Oriented Language (COBOL) – uses terms like file, move and copy.
FORmula TRANslation (FORTRAN) – using mathematical language terminology, it was developed
mainly for scientific and engineering problems.
ALGOrithmic Language (ALGOL) – focused on being an appropriate language to define algorithms,
while using mathematical language terminology, targeting scientific and engineering problems, just like
FORTRAN.
Programming Language One (PL/I) – a hybrid commercial-scientific general purpose language
supporting pointers.
Beginners All purpose Symbolic Instruction Code (BASIC) – it was developed to enable more people to
write programs.
C – a general-purpose programming language, initially developed by Dennis Ritchie between 1969 and
1973 at AT&T Bell Labs.
All these languages follow the procedural paradigm. That is, they describe, step by step, exactly the procedure
that should, according to the particular programmer at least, be followed to solve a specific problem.
The efficacy and efficiency of any such solution are both therefore entirely subjective and highly dependent on
that programmer's experience, inventiveness, and ability.
Object-oriented programming
Prof: Padmini. R Dept: BCA Programming in JAVA
Following the widespread use of procedural languages, object-oriented programming (OOP) languages
were created, such as Simula, Smalltalk, C++, Eiffel, Python, PHP, Java, and C#.
In these languages, data and methods to manipulate it are kept as one unit called an object.
With perfect encapsulation, one of the distinguishing features of OOP, the only way that another object
or user would be able to access the data is via the object's methods.
Thus, an object's inner workings may be changed without affecting any code that uses the object. There
is still some controversy raised by Alexander Stepanov, Richard Stallman[10] and other programmers,
concerning the efficacy of the OOP paradigm versus the procedural paradigm.
The need for every object to have associative methods leads some skeptics to associate OOP
with software bloat; an attempt to resolve this dilemma came through polymorphism.
Because object-oriented programming is considered a paradigm, not a language, it is possible to create
even an object-oriented assembler language.
High Level Assembly (HLA) is an example of this that fully supports advanced data types and object-
oriented assembly language programming – despite its early origins.
Thus, differing programming paradigms can be seen rather like motivational memes of their advocates,
rather than necessarily representing progress from one level to the next.
Precise comparisons of competing paradigms' efficacy are frequently made more difficult because of
new and differing terminology applied to similar entities and processes together with numerous
implementation distinctions across languages.
Different between procedural oriented programming and object oriented programing:
Prof: Padmini. R Dept: BCA Programming in JAVA
Benefits of oops:
We can build the programs from standard working modules that communicate with one another,
rather than having to start writing the code from scratch which leads to saving of development time and
higher productivity,
OOP language allows to break the program into the bit-sized problems that can be solved easily (one
object at a time).
The new technology promises greater programmer productivity, better quality of software and lesser
maintenance cost.
OOP systems can be easily upgraded from small to large systems.
It is possible that multiple instances of objects co-exist without any interference,
It is very easy to partition the work in a project based on objects.
It is possible to map the objects in problem domain to those in the program.
The principle of data hiding helps the programmer to build secure programs which cannot be invaded
by the code in other parts of the program.
By using inheritance, we can eliminate redundant code and extend the use of existing classes.
Message passing techniques is used for communication between objects which makes the interface
descriptions with external systems much simpler.
The data-centered design approach enables us to capture more details of model in an implementable
form.
While it is possible to incorporate all these features in an OOP, their importance depends upon the type of
project and preference of the programmer. These technology is still developing and current products may be
superseded quickly.
Developing a software is easy to use makes it hard to build.
Applications of oops
The Java Runtime Environment, or JRE, is a software layer that runs on top of a computer’s operating system
software and provides the class libraries and other resources that a specific Java program needs to run.
The JRE is one of three interrelated components for developing and running Java programs. The other two
components are as follows:
Prof: Padmini. R Dept: BCA Programming in JAVA
The Java Development Kit, or JDK, is a set of tools for developing Java applications. Developers
choose JDKs by Java version and by package or edition—Java Enterprise Edition (Java EE), Java
Special Edition (Java SE), or Java Mobile Edition (Java ME). Every JDK always includes a
compatible JRE, because running a Java program is part of the process of developing a Java program.
The Java Virtual Machine, or JVM, executes live Java applications. Every JRE includes a default
JRE, but developers are free to choose another that meets the specific resource needs of their
applications.
The JRE combines Java code created using the JDK with the necessary libraries required to run it on a JVM
and then creates an instance of the JVM that executes the resulting program. JVMs are available for multiple
operating systems, and programs created with the JRE will run on all of them. In this way, the Java Runtime
Environment is what enables a Java program to run in any operating system without modification.
JDK
The Java Development Kit (JDK) is one of three core technology packages used in Java programming, along
with the JVM (Java Virtual Machine) and the JRE (Java Runtime Environment). It's important to differentiate
between these three technologies, as well as understanding how they're connected:
JDK contents
The JDK has as its primary components a collection of programming tools, including:
appletviewer – this tool can be used to run and debug Java applets without a web browser
apt – the annotation-processing tool[6]
extcheck – a utility that detects JAR file conflicts
idlj – the IDL-to-Java compiler. This utility generates Java bindings from a given Java IDL file.
jabswitch – the Java Access Bridge. Exposes assistive technologies on Microsoft Windows systems.
java – the loader for Java applications. This tool is an interpreter and can interpret the class files
generated by the javac compiler. Now a single launcher is used for both development and deployment. The
old deployment launcher, jre, no longer comes with Sun JDK, and instead it has been replaced by this new
java loader.
javac – the Java compiler, which converts source code into Java bytecode
javadoc – the documentation generator, which automatically generates documentation from source
code comments
jar – the archiver, which packages related class libraries into a single JAR file. This tool also helps
manage JAR files.
javafxpackager – tool to package and sign JavaFX applications
Prof: Padmini. R Dept: BCA Programming in JAVA
A java program is not embedded within HTML or any other language and can Stand on its own. It is referred
to as Application program.
2. Applet Programs are small java programs developed for internet applications. Applets are embedded in
HTML documents.
Applet programs can be run using the applet viewer or web browser.
For example, when you use java to enhance a WWW page, the java code is embedded within HTML code. It
is called as Applet.
How to Compile and Run Java Program
In this section, we learn how to compile and run java program step by step.
Step 1:
Write a program on the notepad and save it with .java (for example, DemoFile.java) extension.
class DemoFile
{
public static void main(String args[])
{
System.out.println("Hello!");
System.out.println("Java");
}
}
Step 2:
Open Command Prompt.
Step 3:
Set the directory in which the .java file is saved. In our case, the .java file is saved in C:\\demo.
Step 4:
Use the following command to compile the Java program. It generates a .class file in the same folder. It also
shows an error if any.
1. javac DemoFile.java
Prof: Padmini. R Dept: BCA Programming in JAVA
Step 5:
JVM:
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in
which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).
What is JVM
It is:
1. A specification where working of Java Virtual Machine is specified. But implementation provider is
independent to choose the algorithm. Its implementation has been provided by Oracle and other
companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run the java class, an
instance of JVM is created.
What it does
o Executes code
o Provides runtime environment
JVM Architecture
Now in this JVM tutorial, let's understand the Architecture of JVM. JVM architecture in Java contains
classloader, memory area, execution engine etc.
Java
Virtual Machine Architecture
1) ClassLoader
The class loader is a subsystem used for loading class files. It performs three major functions viz. Loading,
Linking, and Initialization.
2) Method Area
JVM Method Area stores class structures like metadata, the constant runtime pool, and the code for methods.
3) Heap
Prof: Padmini. R Dept: BCA Programming in JAVA
All the Objects, their related instance variables, and arrays are stored in the heap. This memory is common and
shared across multiple threads.
Java language Stacks store local variables, and it’s partial results. Each thread has its own JVM stack, created
simultaneously as the thread is created. A new frame is created whenever a method is invoked, and it is deleted
when method invocation process is complete.
5) PC Registers
PC register store the address of the Java virtual machine instruction which is currently executing. In Java, each
thread has its separate PC register.
Native method stacks hold the instruction of native code depends on the native library. It is written in another
language instead of Java.
7) Execution Engine
It is a type of software used to test hardware, software, or complete systems. The test execution engine never
carries any information about the tested product.
The Native Method Interface is a programming framework. It allows Java code which is running in a JVM to
call by libraries and native applications.
Native Libraries is a collection of the Native Libraries(C, C++) which are needed by the Execution Engine.
In order to write and execute a software program, you need the following
1) Editor – To type your program into, a notepad could be used for this
2) Compiler – To convert your high language program into native machine code
3) Linker – To combine different program files reference in your main program together.
4) Loader – To load the files from your secondary storage device like Hard Disk, Flash Drive, CD into RAM
for execution. The loading is automatically done when you execute your code.
Prof: Padmini. R Dept: BCA Programming in JAVA
5) Execution – Actual execution of the code which is handled by your OS & processor.
To understand the Java compiling process in Java. Let's first take a quick look to compiling and linking process
in C.
Suppose in the main, you have called two function f1 and f2. The main function is stored in file a1.c.
All these files, i.e., a1.c, a2.c, and a3.c, is fed to the compiler. Whose output is the corresponding object files
which are the machine code.
The next step is integrating all these object files into a single .exe file with the help of linker. The linker will
club all these files together and produces the .exe file.
During program run, a loader program will load a.exe into the RAM for the execution.
Prof: Padmini. R Dept: BCA Programming in JAVA
Now in this JVM tutorial, let's look at the process for JAVA. In your main, you have two methods f1 and f2.
The compiler will compile the three files and produces 3 corresponding .class file which consists of BYTE
code. Unlike C, no linking is done.
The Java VM or Java Virtual Machine resides on the RAM. During execution, using the class loader the class
files are brought on the RAM. The BYTE code is verified for any security breaches.
Next, the execution engine will convert the Bytecode into Native machine code. This is just in time compiling.
It is one of the main reason why Java is comparatively slow.
Prof: Padmini. R Dept: BCA Programming in JAVA
NOTE: JIT or Just-in-time compiler is the part of the Java Virtual Machine (JVM). It interprets part of the
Byte Code that has similar functionality at the same time.
The java command-line argument is an argument i.e. passed at the time of running the java program.
The arguments passed from the console can be received in the java program and it can be used as an input.
So, it provides a convenient way to check the behavior of the program for the different values. You can
pass N (1,2,3 and so on) numbers of arguments from the command prompt.
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
compile by > javac A.java
run by > java A sonoo jaiswal 1 3 abc
Output: sonoo
jaiswal
1
Java Comments
The Java comments are the statements in a program that are not executed by the compiler and interpreter.
The single-line comment is used to comment only one line of the code. It is the widely used and easiest way of
commenting the statements.
Single line comments starts with two forward slashes (//). Any text in front of // is not executed by Java.
4.2M
Syntax:
//This is single line comment
CommentExample1.java
public class CommentExample1 {
public static void main(String[] args) {
int i=10; // i is a variable with value 10
System.out.println(i); //printing the variable i
}
}
Output:
10
Prof: Padmini. R Dept: BCA Programming in JAVA
The multi-line comment is used to comment multiple lines of code. It can be used to explain a complex code
snippet or to comment multiple lines of code at a time (as it will be difficult to use single-line comments there).
Multi-line comments are placed between /* and */. Any text between /* and */ is not executed by Java.
Syntax:
/*
This
is
multi line
comment
*/
CommentExample2.java
public class CommentExample2 {
public static void main(String[] args) {
/* Let's declare and
print variable in java. */
int i=10;
System.out.println(i);
/* float j = 5.9;
float k = 4.4;
System.out.println( j + k ); */
}
}
Output:
10
Note: Usually // is used for short comments and /* */ is used for longer comments.
Documentation comments are usually used to write large programs for a project or software application as it
helps to create documentation API. These APIs are needed for reference, i.e., which classes, methods,
arguments, etc., are used in the code.
To create documentation API, we need to use the javadoc tool. The documentation comments are placed
between /** and */.
Syntax:
Prof: Padmini. R Dept: BCA Programming in JAVA
/**
*
*We can use various tags to depict the parameter
*or heading or author name
*We can also use HTML tags
*
*/
javadoc tags
@code {@code text} To show the text in code font without interpreting it as html
markup or nested javadoc tag.
@since @since release To add "Since" heading with since text to generated
documentation.
@param @param parameter-name To add a parameter with given name and description to
description 'Parameters' section.
@return @return description Required for every method that returns something (except
void)
Calculate.java
import java.io.*;
/**
* <h2> Calculation of numbers </h2>
* This program implements an application
* to perform operation such as addition of numbers
* and print the result
* <p>
Prof: Padmini. R Dept: BCA Programming in JAVA
Create Document
Now, the HTML files are created for the Calculate class in the current directory, i.e., abcDemo. Open the
HTML files, and we can see the explanation of Calculate class provided through the documentation comment.
Ans: As we know, Java comments are not executed by the compiler or interpreter, however, before the lexical
transformation of code in compiler, contents of the code are encoded into ASCII in order to make the
processing easy.
Test.java
public class Test{
public static void main(String[] args) {
//the below comment will be executed
// \u000d System.out.println("Java comment is executed!!");
}
}
Output:
The above code generate the output because the compiler parses the Unicode character \u000d as a new
line before the lexical transformation, and thus the code is transformed as shown below:
Test.java
public class Test{
Prof: Padmini. R Dept: BCA Programming in JAVA
Thus, the Unicode character shifts the print statement to next line and it is executed as a normal Java code.
Prof: Padmini. R Dept: BCA Programming in JAVA
UNIT 2
Elements: Constants-variables-Data types-scopes of variables- Types casting-operators-special operators-
Expression- Evaluation of Expression. Decision Making and branching statements – Decision making and
looping – break – labeled loop – continue statement. Arrays –one dimensional array-creating an array-array
processing-multi-dimensional array-vectors-Array list –Advantages of array list over array wrapper classes
Constants
Constants refers to fixed values, that do not change during the execution.
Integer Constants
Integer Constants refers to a Sequence of digits which Includes only negative or positive Values and many
other things those are as follows:-
1. An Integer Constant must have at Least one Digit.
2. it must not have a Decimal value.
3. it could be either positive or Negative.
4. if no sign is Specified then it should be treated as Positive.
5. No Spaces and Commas are allowed in Name.
Real Constants
1. A Real Constant must have at Least one Digit.
2. it must have a Decimal value.
3. it could be either positive or Negative.
4. if no sign is Specified then it should be treated as Positive.
5. No Spaces and Commas are allowed in Name.
6. Like 251, 234.890 etc are Real Constants.
Prof: Padmini. R Dept: BCA Programming in JAVA
In The Exponential Form of Representation the Real Constant is Represented in the two Parts The part
before appearing e is called mantissa whereas the part following e is called Exponent.
7. In Real Constant The Mantissa and Exponent Part should be Separated by letter e.
8. The Mantissa Part have may have either positive or Negative Sign.
9. Default Sign is Positive.
Single Character Constants
A Character is Single Alphabet a single digit or a Single Symbol that is enclosed within Single inverted
commas.
Like 'S' ,'1' etc are Single Character Constants.
String Constants
String is a Sequence of Characters Enclosed between double Quotes These Characters may be digits ,Alphabets
Like "Hello" , "1234" etc.
Type Conversion
Type Conversion is that which converts the one data type into another for example converting a into float
converting a float into double
The Type Conversion is that which automatically converts the one data type into another but remember we can
store a large data type into the other for ex we can store a float into int because a float is greater than int Type
Conversion is Also Called as Promotion of data Because we are Converting one Lower data type into higher
data type So this is Performed Automatically by java compilers
Type casting:
Sometimes we need to store a value of one type into a variable of another type. In such cases, we must
cast the value from one type to target type. It can be done as follows.
Type variable= (type) variable2;
Automatic conversion:
Automatic type conversion is possible only if the destination type has enough privilege to store the
source value. For example, int is large enough to hold a byte value. Therefore,
byte b=75;
int a=b;
Explicit conversion:
Sometimes we need to explicitly convert the data from one type to another type. For example if you
want to assign an int value to a byte value. This conversion can’t be performed automatically, because byte is
smaller than an int. This type of conversions sometimes called a narrowing conversion.
Prof: Padmini. R Dept: BCA Programming in JAVA
To create a conversion between two incompatible type, you must use a cast. The general format as
follows.
(target_type) value;
Ex: int a=150;
byte b;
b=(byte) a;
Data types:
Every variable in java has a data type. Data types specify the size and type of values that can be stored
in a variable.
Integer types:
Integer type can hold whole numbers such as 123, -96 and 5639. The size of the values that can be
stored depends on the integer data type we choose. Java supports four types of integer. They are byte, short,
int and long.
Type Size
Read statement:
We can also give values to variable s interactively through the keyboard using the readLine( ) method.
Java supports two output methods that can be used to send the results to the screen.
print( ) method: This method prints output on one line until a new line character is encountered.
System.out.print(“Hello”);
System.out.print(“java”);
println( ) method: it takes the information provided and displays it on a line followed by a line feed(carriage
return).
System.out.println(“Hello”);
System.out.printl(“java”);
Output: Hello
Java
Prof: Padmini. R Dept: BCA Programming in JAVA
Scope of Variables
Instance Variables
The Variables those are declared in a class are known as instance variables
When object of Class is Created then instance Variables are Created So they always Related With Class Object
But Remember Only one memory location is created for one instance variable.
Local Variables
The Variables those are declared in Method of class are known as Local Variables
They are Called Local because they are not used from outside the method
The Accessibility of Variables Through out the program is called is Known as the Scope of Variables.
Class Variables
The Variables Those are declared inside a class are called as Class variables or also called as data members of
the class they are friendly by default means they are Accessible to main Method or any other Class Which
inherits.
Operators:
1. Arithmetic operators:
Arithmetic operators are used to perform basic arithmetic operations like addition, subtraction, etc. By
using arithmetic operators we can construct mathematical expressions. java provides all the basic
arithmetic operators.
Operator Meaning
* Multiplication
/ Division
Example
class arith
{
public static void main(String ar[])
{
int a=10, b=3;
Prof: Padmini. R Dept: BCA Programming in JAVA
== Is equal to
!= Is not equal to
3. Logical operators
The logical operators && and || are used to create compound conditions by combining two or more
relations.
Ex: a>b && x==10
Operator Meaning
|| Logical OR
! Logical NOT
4. Assignment operators
Prof: Padmini. R Dept: BCA Programming in JAVA
Assignment operators are used to assign a value, or assign the value of a variable or assign the value of
an expression to a single variable.
Ex: a=10; a=b+c; a=x;
Java also provides shorthand assignment operators. These operators are : +=, -=, *=, /= and %=.
Statement with
Assignment
shorthand assignment
Statement
operator
a=a+1 a+=1
a=a-1 a-=1
a=a*(n+1) a*=(n+1)
a=a/5 a/=5
a=a%b a%=b
5. Increment and decrement operators
Java has two very useful operators not generally found in many other languages. These are the
increment and decrement operators. They are ++ and --.
The operator ++ adds 1 to the operand while – subtract 1. Both are unary operators and are used in the
following forms.
++m; or m++; (equivalent to m=m+1)
--m or m--; (equivalent to m=m-1)
Example
class unary
{
public static void main(String ar[])
{
int a=20;
System.out.println(" a++ = " + (a++));
System.out.println(" ++a = " + (++a));
System.out.println(" a-- = " + (a--));
System.out.println(" --a = " + (--a));
}
}
Output
a++ = 20
++a = 22
a-- = 22
--a = 20
6. Conditional operators (?:)
The character pair ?: is a ternary operator available in java. This operator is used to construct
conditional expression as follows
Prof: Padmini. R Dept: BCA Programming in JAVA
| Bitwise OR
^ Bitwise Ex-OR
~ One’s complement
{
public static void main(String ar[])
{
int a=20;
int b=30;
System.out.println(" a & b =" + (a&b));
System.out.println(" a | b =" + (a|b));
System.out.println(" a<<1 =" + (a<<1));
System.out.println(" a>>1 =" + (a&b));
System.out.println(" a >>> 1 " + (a&b));
System.out.println(" ~a = " + (~a));
}
}
Output
a & b =20
a | b =30
a<<1 =40
a>>1 =10
a >>> 1 10
~a = -21
8. Special operators
Instanceof operator
The instanceof is an object reference operator and return true if the object on the left-hand side is an
instance of the class given on the right-hand side.
Dot operator
The dot operator (.) is used to access the instance variable and methods of class object.
Types of Expressions:
i) Constant Expression:
Ex: 20+5.0
ii) Integer Expression
Ex: m*7
iii) Float Expressions
Ex: 5.78/a
iv) Relational Expressions
Ex: c<=y
v) Logical Expressions
Ex: a>b && a>c
vi) Bitwise Expressions
Ex: x<<3 //shift three bit position to left.
Control statements:
Branching statements:
If we want to execute a specific block among multiple alternatives then the branching statements are
useful. The following are the branching statements.
Simple if:
Prof: Padmini. R Dept: BCA Programming in JAVA
It checks the condition; if the condition is true then the true block statement will be executed; otherwise
the true block will be skipped and the execution will jump to the Next statement that is followed by the true
block.
Syntax:
if(condition)
{
true block;
}
Next statement;
Control Flow Diagram
Example:
import java.io.*;
class distance
{
public static void main(String ar[])throws IOException
{
int x1,x2,dist;
DataInputStream ds=new DataInputStream(System.in);
System.out.println("Enter x1 and x2 values:");
x1=Integer.parseInt(ds.readLine());
x2=Integer.parseInt(ds.readLine());
dist=x2-x1;
if(dist<0)
dist=-dist;
System.out.println("Distance between points : " + dist);
}
}
Output
Enter x1 and x2 values:
Prof: Padmini. R Dept: BCA Programming in JAVA
45
23
Distance between points : 22
if – else statement:
It checks the condition; if the condition is true then it executes the true block. If the condition is false
then it executes the false block. Every time any one of the block will be executed. Not both at the same time.
Control flow diagram
Syntax:
if (expression)
{
True block;
}
else
{
False block;
}
Example
import java.io.*;
class eligible
{
public static void main(String ar[])throws IOException
{
int age;
DataInputStream ds=new DataInputStream(System.in);
System.out.print("Enter your age value :");
age=Integer.parseInt(ds.readLine());
Prof: Padmini. R Dept: BCA Programming in JAVA
if(age>=18)
System.out.println("Eligible for vote");
else
System.out.println("Ineligible for vote");
}
}
Output
Enter your age value: 45
Eligible for vote
else – if ladder:
In else-if ladder the conditions are evaluated from the top to bottom. If true condition is found,
the statement associated with it is executed and control transferred to the statement-x (skipping rest of the
ladder). When all the conditions become false, then the final else block will be executed.
Control flow diagram
Prof: Padmini. R Dept: BCA Programming in JAVA
Syntax:
if(condition1)
{
Block1; }
else if(condition 2)
{
Block2;
}
else if(condition 3)
{
Block3;
}
Prof: Padmini. R Dept: BCA Programming in JAVA
…………
else if(condition n)
{
Block n;
}
else
{
Default Statement;
}
Example
import java.io.*;
class grade
{
public static void main(String ar[])throws IOException
{
int avg;
DataInputStream ds=new DataInputStream(System.in);
System.out.print("Enter your average mark : ");
avg=Integer.parseInt(ds.readLine());
if(avg>=75)
System.out.println("Distinction");
else if(avg>=60)
System.out.println("First class");
else if(avg>=50)
System.out.println("Second class");
else if(avg>=40)
System.out.println("Third class");
else
System.out.println("Fail");
}
}
Output
Enter your average mark : 79
Distinction
switch statement:
Java has a built-in multi-way decision statement known as switch. The switch test the value of a given
variable (or expression) against a list of case values and when a match case is found, a block of statements
associated with that case is executed. default block will be executed if all the above cases are failed.
Syntax:
switch(expression)
{
case val1:
block 1;
break;
Prof: Padmini. R Dept: BCA Programming in JAVA
case val2:
block 2;
break;
…………
case valn:
block n;
break;
default :
default block;
}
Example
import java.io.*;
class day
{
public static void main(String ar[])throws IOException
Prof: Padmini. R Dept: BCA Programming in JAVA
{
int d;
DataInputStream ds=new DataInputStream(System.in);
System.out.print("Enter your number for day : ");
d=Integer.parseInt(ds.readLine());
switch(d)
{
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Enter any integer between 1 and 7");
}
}
}
Output:
Enter your number for day : 3
Wednesday
Looping statements:
The process of repeatedly executing a block of statement is known as looping. Java has the following
looping statements.
while loop:
It executes set of lines until the specified condition becomes false. It is an entry-controlled loop.
Syntax
while(condition)
{
Prof: Padmini. R Dept: BCA Programming in JAVA
Example
import java.io.*;
class factorial
{
public static void main(String ar[])throws IOException
{
int fact=1,n,i=1;
DataInputStream ds=new DataInputStream(System.in);
System.out.print("Enter your n value : ");
n=Integer.parseInt(ds.readLine());
while(i<=n)
{
fact=fact*i;
i++;
}
System.out.println("Factorial value for " + n + " is : " + fact);
}
}
Output
Enter your n value : 6
Factorial value for 6 is : 720
do while loop:
Prof: Padmini. R Dept: BCA Programming in JAVA
It is very similar to while loop, but it is an exit control loop. It continues the loop execution until the
condition becomes false.
Syntax
do
{
Body of the loop;
} while(condition);
Control flow diagram
Example
import java.io.*;
class numbers
{
public static void main(String ars[])throws IOException
{
int n,i=0;
DataInputStream ds=new DataInputStream(System.in);
System.out.print(“Enter your n value : “);
n=Integer.parseInt(ds.readLine());
do
{
System.out.print(" "+ i);
i++;
}while(i<=n);
}
}
Prof: Padmini. R Dept: BCA Programming in JAVA
Output
Enter your n value: 10
0 1 2 3 4 5 6 7 8 9 10
for loop:
This is very similar other loops. But it is very useful when the user knows how many times we need to
execute the body of the loop.
Syntax
for (initialization; condition ; increment/decrement)
{
Body of the loop;
}
Example
import java.io.*;
class table
{
Public static void main(String ars[])throws IOException
{
int n,m;
DataInputStream ds=new DataInputStream(System.in);
System.out.print("Enter your table number m : ");
m=Integer.parseInt(ds.readLine());
System.out.print("Enter number of terms n : ");
n=Integer.parseInt(ds.readLine());
for(int i=1;i<=n;i++)
System.out.println(i + " x " + m + " = " + (i*m));
} }
Output
Enter your table number m : 6
Enter number of terms n : 8
1x6=6
2 x 6 = 12
3 x 6 = 18
4 x 6 = 24
5 x 6 = 30
6 x 6 = 36
7 x 6 = 42
8 x 6 = 48
Jumping statements:
break:
When the break statement is encountered inside a loop, the loop is immediately exited and the program
continues with the statement immediately following the loop. When the loops are nested, the break would only
exit from the loop containing it. That is, the break will exit only a single loop.
Example
import java.io.*;
Prof: Padmini. R Dept: BCA Programming in JAVA
class prime
{
public static void main(String ars[])throws IOException
{
int n,a=0;
DataInputStream ds=new DataInputStream(System.in);
System.out.print("Enter your n value : ");
n=Integer.parseInt(ds.readLine());
for(int i=2;i<n;i++)
{
if(n%i==0)
{
System.out.println("The number " + n+" is not prime ");
a++;
break;
}
}
if(a==0)
System.out.println("The given number " + n + " is a prime number");
}
}
Output
Enter your n value : 23
The given number 23 is a prime number
continue:
Sometimes we need to skip a part of the body of the loop. In this situation we can use continue
statement. When a continue statement is encounter inside a loop control automatically transferred to the
beginning of the loop for the next iteration.
Example
import java.io.*;
class skip
{
public static void main(String ars[])throws IOException
{
int n;
DataInputStream ds=new DataInputStream(System.in);
System.out.print("Enter your n value : ");
n=Integer.parseInt(ds.readLine());
for(int i=1;i<=n;i++) {
if(i%3==0)
{
continue;
}
System.out.print(" " + i);
Prof: Padmini. R Dept: BCA Programming in JAVA
}
}
}
Output
Enter your n value: 25
1 2 4 5 7 8 10 11 13 14 16 17 19 20 22 23 25
Labeled break and continue statements:
We know break statement can terminate only a single loop at a time. Similarly continue statement
transfer the control to the beginning of the current loop. Java provides special feature labeled break and
continue statements. We can use these statements like goto statement in C.
Example
import java.io.*;
class pass
{
public static void main(String ars[])throws IOException
{
out: for(int i=1;i<=3;i++)
{
System.out.print("\npass " + i +" : ");
for(int j=1;j<=100;j++)
{
if(j==10)
break out;
if(j==i)
continue out;
System.out.print(" *");
}
}
}
}
Output
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
Array:
Array is a collection of same type of data stored in single variable name. We can store and retrieve
elements in an array using index or subscript.
One-dimensional array:
A list of items are stored in single variable name using single subscript is called single dimensional
array. We can declare single dimensional array as follows.
typename arrayname[];
or
typename [] arrayname;
Ex:
int a[];
float [] x;
After the declaration, we need to allocate memory spaces for the array type variable. That can be done
by new operator.
Syntax
arrayname=new typename[size];
Prof: Padmini. R Dept: BCA Programming in JAVA
Ex:
a=new int[10];
Example:
class array
{
public static void main(String []x)
{
int list[]={45,78,38,90,12}; //array initialization
int n=list.length;
int temp;
for(int i=0;i<n;i++)
for(int j=i+1;j<n;j++)
if(list[i]>list[j])
{
temp=list[i];
list[i]=list[j];
list[j]=temp;
}
System.out.println("Sorted list is :\n");
for(int i=0;i<n;i++)
System.out.println("\t\tlist[" + i + "]=" + list[i]);
}
}
Output
Sorted list is :
list[0]=12
list[1]=38
list[2]=45
list[3]=78
Prof: Padmini. R Dept: BCA Programming in JAVA
list[4]=90
Two-dimensional array:
If we store and retrieve elements in an array using two subscripts or indexes is called tow-dimensional
array or double dimensional array.
Syntax
typename arrayname[][];
arrayname=new typename[row][column];
Example:
import java.io.*;
class matrix
{
int r,c,m[][]; //two dimensional array declaration
void read()throws IOException
{
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
m[i][j]=Integer.parseInt(di.readLine());
}
void print()
{
for(int j=0;j<c;j++)
System.out.print("\t" + m[i][j]);
System.out.println("\n");
}
}
}
class examplemat
{
public static void main(String ar[]) throws IOException
{
matrix x=new matrix();
x.read();
x.print();
}
}
Output
Enter your r and c values :
2
3
Enter your array elements
Martix :
4 7 6
8 9 6
Prof: Padmini. R Dept: BCA Programming in JAVA
Java ArrayList
Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but there is no size limit.
We can add or remove elements anytime. So, it is much more flexible than the traditional array. It is found in
the java.util package. It is like the Vector in C++.
The ArrayList in Java can have the duplicate elements also. It implements the List interface so we can use all
the methods of List interface here. The ArrayList maintains the insertion order internally.
The important points about Java ArrayList class are:2.8MJava Try Catch
o Java ArrayList class can contain duplicate elements.
o Java ArrayList class maintains insertion order.
o Java ArrayList class is non synchronized.
o Java ArrayList allows random access because array works at the index basis.
o In ArrayList, manipulation is little bit slower than the LinkedList in Java because a lot of shifting needs
to occur if any element is removed from the array list.
As shown in the above diagram, Java ArrayList class extends AbstractList class which implements List
interface. The List interface extends the Collection and Iterable interfaces in hierarchical order.
Constructors of ArrayList
Constructor Description
ArrayList(Collection<? extends It is used to build an array list that is initialized with the elements of
E> c) the collection c.
ArrayList(int capacity) It is used to build an array list that has the specified initial capacity.
Methods of ArrayList
Method Description
void add(int index, E element) It is used to insert the specified element at the specified
position in a list.
boolean add(E e) It is used to append the specified element at the end of a list.
boolean addAll(Collection<? extends E> It is used to append all of the elements in the specified
c) collection to the end of this list, in the order that they are
returned by the specified collection's iterator.
boolean addAll(int index, Collection<? It is used to append all the elements in the specified
extends E> c) collection, starting at the specified position of the list.
void clear() It is used to remove all of the elements from this list.
E get(int index) It is used to fetch the element from the particular position of
the list.
Iterator()
listIterator()
Prof: Padmini. R Dept: BCA Programming in JAVA
int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence
of the specified element, or -1 if the list does not contain this
element.
<T> T[] toArray(T[] a) It is used to return an array containing all of the elements in
this list in the correct order.
boolean contains(Object o) It returns true if the list contains the specified element
int indexOf(Object o) It is used to return the index in this list of the first occurrence
of the specified element, or -1 if the List does not contain
this element.
boolean removeAll(Collection<?> c) It is used to remove all the elements from the list.
boolean removeIf(Predicate<? super E> It is used to remove all the elements from the list that
filter) satisfies the given predicate.
protected void removeRange(int It is used to remove all the elements lies within the given
fromIndex, int toIndex) range.
void replaceAll(UnaryOperator<E> It is used to replace all the elements from the list with the
operator) specified element.
void retainAll(Collection<?> c) It is used to retain all the elements in the list that are present
in the specified collection.
E set(int index, E element) It is used to replace the specified element in the list, present
at the specified position.
void sort(Comparator<? super E> c) It is used to sort the elements of the list on the basis of
specified comparator.
List<E> subList(int fromIndex, int It is used to fetch all the elements lies within the given range.
toIndex)
int size() It is used to return the number of elements present in the list.
Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.
Java new generic collection allows you to have only one type of object in a collection. Now it is type safe so
typecasting is not required at runtime.
In a generic collection, we specify the type in angular braces. Now ArrayList is forced to have the only
specified type of objects in it. If you try to add another type of object, it gives compile time error.
For more information on Java generics, click here Java Generics Tutorial.
Vectors:
Vector implements a generic dynamic array. Vector class can hold objects of any type and any number.
This is not necessary the entire object must be homogeneous. We can declare Vector object as follows,
Syntax:
Vector vecobj=new Vector(); //declaring without size
Vector vecob=new Vector(3); // declaring with size
Vectors have the number of advantages over arrays.
1. It is convenient to use Vector class to store objects
2. A vector class can be used to store objects that may vary in size.
3. We can add and delete objects from the list when we required.
Method Task performed
v.addElement(item); Add the item to the list at the end
v.elementAt(n); Returns the name of the nth object in the list
v.size(); Returns the number of objects in the list
v.removeElement(item); Removes the element item form the list.
v.removeElementAt(n); Removes the element in the nth position of the list.
v.removeAllElements() Removes all the elements in the list
v.insertElementAt(item,n) Inserts the element item at nth location in the list
v.firstElement() Returns the first element in the list
v.lastElement() Returns the last element in the list
Returns the index of first occurrence of item in the list. If the object is not in the
v.indexOf(item)
list, -1 is returned.
v.isEmpty(); Returns ‘true’ if the list is empty, else return ‘false’.
Returns the index of the last occurrence of the item in the list. -1 is returned if the
v.lastIndexOf(item);
item not present in the list.
Example:
import java.io.*;
import java.util.*;
class comp
{
int real,img; }
class vector
{
public static void main(String a[])throws Exception
{
DataInputStream di=new DataInputStream(System.in);
int i;
float f;
double d;
System.out.println("Enter your int, float and double values :");
i=Integer.parseInt(di.readLine());
f=Float.parseFloat(di.readLine());
Prof: Padmini. R Dept: BCA Programming in JAVA
d=Double.parseDouble(di.readLine());
Vector v=new Vector();
v.addElement(new Integer(i));
v.addElement(new Float(f));
v.addElement(new Double(d));
comp c=new comp();
v.addElement(c);
System.out.println("Size of the class is : " + v.size());
System.out.println("Our list contains :");
for(int j=0;j<v.size();j++)
System.out.println("elementat[" + j + "] = "+(v.elementAt(j)).toString());
v.removeElementAt(3);
v.insertElementAt(new String("Java"),1);
System.out.println("Now our list contains :");
for(int j=0;j<v.size();j++)
System.out.println("elementat[" + j + "] = "+(v.elementAt(j)).toString());
v.removeAllElements();
System.out.println("After removing the elements is : " + v.size());
}
}
Output
Enter your int, float and double values :
10
72.325
960.32587
Wrapper
Simple Type
class
boolean Boolean
Char Character
double Double
Float Float
int Integer
long Long
Example:
Integer intval=new Integer(i);
Float fval=new Float(f);
Double dblval=new Double(d);
Long lval=new Long(l);
Note:Here i, f, d and l denotes int, float, double and long values respectively. These values may be constants or
variables.
Prof: Padmini. R Dept: BCA Programming in JAVA
UNIT 3
Classes and objects: Defining a classes –methods-creating objects-Accessing class members- constructors-
Method over loading –Static members-Nesting of Methods-This keyword-command line input. Inheritance:
Defining inheritance-Types of inheritance-over ridding methods-final variables and methods- final classes-final
methods- abstract methods and classes –visibility control-interfaces: Defining interface-Extending interface-
implementing interface-Accessing interface variables. Strings: string array- strings methods-string buffer class.
Classes:
Class is an important feature of object-oriented language. Class is used to create a new user defined
data type. In java we can declare a class using the keyword class. Body of the class is enclosed with a pair
braces. Variables declared inside the class is called instance variable and methods declared inside class is
called instance methods. Instance variables also called member variables. The syntax for declaring a class as
follows,
Syntax:
class classname [extendssuperclassname]
{
[Fields declaration;]
[Methods declaration;]
}
Object:
Once a class has been created we can declare variables of that type using the class name. In java these
variables are called objects. Simply object are variables in the user-defined data type. Main purpose of the
object is to access the members of the class.
Syntax:
class_name obj_name=new class_name();
Methods:
Method is a functions defined for achieving well-defined task. Method declaration has four basic parts:
1. The name of the method
2. Return type of the method
3. A list of parameters
4. The body of the method
Syntax:
ret_type methodname(parameterlist)
{ Body of the method; }
Accessing class members:
Remember that we can access the instance variables and instance methods directly. For accessing
members we need object of the class and dot (.) operator. We can access the members as follows,
Syntax
objectname.variablename=value;
objectname.methodname(parameterlist);
Example
import java.io.*;
class box
{
Prof: Padmini. R Dept: BCA Programming in JAVA
Constructor:
Constructor is the special member function of a class. It has the same name as the class name. We can
not specify return type to a constructor not even void. Constructor methods automatically called at the time of
object creation of its associated class. The main purpose of the constructor is to initialize the objects.
Syntax:
class class_name
{
……..
class_name(parameters)
{
Body of the constructor;
Prof: Padmini. R Dept: BCA Programming in JAVA
}
……….
}
Example
import java.io.*;
class complex
{
int real,img;
complex() //constructor function
{
real=0;
img=0;
}
void read()throws IOException //member function
{
System.out.println("Enter your real and img values : ");
DataInputStream ds=new DataInputStream(System.in);
real=Integer.parseInt(ds.readLine());
img=Integer.parseInt(ds.readLine());
}
void print() //member function
{
if(img<0)
System.out.println(real +""+ img +"i");
else
System.out.println(real + "+" + img + "i");
}
}
class construct
{
public static void main(String ars[])throws IOException
{ complex b=new complex(); //calling constructor method
b.print(); // calling instance method
b.read(); // calling instance method
b.print();
}
}
Constructor overloading:
class box
{
int length, width, height;
box() //default constructor
{
length=width=height=0;
Prof: Padmini. R Dept: BCA Programming in JAVA
}
box(int x)
{
length=width=height=x;
}
box(int a,int b, int c)
{
length=a;
width=b;
height=c;
}
int volume()
{
return length*width*height;
}
}
class overcons
{
public static void main(String ar[])
{
box mybox1=new box();
System.out.println("Volume of mybox1 is : " + mybox1.volume());
box mybox2=new box(5);
System.out.println("Volume of mybox2 is : " + mybox2.volume());
box mybox3=new box(12,6,5);
System.out.println("Volume of mybox3 is : " + mybox3.volume());
}
}
Output
Volume of mybox1 is : 0
Volume of mybox2 is : 125
Volume of mybox3 is : 360
Method overloading:
Same method name with different argument is called method overloading. It is one of the features of
object-oriented programming. Method overloading is useful when objects are required to perform similar task
but using different arguments. When we call a method, java matches up the method name first and then the
number and type of arguments to decide which one of the definition to execute. This process is known as
polymorphism.
Example
class classarea
{
void area(int x)
{
Prof: Padmini. R Dept: BCA Programming in JAVA
{
count.meth(34); //calling static method
}
}
Output
a=3
b = 13
c = 34
There can be a lot of usage of Java this keyword. In Java, this is a reference variable that refers to the current
object.
Inheritance:
The mechanism of deriving a new class from old one is called inheritance. The old class is known as
the base class or super class or parent class and the new class is called the sub class or derived class or child
class.extends is a keyword used to inherit a base class to a derived class.
Syntax
class subclassname extends superclassname
{
Body of the subclass; }
Types of inheritance:
Single inheritance: One base class with only one derived class is called single inheritance.
Prof: Padmini. R Dept: BCA Programming in JAVA
B b=new B();
b.show(); //calling base class function
b.disp(); //calling derived class function
}
}
Output
Base class member
Derived class member
super():Super() method is used to call the super class constructor. The syntax is as follows.
super(argument)
super() must be the first statement inside the subclass constructor.
Example
class two {
int length,breadth;
two(int length,int breadth)
{
this.length=length;
this.breadth=breadth;
}
int area()
{
return length*breadth;
}
}
class three extends two
{
int height;
three(int a,int b, int c)
{
super(a,b); //calling base class constructor
height=c;
}
int volume()
{
return length*breadth*height;
}
}
class superex
{
public static void main(String ar[])
{
three t=new three(10,20,30);
System.out.println("Area of the box is : " +t.area());
System.out.println("volume of the box is : "+t.volume());
Prof: Padmini. R Dept: BCA Programming in JAVA
}
}
Output
Area of the box is : 200
volume of the box is : 6000
Overriding methods:
When both base and derived classes have the same function name with same signature then derived
class member overrides the base class member. This process is called overriding. That means whenever we
call the base class member using derived class object, it calls its own member and never calls base class
member.
Example for overriding
class A //base class
{
void show() //base class show method
{
System.out.println("This is base class method");
}
}
class B extends A //extending class A to B
{
void show() //derived class show method
{
System.out.println("This is derived class method");
} }
class override
{
public static void main(String ar[]) {
B x=new B();
x.show();
x.show();
}
}
Output
This is derived class method
This is derived class method
Solving overriding problem using super keyword:
class A //base class
{
void show() //base class show method
{ System.out.println("This is base class method");
}
}
class B extends A //extending class A to B
{
Prof: Padmini. R Dept: BCA Programming in JAVA
}
}
class finalclass {
public static void main(String x[])
{
second s=new second();
s.show();
}
}
finalize () method:
Sometimes an object will need to perform some action when it is destroyed. For example if an object is
holding some non-java resource such as file handler or character font and then we need to make sure these
resources are freed before an object is destroyed. finalize() method must be a protected of a class.
Example
import java.io.*;
class complex
{
int real,img;
complex(int a,int b)
{
real=a;
img=b;
finalize();
}
complex()
{
real=0;
img=0;
finalize();
}
protected void finalize()
{
if(img<0)
System.out.println(real+ ""+img+"i");
else
System.out.println(real+"+"+img+"i");
}
}
class comexam {
public static void main(String ar[]) {
complex c1=new complex(10,20);
complex c2=new complex(30,40);
}
}
Prof: Padmini. R Dept: BCA Programming in JAVA
Output
10+20i
30+40i
Abstract method:
We know that if a method is declared as final that can’t be redefined by the subclass. Abstract method
is direct opposite to the final method. If a method is declared as abstract that must be redefined inside the
subclass.
abstractret_type methodname(paramerters);
Abstract class:
If a class is declared as abstract that must be inherited by a subclass. We can declare abstract class as
follows.
Abstract class classname
{
Body of the abstract class;
}
Note:We can’t declare objects for abstract class.
Example
abstract class abc //abstract class
{
abstract void show(); //abstract method declaration
}
class xyz extends abc {
void show() //abstract method definition {
System.out.println("Show method defined here");
}
}
class absclass
{
public static void main(String p[])
{
xyz t=new xyz();
t.show();
}
}
Output
Show method defined here
Visibility control:
Visibility controls provide the different level of protection to the class member. Java provides the
following visibility control. They are public, private and protected.
public access:
If a variable or method declared as public that can be accessed anywhere.
private access:
Anything declared as private that cannot be seen outside of its class.
No modifier (default):
Prof: Padmini. R Dept: BCA Programming in JAVA
When a member does not have explicit access specification, it is in default mode. These members can
be accessed by same package subclass as well as other classes (non-subclass) in the same package.
protected access:
This visibility level lies between the public access and no modifier access. That is the protected
modifier makes the fields visible not only all classes and sub classes in the same package but also to subclass in
other packages.
Strings:
String is a sequence of characters. The easiest way to represent a string in java is by using a character
array.
Ex: char chararray[]=new char[4];
chararray[0]=’J’;
chararray[1]=’A’;
chararray[2]=’V’;
chararray[3]=’A’;
But character arrays are not good enough to support the range of operations we may like to perform on string.
String is probably the most commonly used class in Java’s class library. The clear reason for this is
that strings are a very important part of programming. A String is immutable, i.e. when it's created, it can
never change. Once string created we can’t modify them. Any such attempt will lead to the creation of new
strings. We can create string object as follows,
Syntax:
String str_name;
Str_name=new String(“string”);
Ex:
String fname;
Prof: Padmini. R Dept: BCA Programming in JAVA
fname=new String(“ranjith”);
In java String class provides variety of methods to accomplish the string manipulations. Below we
listed some of the most commonly used methods.
Method Task performed
S2=s1.toLowerCase(); Converts the string s1 to all lowercase
S2=s1.toUpperCase(); Converts the string s1 to all Uppercase
S2=s1.replace(‘x’,’y’); Replaces all appearances of x with y.
S2=s1.trim(); Removes white spaces beginning and end of the string s1.
S1.equals(s2); Returns ‘true’ if both strings are equal.
S1.equalsIgnoreCase(s2); Returns ‘true’ if s1=s2, ignoring the case of characters.
S1.length(); Returns the length( number of characters) of s1
S1.charAt(n) Returns the nth character of string S1.
s1.compareTo(s2); Returns negative if s1<s2, positive if s1>s2 and 0 if both are equal.
S1.concat(S2); Concatenates S1 and S2.
S1.substring(n); Returns the substring starts from nth character of S1.
S1.substring(n,m); Returns the substring starts from nth character up to mth ( not included mth)
x.toString(); Creates the string representation of the object x.
S1.indexOf(‘x’); Gives the position of the first occurrence of ‘x’ in the string s1.
S1.indexOf(‘x’,n) Gives the position of the first occurrence of ‘x’ after the nth position in string S1.
S1.lastIndexOf(‘x’) Give the position of the last occurrence of ‘x’ in the string s1.
Example1:
import java.io.*;
class strexam
{
public static void main(String a[])throws Exception
{
DataInputStream di=new DataInputStream(System.in);
String s=new String();
String s2,s3;
int l;
System.out.print("Enter your string :");
s=di.readLine();
l=s.length();
System.out.println("Size of the String is :"+l);
s2=s.toLowerCase();
System.out.println("Lowercase is : "+s2);
s3=s.toUpperCase();
System.out.println("Uppercase is : " +s3);
System.out.println("Equals() : " + s.equals(s3));
System.out.println("Compareto() : " + s.compareTo(s3));
System.out.println("Equalsignorecase() : " + s.equalsIgnoreCase(s3));
}
Prof: Padmini. R Dept: BCA Programming in JAVA
}
Output
Enter your string : Programming in Java
Size of the String is :19
Lowercase is : programming in java
Uppercase is : PROGRAMMING IN JAVA
Equals() : false
Compareto() : 32
Equalsignorecase() : true
Example2:
import java.io.*;
class strexam1 {
public static void main(String a[])throws Exception
{
DataInputStream di=new DataInputStream(System.in);
String s=new String();
String s1,s2,s3,s4;
System.out.println("Enter your First and Second string");
s=di.readLine();
s1=di.readLine();
s2=s.concat(s1);
System.out.println("String concatenation :"+s2);
System.out.println("Substring(n) : "+s2.substring(5));
System.out.println("Substring(n,m) : " +s2.substring(5,11));
s4=new String("Praveena");
System.out.println("indexOf(a) : " + s4.indexOf('a'));
System.out.println("indexOf(a,4) : " + s4.indexOf('a',4));
}
}
Output
Enter your First and Second string
priya
dharshini
String concatenation :priyadharshini
Substring(n) : dharshini
Substring(n,m) : dharsh
indexOf(a) : 2
indexOf(a,4) : 7
String Buffer class:
StringBuffer is also used to represent a sequence of character that is string. But the StringBuffer Class
supports growable and modifiable string where as String class supports constant strings. We can create
StringBuffer object as follows,
Syntax:
StringBuffer objname=new StringBuffer(“string”);
Prof: Padmini. R Dept: BCA Programming in JAVA
Ex:
StringBuffer sb=new StringBuffer(“Hello JAVA”);
Method Task performed
S1.length(); Returns the length( number of characters) of s1
S1.charAt(n); Returns the nth character of string S1.
S1.append(S2); Adds S2 content at the end of S1.
S1.delete(n,m); Deletes substring from nth position to m-1th position
S1.substring(n,m) Returns the substring form nth position to mth position
S1.insert(n,S2); Inserts the string S2 in the nth location of S1.
S1.length(); Returns the length( number of characters) of s1
S1.indexOf(s2); Returns the first occurrence of s2 in S1.
S1.indexOf(s2,n); Returns the first occurrence of s2 in S1after nth position.
S1.lastIndexOf(s2); Returns the last occurrence position of s2 in S1.
S1.reverse() Returns the reverse of the string
Example
import java.io.*;
class strbuf
{
public static void main(String[]ar)throws Exception
{
DataInputStream di=new DataInputStream(System.in);
System.out.print("Enter your main string : ");
StringBuffer s1=new StringBuffer(di.readLine());
System.out.print("Enter your next string : ");
StringBuffer s2=new StringBuffer(di.readLine());
System.out.println("Length of the main string is : " +s1.length());
System.out.println("Concatenated string is : " + s1.append(s2));
System.out.println("After concatenation s1 length is : " +s1.length());
System.out.println("Substring of s1 from 7th position is : " + s1.substring(7));
System.out.println("After deletion of sub string 0-7 : " +s1.delete(0,7));
System.out.println("After Insertion of vinoth in the 0th position : " + s1.insert(0,"vinoth"));
System.out.println("Final length of the string is : " + s1.length());
System.out.println("Reverse of s1 is : " + s1.reverse());
}
}
Output
Enter your main string : sathish
Enter your next string : kumar
Length of the main string is : 7
Concatenated string is : sathishkumar
After concatenation s1 length is : 12
Substring of s1 from 7th position is : kumar
Prof: Padmini. R Dept: BCA Programming in JAVA
Interfaces:
An interface is just like a class with a major different.The different is that interfaces define only abstract
methods and final variables. This means that interfaces do not specify any code to implement these methods.
Syntax:
interface interfacename
{
Variable declaration;
Method declaration;
}
Example:
interface item
{
finalint code=1000;
final String iname=“Fan”;
}
Differences between class and interface:
1. The member of a class can be constant or variables. But the members of an interface are always
declared as constant (final variables).
2. Class can contain abstract or non-abstract methods. But methods in an interface must be abstract.
3. Class can use various access specifiers. But an interface can use only public access.
4. For class we can declare and initiate object. But for interface we can declare object, can’t be initiated.
Extending interface:
Like a class an interface can be inherited to some other interface.We can inherit a super interface to sub
interface with help of extends keyword.
Syntax:
interface name2 extends name1
{
body of the name2;
}
Implementing interface:
An interface can act as a base class for a sub class.We can do this with the help of implements keyword
Syntax:
class classname implements interfacename
{
Body of class
}
Example:
interface item // interface declaration
Prof: Padmini. R Dept: BCA Programming in JAVA
{
finalint code=1000;
final String name="Fan";
}
interface itemdisp extends item //extending interface
{
void display();
}
class interclass implements itemdisp // implements interface to class
{
public void display()
{
System.out.println("Item code is : " + code);
System.out.println("Name of the item : " + name);
}
}
class interdemo
{
public static void main(String ar[])
{
interclass i=new interclass();
i.display();
}
}
Output
Item code is: 1000
Name of the item: Fan
Prof: Padmini. R Dept: BCA Programming in JAVA
Unit 4
Packages: java API packages –system packages-Naming convention –creating & Accessing a packages –
Adding class to a packages-Hiding classes . Exception Handling: Limitations of Error Handling –Advantages
of Exception Handling –Types of Errors-Basics of Exception Handling –try blocks-throwing an exception-
catching an exception-finally statement. Multithreading: creating Threads –life of a Thread –Defining
&Running Thread- Thread Methods- Threads Priority –Synchronization – implementation Running interface-
Thread.
Packages:
Java API provides a large number of classes grouped into different packages according to functionality.
Most of the time we are using the packages available within the Java API.Frequently used packages are: lang,
util, io, awt, net, applet.
java.lang: It includes language support classes. They are automatically imported. It includes classes for
primitive types, strings, math functions, thread and exceptions.
java.util: It includes language utility classes such as Vector, Random, Date, etc.
java.awt: It is used to implementgraphical user interface. It contains the classes for windows, buttons, lists,
menus and so on.
java.net: classes for networking. They include classes for communicating with local computers as well as
with internet servers.
Prof: Padmini. R Dept: BCA Programming in JAVA
The packages are organized in a hierarchical structure. This is illustrated in the following diagram. The
package java contains the sub package awt, which in turn contains various classes required for implementing
graphical user interface.
There are two ways of accessing the class stored in a package. The first approach is to use the fully
qualified class name of the class that we want to use. For example, if we want to refer the class Colorin the
awt package, then we can do as follows,
java.awt.Color
Notice that awt is a package within the package java and then the hierarchy is represented by separating
the level with dots.
In some cases we want to use a class in a number of places in a program. We can achieve this easily as
follows:
Prof: Padmini. R Dept: BCA Programming in JAVA
importpackagename.classname;
Or
importpackagename.*;
These are import statements and must appear at the top of the file, before any class declarations.
importis a keyword. For example if you want to access the Color class that is available in awtpackage we can
do any one of the following.
importjava.awt.Color;
or
importjava.awt.*;
[Note: * represents all the classes available inside the awt package].
Naming conventions:
We can name a package using the standard java naming rules. Packages begin with lowercase letter.
This makes it easy for users to distinguish package names form the class names. For example,
double y=java.lang.Math.sqrt(x);
Here java.lang is the name of the package, Mathis the class name available in java.lang and sqrt() is a
function in Math class.
Creating packages:
We must first declare the name of the package using the package keyword followed by a package
name. This must be first statement in a java source file. Then we define a class.
packagepackagename;
Example
packagefirstpackage;
…………..
}
Prof: Padmini. R Dept: BCA Programming in JAVA
Here the package name is firstpackage. The class firstclass is now considered a part of this package.
This file should be saved as firstclass.java, and located in a directory firstpackage.
1. Create a subdirectory under the directory where the main source file is stored.
2. Declare the package at the beginning of the file using the statement package packagename;
3. Define the class that is to be put in the package and declare it as public.
5. Compile this file once. Thus make .class in the sub directory.
Example
package mypack;
int real,img;
real=x;
img=y; }
if(img<0)
else
Prof: Padmini. R Dept: BCA Programming in JAVA
import mypack.*;
import java.io.*;
class packdemo
inta,b,c,d;
a=Integer.parseInt(di.readLine());
b=Integer.parseInt(di.readLine());
c=Integer.parseInt(di.readLine());
d=Integer.parseInt(di.readLine());
c1.print();
c2.print();
Output
10 -20 -30 40
Prof: Padmini. R Dept: BCA Programming in JAVA
10-20i
-30 + 40i
Thread:
A thread is similar to a program that has a body, and an end, and executes commands sequentially.
Threads in java are subprograms of a main application program and share the same memory space.
They are known as lightweight threads or lightweight processes.
Multithreaded program: a program that contains multiple flows of control is known as multithreaded
program.
Multithreading Multitasking
The processor has to switch between different The processor has to switch between different
threads. processes.
Creating threads:
1. By creating a thread class: Define a class that extends Thread class and override its run() method.
2. By converting a class to a thread: Definea class that implements Runnable interface and define the
method run().
Implementing run():
The run() method is the heart and soul of any threads. It makes up the entire body of a thread and it is
the only method in which we can define the behavior of the thread. A run() appear as follows
Statements;
2. Implements the run() method that represent the behavior of the thread.
Example
for(int i=1;i<=5;i++)
for(int j=1;j<=5;j++)
for(int k=1;k<=5;k++)
class threaddemo
A x=new A();
B y=new B();
C z=new C();
Output
Start thread A
Start thread B
From Thread A : i = 1
From Thread A : i = 2
Start thread C
From Thread A : i = 3
From Thread A : i = 4
From Thread A : i = 5
Exit from A
From Thread B : j = 1
From Thread B : j = 2
From Thread B : j = 3
From Thread C : k = 1
From Thread C : k = 2
From Thread C : k = 3
From Thread C : k = 4
From Thread C : k = 5
Prof: Padmini. R Dept: BCA Programming in JAVA
Exit from C
We can start the thread execution by call the start() function. We can also stop a thread that is currently
running with the help of stop(). Now the stopped thread moves to the dead state.We can move the threads to
the blocked state by using the following functions:
blocked state is not a dead state, so the process can continue its execution after sometimes.
During the life time of a thread, there are many states it can enter. They include:
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
Prof: Padmini. R Dept: BCA Programming in JAVA
A thread is always in one of these five states. During execution thread can move from one state to another
state.
Newborn state:
When we create a thread object, the thread is born and is said to be in newborn state. At this state, we
can do only one of the following:
Runnable state:
The runnable state means that the thread is ready for execution and is waiting for the availability of the
processor. That is, the thread has joined the queue of threads that are waiting for execution. If all the threads
have equal priority, then they are given time slots for execution in round robin fashion.
Running state:
Running means that the processor has given its time to the thread for its execution. A running thread
may surrender its control in one of the following situations.
Prof: Padmini. R Dept: BCA Programming in JAVA
Blocked state:
A thread is said to be blocked when it is prevented from entering into the runnable state and
subsequently the running state. This happens when the thread is suspended, sleeping or waiting in order to
satisfy certain requirements. A blocked thread is considered “not runnable” but not dead.
1. Thread has been suspended using suspend() method. A suspended thread can be retrieved by using the
resume() method. This approach is useful when we want to suspend a thread for some times due to
certain reason, but do not want to kill.
2. We can put a thread to sleep for a specified time period using the method sleep(time), where time is in
milliseconds.
3. Thread can be told to wait until some event to occur. This is done using the wait() method. The threads
can be scheduled to run again using the notify() method.
Dead state:
Prof: Padmini. R Dept: BCA Programming in JAVA
A running thread life ends when its execution completed. It is a natural death. Moreover we can kill a
process by sending the stop message to it at any state thus causing a premature death to it.
Example
for(int i=1;i<=5;i++)
if(i==1)
for(int j=1;j<=5;j++)
if(j==3)
}
Prof: Padmini. R Dept: BCA Programming in JAVA
for(int k=1;k<=5;k++)
if(k==1)
try
catch(Exception e)
class threadmeth {
Output
Start thread A
Start thread B
From Thread A : i = 1
From Thread A : i = 2
Start thread C
From Thread A : i = 3
From Thread A : i = 4
From Thread A : i = 5
Exit from A
From Thread B : j = 1
From Thread B : j = 2
From Thread B : j = 3
From Thread C : k = 1
From Thread C : k = 2
From Thread C : k = 3
From Thread C : k = 4
From Thread C : k = 5
Exit from C
Thread Exceptions:
It is necessary to handle the exception during the thread execution. For example, a sleeping thread
cannot deal with the resume() method because a sleeping thread cannot receive any instructions. The same is
true with the suspend() method.
Prof: Padmini. R Dept: BCA Programming in JAVA
Thread priority:
Java permits us to set the priority of a thread using setPriority() method. The syntax is as follows:
Threadname.setPriority(intnumber);
The intnumber is an integer value to set the priority for a thread. The Thread class has several priority
constants:
MIN_PRIORITY=1
NORM_PRIORITY =5
MAX_PRIORITY=10
The intnumber may be any one of the value between 1 and 10. Note that the default priority is
NORM_PRIORITY.
The Thread class defines several methods that help to manage threads. The methods and descriptions
are given below.
Method Meaning
Example
for(int i=1;i<=5;i++)
for(int j=1;j<=5;j++)
for(int k=1;k<=5;k++)
class threadpri
Prof: Padmini. R Dept: BCA Programming in JAVA
A x=new A();
B y=new B();
C z=new C();
y.setPriority(Thread.MAX_PRIORITY);
z.setPriority(Thread.MIN_PRIORITY);
x.setPriority(z.getPriority()+1);
x.start();
y.start();
z.start();
Output
Start thread A
Start thread B
From Thread A : i = 1
Start thread C
From Thread A : i = 2
From Thread B : j = 1
From Thread B : j = 2
From Thread A : i = 3
From Thread B : j = 3
From Thread C : k = 1
From Thread B : j = 4
From Thread A : i = 4
From Thread B : j = 5
Exit from B
From Thread C : k = 2
From Thread C : k = 3
From Thread C : k = 4
From Thread C : k = 5
Exit from C
From Thread A : i = 5
Exit from A
[Note: But these methods do not give any assurance to which process terminated first. It is mostly depends on
the CPU selection process.]
Synchronization:
When two or more threads need to access a shared resource, they need some way to ensure that the
resource will be used by only one thread at a time. It can be achieved with the help of the keyword
synchronization.
If we declare a method as synchronized, then java creates a “monitor” and hands over it to the thread
that calls the first time. As long as the thread holds the monitor, no other thread can enter the synchronized
section of code.
Example
class table
void prints(int j)
for(int i=1;i<=5;i++)
Prof: Padmini. R Dept: BCA Programming in JAVA
table ta;
int tn;
Thread t;
thread(table x, int a)
ta=x;
tn=a;
t=new Thread(this);
t.start();
synchronized(ta)
ta.prints(tn);
{
Prof: Padmini. R Dept: BCA Programming in JAVA
try
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch(InterruptedException e)
System.out.println("Interrupted");
Output
1 * 5=5
2 * 5=10
3 * 5=15
4 * 5=20
5 * 5=25
1 * 9=9
2 * 9=18
3 * 9=27
4 * 9=36
Prof: Padmini. R Dept: BCA Programming in JAVA
5 * 9=45
1 * 7=7
2 * 7=14
3 * 7=21
4 * 7=28
5 * 7=35
Implementing the Runnable interface:
We can create a thread by implementing Runnable interface. The Runnable interface declares the
run() method that is required for implementing threads in our programs. We can achieve this using the
following steps:
3. Create a thread object and that is instantiated from this runnable class.
Example
for(int i=1;i<=5;i++)
System.out.println("End of threadX");
class runnabletest
X runs=new X();
t.start();
Output
ThreadX : 1
ThreadX : 2
ThreadX : 3
ThreadX : 4
ThreadX : 5
End of thread
Run-time errors:
Sometimes a program may compile successfully, but may not run properly. Such programs may
produce wrong results due to wrong logic or may terminate due to errors such as stack overflow. These types
of errors are called run-time errors.
Most common run-time errors are listed below:
Dividing by zero
Array index of out of bounds
Passing parameter that is not in a valid range or value for a method.
Trying to illegally change the state of a thread
Attempting to use a negative size for an array.
Converting invalid string to a number.
Accessing a character that is out of bounds of a string.
Example
class error
{
public static void main(String ar[])
{
int a=10;
int b=5, c=5;
int x=a/(b-c); //division by zero
System.out.println(" X : " + x);
}
}
The above program does not have any syntax error, so it can produce .class file. But while executing
the program it will display the following message and terminate the program execution immediately.
java.lang.ArithmeticException: / by zero
aterror.main(error.java:7)
Exceptions:
An exception is a condition that is caused by a run-time error in the program.When the java interpreter
encounters an error such as dividing an integer by zero during execution, it creates an exception object and
throws it.If the exception object is not caught and handle properly, the interpreter will display an error message.
If you want the program to continue with the execution of the remaining code, then we should try to
catch the exception object thrown by the error condition and then display an appropriate message for taking
corrective actions.This task is known as exception handling.
The purpose of exception handling mechanism is to provide a means to detect and report an
“exceptional circumstance”.The exception handling performs the following tasks:
1. Find the problem( hit the exception)
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (catch the exception)
4. Take corrective actions (Handle the exception)
Common java exceptions:
ArithmeticException –caused by math errors such as division by zero.
ArrayIndexOutOfBoundsException – caused by bad array index
ArrayStoreException – caused when a program tries to store the wrong type of data in an array.
Prof: Padmini. R Dept: BCA Programming in JAVA
try:
Java uses a keyword try to perform a block of code that is likely to cause an error condition and “throw”
an exception.
catch:
A catch block defined by the keyword catch “catches” the exception “throwb” by the try block and
handles the exception with appropriate code. The catch block is immediately added after the try block. The
following statements illustrate the use of simple try andcatch statements:
Prof: Padmini. R Dept: BCA Programming in JAVA
………….
…………
try
{
Statements; //generate an exception
}
catch(Exception e)
{
Statements; //process the exception
}
Example:
class error
{
public static void main(String ar[])
{
int a=10;
int b=5, c=5;
int x,y;
try
{
x=a/(b-c); //Exception
}
catch(ArithmeticException e)
{
System.out.println("Division by Zero");
}
y=a/(b+c);
System.out.println("y = " + y);
}
}
Output
Division by Zero
y=1
Nested try statements:
If a try-catch block is specified within another one try block is called nested try statement. The
following program clearly explains the use of nested try statement.
class nesttry
{
public static void main(String arg[])
{
int a=1, b=2, c=1, x=5, z;
try
{
int p[]={2};
Prof: Padmini. R Dept: BCA Programming in JAVA
p[3]=33;
try
{
z=x/((b*b)-(4*a*c));
System.out.println("The value of z is : " + z);
}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out of bounds");
}
}
}
Output
Array index out of bounds
Multiple catch statement:
It is possible to give more catch block for a single try block. The syntax is as follows
try
{
Statement;
}
catch(Exception typ1)
{
statements
}
catch(Exception type2)
{
statements
}
catch(Exception typen)
{
statements
}
Example:
class exam136
{
public static void main(String args[])
{
int a[]={5,10};
int b=5;
Prof: Padmini. R Dept: BCA Programming in JAVA
try {
a[1]=Integer.parseInt("abc");
int x=a[1]/(b-a[0]);
}
catch(ArithmeticException e)
{
System.out.println("Division by Zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index error");
}
catch(NumberFormatException e)
{
System.out.println("Number format exception");
}
System.out.println("End of program");
}
}
Output:
Number format exception
End of program
In the above program if any arithmetic exception generated that can be caught by the
ArithmeticException catch block. If we use invalid array index then that can be caught by the
ArrayIndexOutOfBoundsException.
Using finally Statement:
finally defines a block of code that will be executed after a try/catch block. The finally block ensure
that the block of code will be executed, regardless of whether or not the exception is thrown. The finally block
will execute even if no catch statement matches the exception.
Example:
class exam136
{
public static void main(String args[]) {
int a[]={5,10};
int b=5;
try
{
a[1]=Integer.parseInt("abc");
int x=a[1]/(b-a[0]);
}
catch(ArithmeticException e)
{
Prof: Padmini. R Dept: BCA Programming in JAVA
System.out.println("Division by Zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index error");
}
catch(NumberFormatException e)
{
System.out.println("Number format exception");
}
finally
{
System.out.println("End of program");
}
}
}
Output
Number format exception
End of program
Throwing our own Exceptions:
There may be times we would like to throw our own exceptions. We can do this with the help of throw
keyword. The syntax is as follows
thrownew exceptionclass()
Example:
classmyexception extends Exception
{
myexception()
{
super("Ball number is invalid");
}
}
classownexcept
{
public static void main(String ar[])
{
int x=7;
try
{
if((x>6)||(x<1))
throw new myexception();
}
catch(myexception e)
{
Prof: Padmini. R Dept: BCA Programming in JAVA
System.out.println(e.getMessage());
}
}
}
Output
Ball number is invalid
Unit 5
I/O streams file- streams-Advantages – The stream class-Byte stream-character stream. Applets: Introduction –
Applet life cycle – Creating &Executing an Applet- Applet tags in HTML-parameter tag-Aligning the display-
Graphics class: Drawing and Filling lines-Rectangle –Polygon-Circles- Arcs-Line Graphs-Drawing Bar charts
AWT components and Even Handlers: Abstract Window tool kit-Event Handlers-Event Listeners- AWT-
controls and Event Handling: Labels-Text component-Action Event –Button –Check Boxes-Item Event –
Choice- Scrollbars- Layout Managers-Input Event-Menu.
In file processing, input refers to the flow of data into a program and output means the flow of data out
of a program. Input to a program may come from the keyboard, the mouse, the memory, the disk or another
program. Similarly, output from a program may go to the screen, the printer, the memory, the disk, a network,
or another program.
A stream in java is a path along which data flows (like a river or pipe along which water flows).
It has a source and destination.
Stream Classes:
The java.io package contains a large number of stream classes that provide capabilities for processing
all types of data. These classes may be categorized into two groups based on the data type
1. Byte stream classes that provide support for handling I/O operations on byte
2. Character stream classes that provide support for managing I/O operation on character.
Byte stream classes have been designed to provide functional features for creating and manipulating
stream and files for reading and writing bytes. Since the streams are unidirectional, they can transmit bytes in
one direction. So java provides two kinds of byte stream class: input stream and output stream.
The input stream class defines methods for performing input functions such as
Prof: Padmini. R Dept: BCA Programming in JAVA
Reading bytes
Closing Streams
Making position in stream
Finding the number of bytes in a stream
Methods Description
The output stream includes methods that are designed to perform the following task.
Writing bytes
Closing
Flushing stream
Method Description
write(byte b[]) Write all bytes in the array b to the output stream
write(byte b[], int n, int m) Writes m bytes from array b starting from nth byte
Character streams can be used to read and write 16-bit Unicode characters. There are two kinds of
character stream classes, namely reader stream classes and writer stream classes.
Reader stream classes are designed to read character from the files. Reader class is the base class for all
other classes in this group.
Prof: Padmini. R Dept: BCA Programming in JAVA
The reader class contains methods that are identical to those available in the inputstream class, except
reader is designed to handle character.
Like output stream classes, the writer stream classes are designed to perform all output operations on
files. Only difference is that while output stream classes are designed to write bytes, the writer stream classes
are designed to write characters.
Applet programming:
Applets are small java programs that are primarily used in internet computing. It can perform
arithmetic operations, displaying graphics, and play sound.
Difference between applet and application
1. Applet do not use main() method for initiating the execution.
2. Applet can’t be run independently, without the help of <applet> HTML tag.
3. Applet can’t read from or a write to the files in the local computer.
4. Applet cannot run any program from the local computer.
5. Applets are restricted from using libraries from other languages such as C and C++.
Applet life cycle:
Every java applet inherits a set of default behaviors from the Applet class.The applet states include:
• New born state
• Running state
• Idle state
• Dead or destroyed state
New born state:
Applet enters into the initialization state when it is first loaded. This is achieved by calling init()
method of Applet class.
Running state: Applet enters the running state when the system calls the start() method of Applet
class.This occurs automatically after the applet is initialized. Starting can also occur if the applet is already in
‘stopped’ (idle) state.
Idle or stopped state:
An applet becomes idle when it is stopped from running.We can do this by calling stop() method
explicitly.
Prof: Padmini. R Dept: BCA Programming in JAVA
Dead state
An applet is said to be dead when it is removed from memory.This occurs automatically by invoking
the destroy() method when we quit the browser.
When an applet begins, the following method are called, in this sequence
init()
start()
paint()
stop()
destroy()
Graphics programming:
One of the most important features of java is its ability to draw graphics. We can write java applet that
draw lines, figures of different shapes, images and text in different fonts and styles.
Java’s Graphics class includes methods for drawing many different types of shapes, from simple line to
polygon and text in a variety of fonts. This class provides the following methods.
Method Description
drawArc() Draws a hollow arc
drawLine() Draws straight line.
drawOval() Draws a hollow oval
drawPolygon() Draws a hollow polygon
drawRect() Draws a hollow Rectangle
drawRoundRect() Draws a hollow Rounded Rectangle
Prof: Padmini. R Dept: BCA Programming in JAVA
Drawing Lines
Lines are drawn by means of the drawLine( ) method, shown here:
void drawLine(int startX, int startY, int endX, int endY)
drawLine( ) displays a line in the current drawing color that begins at startX, startY and
ends at endX, endY.
Drawing Rectangles
The drawRect( ) and fillRect( ) methods display an outlined and filled rectangle, respectively. They are
shown here:
void drawRect(int left, int top, int width, int height)
void fillRect(int left, int top, int width, int height)
The upper-left corner of the rectangle is at top and left. The dimensions of the rectangle are specified by
width and height.
To draw a rounded rectangle, use drawRoundRect( ) or fillRoundRect( ), both shown here:
void drawRoundRect(int left, int top, int width, int height,int xDiam, int yDiam)
void fillRoundRect(int left, int top, int width, int height,int xDiam, int yDiam)
A rounded rectangle has rounded corners. The upper-left corner of the rectangle is at top,left. The
dimensions of the rectangle are specified by width and height. The diameter of the rounding arc along the X
axis is specified by xDiam. The diameter of the rounding arc along the Y axis is specified by yDiam.
Drawing Arcs
Arcs can be drawn with drawArc( ) and fillArc(), shown here:
void drawArc(int left, int top, int width, int height, int startAngle,int sweepAngle)
void fillArc(int left, int top, int width, int height, int startAngle,int sweepAngle)
The arc is bounded by the rectangle whose upper-left corner is specified by top, left and whose width
and height are specified by width and height. The arc is drawn from startAngle through the angular distance
specified by sweepAngle. Angles are specified in degrees.
Drawing Polygons
It is possible to draw arbitrarily shaped figures using drawPolygon( ) and fillPolygon( ), shown here:
void drawPolygon(int x[ ], int y[ ], intnumPoints)
void fillPolygon(int x[ ], int y[ ], intnumPoints)
The polygon’s endpoints are specified by the coordinate pairs contained within the x and y arrays. The
number of points defined by x and y is specified by numPoints. There are alternative forms of these methods in
which the polygon is specified by a Polygon object. The following applet draws an hourglass shape :
Prof: Padmini. R Dept: BCA Programming in JAVA
// Draw Polygon
Import java.awt.*;
Import java.applet.*;
/*
<applet code="HourGlass" width=230 height=210>
</applet>
*/
public class HourGlass extends Applet {
public void paint(Graphics g) {
int xpoints[] = {30, 200, 30, 200, 30};
int ypoints[] = {30, 30, 200, 200, 30};
int num = 5;
g.drawPolygon(xpoints, ypoints, num);
}
}
Sample output from this program is shown here:
g.drawOval (57,75,39,20);
g.drawOval (110,75,30,20);
g.fillOval (68,81,10,10);
g.fillOval(121,81,10,10);
g.fillOval(85,100,30,30);
g.fillArc(60,125,80,40,180,180);
g.drawOval(25,92,15,30);
g.drawOval(160,92,15,30);
}
}
Frame encapsulates what is commonly thought of as a “window”. It is a subclass of Window and has a
title bar, menu bar, borders, and resizing corners.
Working with Frame windows:
We can use Frame to create a child window within applet. Here are two of Frame’s constructors:
Frame()
Frame(String title)
The first form creates a standard window that does not contain a title. The second form creates a window with
the title specified by title.
Setting the Windows Dimensions:
The setSize() method is used to set the dimensions of the window. Its signature is shown here:
voidsetSize(intnewWidth, intnewHeight)
voidsetSize(Dimension newsize)
the new size of the window is specified by newWidth and newHeight, or by the width and height fields of the
Dimension object passed in newsize.
Hiding and Showing a Window:
After a frame window has been created, it will not be visible until you call setVisible(). Its signature is
shown here:
voidsetVisible(Boolean visibleFlag)
The window is visible if the argument to this method is true. Otherwise, it is hidden.
Setting a Window’s Title:
We can change the title in a Frame window using setTitle(), which has this general form:
voidsetTitle(String newTitle)
Here newTitle is the title for the window.
Closing a Frame Window:
When using a frame window, your program must remove that window from the screen when it is
closed, by calling setVisible(false). To intercept(capture) window-close event, you must implement the
windowClosing() method of the WindowListenerinterface.
Working with Colors:
Java supports color in a portable, device-independent fashion. The AWT color system allows you to
specify any color you want. The most commonly used forms are shown here:
Color(int red, int green, int blue)
Color(int rgbValue)
Color(float red, float green, float blue)
The first constructor takes three integers that specify the color as a mix of red, greenand blue. These
values must be between 0 and 255, as in this example:
new Color(255, 100, 100); // light red.
The second color constructor takes a single integer that contains the mix of red, green and blue packed
into an integer. The integer is organized with red in bits 16 to 23,green in bits 8 to 15, and blue in bits 0 to 7.
Here is an example of this constructor:
Color darkRed = new Color (newRed);
The final constructor, Color (float, float, float), takes three float values (between 0.0
and 1.0) that specify the relative mix of red, green, and blue.
Once you have created a color, you can use it to set the foreground and/or background color by using
the setForeground( ) and setBackground( ) methods
Prof: Padmini. R Dept: BCA Programming in JAVA
The AWT supports multiple type fonts. The AWT provides flexibility by abstracting font-manipulation
operations and allowing for dynamic selection of fonts.
Fonts have a family name, a logical font name, and a face name. The family name is the general name of
the font, such as Courier. The logical name specifies a category of font, such as Monospaced. The face name
specifies a specific font, such as Courier Italic.
Fonts are encapsulated by the Font class. Several of the methods defined by Font are listed here
static Font decode(String str) -> Returns a font given its name.
boolean equals(Object FontObj) -> Returns true if the invoking object containsthe same font as that
specified by FontObj.Otherwise, it returns false.
String getFamily( ) ->Returns the name of the font family towhich the invoking font belongs.
static Font getFont(String property) ->Returns the font associated with the system property specified by
property. Null is returned if property does not exist.
static Font getFont(String property, Font defaultFont) ->Returns the font associated with the system
property specified by property. The font specified by defaultFont is returned if property does not exist.
String getName( ) ->Returns the logical name of the invoking font.int getSize( ) Returns the size, in
points, of the invoking font.
int hashCode( ) ->Returns the hash code associated with the invoking object.
boolean isBold( ) ->Returns true if the font includes the BOLDstyle value. Otherwise, false is returned.
boolean isItalic( ) ->Returns true if the font includes the ITALICstyle value. Otherwise, false is
returned.
boolean isPlain( ) ->Returns true if the font includes the PLAINstyle value. Otherwise, false is returned.
To select a new font, you must first construct a Font object that describes that font. We can construct a new font
using the following constructor,
Here, fontName specifies the name of the desired font. The name can be specified using either the logical or
face name.
The style of the font is specified by fontStyle. It may consist of one or more of these three constants:
Font.PLAIN, Font.BOLD, and Font.ITALIC. To combine these styles, we can use | (OR operator). For
example, Font.BOLD | Font.ITALIC specifies a bold, italics style. The size, in points, of the font is specified
by pointSize.
Prof: Padmini. R Dept: BCA Programming in JAVA
To use a font that you have created, you must select it by using the method setFont( ). The signature is
given below.
AWT Classes:
Class Description
The border layout manager. Border layouts use five components: North, South, East,
BorderLayout
West and Center.
FlowLayout The flow layout manager. Flow layout positions components left to right, top to bottom.
Frame Creates a standard window that has a title bar, resize corners and menu bar.
GridLayout The Grid layout manager. Grid layout displays components in a two-dimensional grid.
Panel Creates a standard window that doesn’t have title bar, resize corners, and menu bar.
We can create radio buttons using the final constructor with group name. The group name must be
same among the multiple radio buttons if they are in the same group.
We can retrieve the current state of the check box, call getState(). To set its state, call
setState(). You can obtain the label call getLabel() function and also we can set the label by callingsetLabel().
Example
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
add(BCA);
add(BSC);
add(BCOM);
add(BBA);
BCA.addItemListener(this);
BSC.addItemListener(this);
BCOM.addItemListener(this);
BBA.addItemListener(this);
}
4. List:
The choice list provides multiple options to the user, and the user can select either one or more than one
choice in the list.
List()
List(intnumrows)
List(intnumrows, Boolean multipleSelect)
The first constructor defines list box. The second constructor defines a list box with height of the list.
The final constructor defines the list box with multiple select option. If the multipleselect argument is true then
the user can select more than one option from the list.
add() method is used to add an Item in the list. The list that allow only single selection, you can
determine which item is selected by calling getSelectedItem() or getSelectedIndex(). For multiple selection,
you must use either getSelectedItems() or getSelectedIndexes().
5. TextField:
It provides the single-line text entry area, usually called an edit control.
TextField()
TextField(int numcharsize)
TextField(stgring str)
Prof: Padmini. R Dept: BCA Programming in JAVA
TextField(Str,numcharsize)
The first constructor defines a text box with default width. The second constructor defines a textbox
with the width attribute. By using this attribute we can set the width of the textbox. The next constructor
defines a textbox with default text. We can set the default text for a textbox using Str attribute. The final
constructor set the default text and width of the text box.
We can get the content currently hold by the text field by getText() and can set call setText().
6. TextArea:
Sometimes single line of text input is not enough for a given task. To handle these situations, AWT
provides TextArea.
TextArea()
TextArea(int numlines,int numcharsize)
TextArea(str)
TextArea(str, int numlines,int numcharsize)
The first constructor defines a multiline text box. The second constructor defines a multi-line textbox
with specified height and width. We can set the height of the textarea by numlines attribute and width of the
textarea by numcharsize attribute. The third constructor defines a textarea with default text. The final
constructor defines a textarea with default text and specified height and width.
7. Choice:
The choice list provides multiple options to the user, and the user can select only one option from the
list. Simply it defines the window’s combo box control.
add() method is used to add an Item in the list. The list that allow only single selection, you can
determine which item is selected by calling getSelectedItem() or getSelectedIndex().
Example
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
//<applet code=choice width=300 height=180></applet>
public class choice extends Applet implements ItemListener
{
Choice dept;
String msg = "";
public void init()
{
dept = new Choice();
dept.add("BCA");
dept.add("BSC");
Prof: Padmini. R Dept: BCA Programming in JAVA
dept.add("BCOM");
dept.add("BBA");
add(dept);
dept.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
msg = "Current Department: ";
msg += dept.getSelectedItem();
g.drawString(msg, 6, 120);
}
}
Output
Layout Managers:
Layout managers are used to automatically arrange your controls within a window by using some type
of algorithm. We can set the manager by the setLayout() method.
Types of Layout:
• FlowLayout()
• BorderLayout()
• GridLayout()
• CardLayout()
1. FlowLayout:
Prof: Padmini. R Dept: BCA Programming in JAVA
It is the default layout manager. Components are arranged from upper-left corner, left to right and top
to bottom.
FlowLayout()
FlowLayout(align)
FlowLayout(align,inthor,intver)
2. BorderLayout:
It has four narrow, fixed width components at the edges and one large area in the center. The
four sides are referred to as north, south, east and west.
BorderLayout()
BorderLayout(inthor,intver)
BorderLayout.CENTER BorderLayout.SOUTH
BorderLayout.EAST BorderLayout.WEST
BorderLayout.NORTH
3. Grid Layout:
In GridLayout components are arranged in two dimensional grids. When you instantiate a
GridLayout, you define the number of rows and columns. The constructors supported by GridLayout are shown
here:
GridLayout( )
GridLayout(intnumRows, intnumColumns )
Here horz and vert arguments specifies the horizontal and vertical space between components.
Note: Specifying numRows as zero allows for unlimited-length columns. Specifying numColumns as zero
allows forunlimited-length rows.
Prof: Padmini. R Dept: BCA Programming in JAVA
4. Card Layout:
The CardLayout class is unique among the other layout managers in that it stores several different
layouts.
CardLayout( )
CardLayout(inthorz, intvert)
Once you have created a menu item, you must add the item to a Menu object by using add( ), which has
the following general form:
MenuItemadd(MenuItem item)
Here, item is the item being added. Items are added to a menu in the order in which the calls to add( )
take place.
Once you have added all items to a Menu object, you can add that object to the menu bar by using this
version of add( ) defined byMenuBar
MenuBar.add(Menu menu)
Here, menu is the menu being added.
Menus only generate events when an item of type MenuItem or CheckboxMenuItem is selected. Each
time a menu item is selected, an ActionEvent object is generated. Each time a check box menu item is checked
or unchecked, an ItemEvent object is generated. Thus, you must implement the ActionListener and
ItemListener interfaces in order to handle these menu events. The getItem() method of ItemEvent returns a
reference to the item that generated this event. The general form of this method is shown here:
Object getItem( )
Following is an example that adds a series of nested menus to a pop-up window. The item selected is
displayed in the window. The state of the two check box menu items is also displayed.