SlideShare une entreprise Scribd logo
1  sur  82
Télécharger pour lire hors ligne
CORE JAVA
SYBSC-CS
SEM 3
302 PARANJPE UDYOG BHAVAN, NEAR KHANDELWAL SWEETS, NEAR THANE
STATION , THANE (WEST)
PHONE NO: 8097071144 / 8097071155
INDEX
SYLLABUS PAGE NO
Unit I The Java Language: Features of Java, Java programming format, Java Tokens,
Java Statements, Java Data Types, Typecasting, Arrays
OOPS: Introduction, Class, Object, Static Keywords, Constructors, this Key
Word, Inheritance, super Key Word, Polymorphism (overloading and overriding),
Abstraction, Encapsulation, Abstract Classes, Interfaces
String Manipulations: String, String Buffer, String Tokenizer
Packages: Introduction to predefined packages (java.lang, java.util, java.io,
java.sql, java.swing), User Defined Packages, Access specifiers
1
Unit II Exception Handling: Introduction, Pre-Defined Exceptions, Try-Catch-Finally,
Throws, throw, User Defined Exception examples
Multithreading: Thread Creations, Thread Life Cycle, Life Cycle Methods,
Synchronization, Wait() notify() notify all() methods
I/O Streams: Introduction, Byte-oriented streams, Character- oriented streams,
File, Random access File, Serialization
Networking: Introduction, Socket, Server socket, Client –Server Communication
27
Unit III Wrapper Classes: Introduction, Byte, Short, Integer, Long, Float, Double,
Character, Boolean classes
Collection Framework: Introduction, util Package interfaces, List, Set, Map, List
interface & its classes, Set interface & its classes, Map interface & its classes
Inner Classes: Introduction, Member inner class, Static inner class, Local inner
class, Anonymous inner class
AWT: Introduction, Components, Event-Delegation-Model, Listeners, Layouts,
Individual components Label, Button, CheckBox, Radio Button, Choice, List,
Menu, Text Field, Text Area
60
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
1
UNIT 1
features of Java.
Platform Independent
The concept of Write-once-run-anywhere (known as the Platform independent) is one of the important
key feature of java language that makes java as the most powerful language. Not even a single language
is idle to this feature but java is more closer to this feature. The programs written on one platform can
run on any platform provided the platform must have the JVM.
Simple
There are various features that makes the java as a simple language. Programs are easy to write and
debug because java does not use the pointers explicitly. Java provides the bug free system due to the
strong memory management. It also has the automatic memory allocation and deallocation system.
Object Oriented To be an Object Oriented language, any language must follow at least the four
characteristics.
 Inheritance : It is the process of creating the new classes and using the behavior of the
existing classes by extending them just to reuse the existing code and adding the
additional features as needed.
 Encapsulation: It is the mechanism of combining the information and providing the
abstraction.
 Polymorphism: As the name suggest one name multiple form, Polymorphism is the way
of providing the different functionality by the functions having the same name based on
the signatures of the methods.
 Dynamic binding : Sometimes we don't have the knowledge of objects about their
specific types while writing our code. It is the way of providing the maximum
functionality to a program about the specific type at runtime.
 Robust Java has the strong memory allocation and automatic garbage collection
mechanism. It provides the powerful exception handling and type checking mechanism
as compare to other programming languages. Compiler checks the program whether
there any error and interpreter checks any run time error and makes the system secure
from crash. All of the above features makes the java language robust.
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
2
 Distributed The widely used protocols like HTTP and FTP are developed in java.
Internet programmers can call functions on these protocols and can get access the files
from any remote machine on the internet rather than writing codes on their local system.
 Portable The feature Write-once-run-anywhere makes the java language portable
provided that the system must have interpreter for the JVM. Java also have the standard
data size irrespective of operating system or the processor. These features makes the java
as a portable language.
 Dynamic While executing the java program the user can get the required files
dynamically from a local drive or from a computer thousands of miles away from the
user just by connecting with the Internet.
 Secure Java does not use memory pointers explicitly. All the programs in java are run
under an area known as the sand box. Security manager determines the accessibility
options of a class like reading and writing a file to the local disk. Java uses the public key
encryption system to allow the java applications to transmit over the internet in the
secure encrypted form. The bytecode Verifier checks the classes after loading.
 Performance Java uses native code usage, and lightweight process called threads. In the
beginning interpretation of bytecode resulted the performance slow but the advance
version of JVM uses the adaptive and just in time compilation technique that improves
the performance.
 Multithreaded As we all know several features of Java like Secure, Robust, Portable,
dynamic etc; you will be more delighted to know another feature of Java which is
Multithreaded. Java is also a Multithreaded programming language. Multithreading
means a single program having different threads executing independently at the same
time. Multiple threads execute instructions according to the program code in a process
or a program. Multithreading works the similar way as multiple processes run on one
computer. Multithreading programming is a very interesting concept in Java. In
multithreaded programs not even a single thread disturbs the execution of other thread.
Threads are obtained from the pool of available ready to run threads and they run on
the system CPUs. This is how Multithreading works in Java which you will soon come
to know in details in later chapters.
 Interpreted We all know that Java is an interpreted language as well. With an
interpreted language such as Java, programs run directly from the source code. The
interpreter program reads the source code and translates it on the fly into computations.
Thus, Java as an interpreted language depends on an interpreter program. The
versatility of being platform independent makes Java to outshine from other languages.
The source code to be written and distributed is platform independent. Another
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
3
advantage of Java as an interpreted language is its error debugging quality. Due to this
any error occurring in the program gets traced. This is how it is different to work with
Java.
 Architecture Neutral The term architectural neutral seems to be weird, but yes Java is an
architectural neutral language as well. The growing popularity of networks makes
developers think distributed. In the world of network it is essential that the applications
must be able to migrate easily to different computer systems. Not only to computer
systems but to a wide variety of hardware architecture and Operating system
architectures as well. The Java compiler does this by generating byte code instructions,
to be easily interpreted on any machine and to be easily translated into native machine
code on the fly. The compiler generates an architecture-neutral object file format to
enable a Java application to execute anywhere on the network and then the compiled
code is executed on many processors, given the presence of the Java runtime system.
Hence Java was designed to support applications on network. This feature of Java has
thrived the programming language.
short note on JVM
Java’s Magic: The Bytecode The key that allows Java to solve both the security and the
portability problems just described is that the output of a Java compiler is not executable code.
Rather, it is bytecode.
 Bytecode is a highly optimized set of instructions designed to be executed by the Java
run-time system, which is called the Java Virtual Machine (JVM). That is, in its standard
form, the JVM is an interpreter for bytecode. This may come as a bit of a surprise. As you
know, C++ is compiled to executable code. In fact, most modern languages are designed
to be compiled, not interpreted—mostly because of performance concerns. However, the
fact that a Java program is executed by the JVM helps solve the major problems
associated with downloading programs over the internet.
 Translating a Java program into bytecode helps makes it much easier to run a program
in a wide variety of environments. The reason is straightforward: only the JVM needs to
be implemented for each platform. Once the run-time package exists for a given system,
any Java program can run on it. Remember, although the details of the JVM will differ
from platform to platform, all interpret the same Java bytecode. If a Java program were
compiled to native code, then different versions of the same program would have to
exist for each type of CPU connected to the Internet. This is, of course, not a feasible
solution. Thus, the interpretation of bytecode is the easiest way to create truly portable
programs. The fact that a Java program is interpreted also helps to make it secure.
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
4
Because the execution of every Java program is under the control of the JVM, the JVM
can contain the program and prevent it from generating side effects outside of the
system. As you will see, safety is also enhanced by certain restrictions that exist in the
Java language. When a program is interpreted, it generally runs substantially slower
than it would run if compiled to executable code. However, with Java, the differential
between the two is not so great. The use of bytecode enables the Java run-time system to
execute programs much faster than you might expect.
Format of a Java program
In Java, a class definition starts with the word "class" (possibly preceded by the word "public" or
"private"), continues with the name of the class and the character "{" (a left brace or curly
bracket), and ends with the character "}" (a right brace). Inside the braces are definitions of
methods and variables.
A method definition similarly starts with naming information followed by a pair of braces that
include the statements of the method. The braces act in this way like parentheses in Scheme.
Braces appear inside methods as well, to group statements (again in the same way that
statements in a Scheme procedure body are grouped with parentheses). Statements within such
a group are separated with semicolons. Here's an example of a "Hello world" program in Java
(traditionally, the simplest program in a given language):
class SimpleGreeter {
public static void main (String [ ] arguments) {
System.out.print ("hello ");
System.out.println ("world");
}
}
At least one of the classes in a Java program must contain a method named main;
a main method is what's called by the operating system to run the program.
Java Tokens
Java Tokens:- A java Program is made up of Classes and Methods and in the Methods are the
Container of the various Statements And a Statement is made up of Variables, Constants,
operators etc .
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
5
Tokens are the various Java program elements which are identified by the compiler. A token is
the smallest element of a program that is meaningful to the compiler. Tokens supported in Java
include keywords, variables, constants, special characters, operations etc.
Tokens are the smallest unit of Program There is Five Types of Tokens
1. Reserve Word or Keywords
2. Identifier
3. Literals
4. Operators
5. Separators
java statements
1. Control Statement
a. Conditional execution
i. If Statement
ii. If – Else statement
iii. If- Else-if statement
iv. Switch Statement
b. Looping
i. For Loop
ii. While Loop
iii. Do – While Loop
c. Flow Control Statement
i. Return Statement
ii. Continue Statement
iii. Break Statement
2. Assignment Statement
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
6
An assignment statement in Java uses the assignment operator (=) to assign the
result of an expression to a variable
Variables
Variables are locations in memory in which values can be stored. Each one has a name, a type,
and a value.
Before we can use a variable, we have to declare it. After it is declared, we can then assign
values to it.
Java actually has three kinds of variables:
1. instance variables,
2. class variables,
3. And local variables.
Instance variables, are used to define the attributes of a particular object.
Class variables, are similar to instance variables, except their values apply to all that class's
instances (and to the class itself) rather than having different values for each object.
Local variables, are declared and used inside method definitions,
Although all three kinds of variables are declared in much the same ways, class and instance
variables are accessed and assigned in slightly different ways from local variables.
Java does not have global variables-that is, variables that are global to all parts of a program.
Instance and class variables can be used to communicate global information between and
among objects.
Declaring Variables
To use any variable in a Java program, we must first declare it. Variable declarations consist of a
type and a variable name:
int myAge;
String myName;
boolean isTired;
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
7
Variable definitions can go anywhere in a method definition (that is, anywhere a regular Java
statement can go), although they are most commonly declared at the beginning of the definition
before they are used:
public static void main (String args[]) {
int count;
String title;
boolean isAsleep;
...
}
We can string together variable names with the same type on one line:
int x, y, z;
String firstName, LastName;
We can also give each variable an initial value when we declare it:
int myAge, mySize, numShoes = 28;
String myName = "eBIZ";
boolean isTired = true;
int a = 4, b = 5, c = 6;
If there are multiple variables on the same line with only one initializer the initial value applies to only
the last variable in a declaration.
We can also group individual variables and initializers on the same line using commas, as with the last
example.
Rules on Variable Names
Variable names in Java can start with a letter, an underscore (_), or a dollar sign ($). They cannot
start with a number. After the first character, our variable names can include any letter or
number. Symbols, such as %, *, @, and so on, are often reserved for operators in Java, so we
should be careful when using symbols in variable names. The Java language uses the Unicode
character set. The Java language is case sensitive, which means that uppercase letters are
different from lowercase letters. This means that the variable X is different from the variable x,
and a rose is not a Rose is not a ROSE.
Variable Types
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
8
In addition to the variable name, each variable declaration must have a type, which defines
what values that variable can hold. The variable type can be one of three things:
• One of the eight primitive data types
• The name of a class or interface
• An array
Primitive Data Types
The eight primitive data types handle common types for integers, floating-point numbers,
characters, and boolean values (true or false).
They're called primitive because they're built into the system and are not actual objects, which
makes them more efficient to use.
Integer Type
There are four Java integer types, each with a different range of values. All are signed, which means they
can hold either positive or negative numbers.
Type Size Range
byte 8 bits -128 to 127
short 16 bits -32,768 to 32,767
int 32 bits -2,147,483,648 to 2,147,483,647
long 64 bits
-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
Data Type Default Value (for fields)
float 0.0f
double 0.0d
char 'u0000'
String (or any object) Null
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
9
Floating-point type:
Floating-point numbers are used for numbers with a decimal part. There are two floating-point
types: float (32 bits, single precision) and double (64 bits, double precision).
Char type:
The char type is used for individual characters. Because Java uses the Unicode character set, the
char type has 16 bits of precision, unsigned.
Constants
 Are similar to variables but, once initialized, their contents may NOT be changed?
 Are declared with the keyword final?
 By convention, have all capital letters in their identifier. This makes them easier to see
within the code.
This program defines a number of constants and then displays some of their values.
public class App
{
public static void main(String[] args)
{
final boolean YES = true;
final char DEPOSIT_CODE = 'D';
final byte INCHES_PER_FOOT = 12;
final int FEET_PER_MILE = 5280;
final float PI = 3.14F;
final double SALES_TAX_RATE = .06;
final String ADDRESS = "119 South Street";
// Display some of the values
System.out.println(INCHES_PER_FOOT);
System.out.println(ADDRESS);
}
}
TYPE CASTING
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
10
Type Casting refers to changing an entity of one datatype into another. This is important for the
type conversion in developing any application. If you will store a int value into a byte variable
directly, this will be illegal operation. For storing your calculated int value in a byte variable
you will have to change the type of resultant data which has to be stored.
Type Conversion and Casting
it is fairly common to assign a value of one type to a variable of another type. If the two types
are compatible, then Java will perform the conversion automatically. For example, it is always
possible to assign an int value to a long variable.
not all types are compatible, and thus, not all type conversions are implicitly allowed. For
instance, there is no conversion defined from double to byte.
it is still possible to obtain a conversion between incompatible types. To do so, you must use a
cast, which performs an explicit conversion between incompatible types.
Java’s Automatic Conversions
When one type of data is assigned to another type of variable, an automatic type conversion will
take place if the following two conditions are met:
■ The two types are compatible.
■ The destination type is larger than the source type.
int type is always large enough to hold all valid byte values, so no explicit cast statement is
required. the numeric types, including integer and floating-point types, are compatible with
each other. However, the numeric types are not compatible with char or boolean. Also, char
and boolean are not compatible with each other.
Casting Incompatible Types
what if you want to assign an int value to a byte variable? This conversion will not be
performed automatically, because a byte is smaller than an int. This kind of conversion is
sometimes called a narrowing conversion, since you are explicitly making the value narrower so
that it will fit into the target type.
To create a conversion between two incompatible types, you must use a cast. A cast is simply an
explicit type conversion. It has this general form:
(target-type) value
int a;
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
11
byte b;
// ...
b = (byte) a;
A different type of conversion will occur when a floating-point value is assigned to an integer
type: truncation.
The Type Promotion Rules
In addition to the elevation of bytes and shorts to int, Java defines several type promotion rules
that apply to expressions. They are as follows. First, all byte and short values are promoted to
int, as just described. Then, if one operand is a long, the whole expression is promoted to long.
If one operand is a float, the entire expression is promoted to float. If any of the operands is
double, the result is double.
Arrays
Introduction
An array is a collection of items. Each slot in the array can hold an object or a primitive value.
Arrays in Java are objects that can be treated just like other objects in the language.
An array is an indexed table of like values. While they can exist in more than one dimension, we
are only interested in one-dimensional arrays as depicted by the following
This array consists of five elements where each is an integer value (217, 138, 92, 12, and 168).
To access a particular element within an array, its corresponding index (offset) is used. For
example, the integer value at index location 3 within this array is 12. Notice that the indexes are
zero based because the offset of the first element is always zero (you don't have to skip over any
other elements to get there).
While all programming languages include the ability to process arrays, Java provides enhanced
integrity and other features not found in other languages.
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
12
Java arrays
Java array require that all elements be of the same data type.
For example,
We may create an array of char values, or an array of float values, or an array of boolean values,
etc...
Java array are objects and must be declared like one.
The general syntax is as follows:
data-type[] identifier = new data-type[n];
or
data-type identifier[] = new data-type[n];
Where identifier is the array (object) reference and n is an integer expression that specifies how
many elements are in the array.
For example,
int[] myArray = new int[5];
Alternatively, a programmer may split the definition of the array reference and the instantiation
of the array into two statements as follows:
int[] myArray;
myArray = new int[5];
Using either technique, it is important to understand what is created.
The following diagram may help:
The array reference (myArray) can be thought of as pointing to the array whose elements reside
on the memory heap.
Notes:
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
13
 At the time an array reference is declared, it initially contains null (it doesn't point to
anything). It doesn't receive a value until an array is assigned to it.
 An array reference can only be assigned an array of the correct type. In the above
example, myArray is declared to be a reference to an int array, so only an array of int
values can ever be assigned to it. To attempt otherwise will result in a compile error.
 An array reference may be reused to point to a different array (of the appropriate type).
Like all objects, however, an array that can no longer be r eferenced will be garbage
collected.
 When instantiated, all array elements are automatically initialized to binary zeros. This
means all elements of numeric arrays will be zero, all elements of boolean arrays will
be false, and all elements of char arrays will be the null character.
Java array can be constructed from a value list.
This is an alternative construction technique as shown by
char[] chars = {'a', 'b', 'c'};
This creates a three element array of characters. The first element is initialized to 'a', the second
is initialized to 'b', and the third is initialized to 'c'.
Notes:
The number of elements in the array is determined by the number of values in the list and the
new keyword isn't coded.
When a value list is used, it can only be coded in the statement that declares the array
reference.
In other words, the following will not compile:
char[] chars;
chars = {'a', 'b', 'c'};
Java array permit an element to be accessed via its unique index.
For example,
int[] numbers = {12, 15, 3, 8};
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
14
The following expression will reference the third element (an int with a value of 3)
numbers[2]
The following program, ArrayDemo, creates an array of integers, puts some values in it, and
prints each value to standard output.
class ArrayDemo {
public static void main(String[] args) {
int[] anArray; // declares an array of integers
anArray = new int[3]; // allocates memory for 10 integers
anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // etc.
System.out.println("Element at index 0: " + anArray[0]);
System.out.println("Element at index 1: " + anArray[1]);
System.out.println("Element at index 2: " + anArray[2]);
}
}
oops
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a
methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation
CLASSES AND OBJECTS
A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
15
A class in Java can contain:
 fields
 methods
 constructors
 blocks
 nested class and interface
Object is the physical as well as logical entity whereas class is the logical entity only.
 An entity that has state and behavior is known as an object
An object has three characteristics:
1. state: represents data (value) of an object.
2. behavior: represents the behavior (functionality) of an object such as deposit, withdraw
etc.
3. identity: Object identity is typically implemented via a unique ID.
static keyword
The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the
class than instance of the class.
The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the
class than instance of the class.
Constructor
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides
data for the object that is why it is known as constructor.
Rules for creating java constructor
There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
Types of java constructors
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
16
There are two types of constructors:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
this keyword
There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to
the current object.
Here is given the 6 usage of java this keyword.
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.
Inheritance
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors
of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
parent class, and you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
17
In java programming, multiple and hybrid inheritance is supported through interface only
super keyword
The super keyword in java is a reference variable which is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
Usage of java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
polymorphism
Method Overloading
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
18
 If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
 If we have to perform only one operation, having same name of the methods increases
the readability of the program.
 Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two parameters, and
b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs.
Method Overriding
 If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in java.
 In other words, If subclass provides the specific implementation of the method that has
been provided by one of its parent class, it is known as method overriding.
No. Method Overloading Method Overriding
1) Method overloading is used to increase the
readability of the program.
Method overriding is used to
provide the specific
implementation of the method that is
already provided by its super class.
2) Method overloading is performed within class. Method overriding occurs in two
classes that have IS-A (inheritance)
relationship.
3) In case of method overloading, parameter must be
different.
In case of method
overriding, parameter must be same.
4) Method overloading is the example of compile
time polymorphism.
Method overriding is the example
of run time polymorphism.
5) In java, method overloading can't be performed
by changing return type of the method
only. Return type can be same or different in
method overloading. But you must have to
change the parameter.
Return type must be same or
covariant in method overriding.
Abstraction
 Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
19
 Another way, it shows only important things to the user and hides the internal details
for example sending sms, you just type the text and send the message. You don't know
the internal processing about the message delivery.
 Abstraction lets you focus on what the object does instead of how it does it.
Encapsulation
 Encapsulation in java is a process of wrapping code and data together into a single unit,
for example capsule i.e. mixed of several medicines.
 We can create a fully encapsulated class in java by making all the data members of the
class private. Now we can use setter and getter methods to set and get the data in it.
Abstract class
A class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.
abstract class A{}
abstract method
A method that is declared as abstract and does not have implementation is known as abstract
method.
abstract void printStatus();//no body and abstract
Interface
 An interface in java is a blueprint of a class. It has static constants and abstract methods.
 The interface in java is a mechanism to achieve abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve abstraction and
multiple inheritance in Java.
 Java Interface also represents IS-A relationship.
 It cannot be instantiated just like abstract class.
Abstract class Interface
1) Abstract class can have abstract and
non-abstractmethods.
Interface can have only abstract methods. Since Java
8, it can have default and static methods also.
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
20
2) Abstract class doesn't support
multiple inheritance.
Interface supports multiple inheritance.
3) Abstract class can have final, non-
final, static and non-static variables.
Interface has only static and final variables.
4) Abstract class can provide the
implementation of interface.
Interface can't provide the implementation of
abstract class.
5) The abstract keyword is used to
declare abstract class.
The interface keyword is used to declare interface.
6) Example:
public abstract class Shape{
public abstract void draw();
}
Example:
public interface Drawable{
void draw();
}
String manipulation
String
 In java, string is basically an object that represents sequence of char values. An array of
characters works same as java string.
 Java String class provides a lot of methods to perform operations on string such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring() etc.
 The java.lang.String class
implements Serializable, Comparable and CharSequence interfaces.
 Generally, string is a sequence of characters. But in java, string is an object that
represents a sequence of characters. The java.lang.String class is used to create string
object.
 The java String is immutable i.e. it cannot be changed. Whenever we change any string,
a new instance is created.
No. Method Description
1 char charAt(int index) returns char value for the
particular index
2 int length() returns string length
3 static String format(String format, Object... args) returns formatted string
4 static String format(Locale l, String format, Object...
args)
returns formatted string with given
locale
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
21
5 String substring(int beginIndex) returns substring for given begin
index
6 String substring(int beginIndex, int endIndex) returns substring for given begin
index and end index
7 boolean contains(CharSequence s) returns true or false after matching
the sequence of char value
8 static String join(CharSequence delimiter,
CharSequence... elements)
returns a joined string
9 static String join(CharSequence delimiter, Iterable<?
extends CharSequence> elements)
returns a joined string
10 boolean equals(Object another) checks the equality of string with
object
11 boolean isEmpty() checks if string is empty
12 String concat(String str) concatinates specified string
13 String replace(char old, char new) replaces all occurrences of specified
char value
14 String replace(CharSequence old, CharSequence
new)
replaces all occurrences of specified
CharSequence
15 static String equalsIgnoreCase(String another) compares another string. It doesn't
check case.
16 String[] split(String regex) returns splitted string matching
regex
17 String[] split(String regex, int limit) returns splitted string matching
regex and limit
18 String intern() returns interned string
19 int indexOf(int ch) returns specified char value index
20 int indexOf(int ch, int fromIndex) returns specified char value index
starting with given index
21 int indexOf(String substring) returns specified substring index
22 int indexOf(String substring, int fromIndex) returns specified substring index
starting with given index
23 String toLowerCase() returns string in lowercase.
24 String toLowerCase(Locale l) returns string in lowercase using
specified locale.
25 String toUpperCase() returns string in uppercase.
26 String toUpperCase(Locale l) returns string in uppercase using
specified locale.
27 String trim() removes beginning and ending
spaces of this string.
28 static String valueOf(int value) converts given type into string. It is
overloaded.
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
22
StringBuffer
Java StringBuffer class is used to created mutable (modifiable) string. The
StringBuffer class in java is same as String class except it is mutable i.e. it can be
changed.
Constructors of StringBuffer
1. StringBuffer(): creates an empty string buffer with the initial capacity of 16.
2. StringBuffer(String str): creates a string buffer with the specified string.
3. StringBuffer(int capacity): creates an empty string buffer with the specified capacity as
length.
Methods of StringBuffer
1. public synchronized StringBuffer append(String s): is used to append the specified
string with this string. The append() method is overloaded like append(char),
append(boolean), append(int), append(float), append(double) etc.
2. public synchronized StringBuffer insert(int offset, String s): is used to insert the
specified string with this string at the specified position. The insert() method is
overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float),
insert(int, double) etc.
3. public synchronized StringBuffer replace(int startIndex, int endIndex, String str): is
used to replace the string from specified startIndex and endIndex.
4. public synchronized StringBuffer delete(int startIndex, int endIndex): is used to delete
the string from specified startIndex and endIndex.
5. public synchronized StringBuffer reverse(): is used to reverse the string.
6. public int capacity(): is used to return the current capacity.
7. public void ensureCapacity(int minimumCapacity): is used to ensure the capacity at
least equal to the given minimum.
8. public char charAt(int index): is used to return the character at the specified position.
9. public int length(): is used to return the length of the string i.e. total number of
characters.
10. public String substring(int beginIndex): is used to return the substring from the
specified beginIndex.
11. public String substring(int beginIndex, int endIndex): is used to return the substring
from the specified beginIndex and endIndex.
StringTokenizer
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
23
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to
break string.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class.
Constructors of StringTokenizer
Constructor Description
StringTokenizer(String str) creates StringTokenizer with specified string.
StringTokenizer(String str,
String delim)
creates StringTokenizer with specified string and delimeter.
StringTokenizer(String str,
String delim, boolean
returnValue)
creates StringTokenizer with specified string, delimeter and
returnValue. If return value is true, delimiter characters are
considered to be tokens. If it is false, delimiter characters
serve to separate tokens.
Methods of StringTokenizer
Public method Description
boolean hasMoreTokens() checks if there is more tokens available.
String nextToken() returns the next token from the StringTokenizer object.
String nextToken(String delim) returns the next token based on the delimeter.
boolean hasMoreElements() same as hasMoreTokens() method.
Object nextElement() same as nextToken() but its return type is Object.
int countTokens() returns the total number of tokens.
Eg:
import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("this is weit"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
Op:
this
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
24
is
weit
Packages
java.lang
 The java.lang package contains classes that are fundamental to the design of the Java
language. The most important classes are Object, which is the root of the class hierarchy,
and Class, instances of which represent classes at run time.
 Frequently it is necessary to represent a value of primitive type as if it were an object.
The wrapper classes Boolean, Character, Integer, Long, Float, and Double serve this
purpose. An object of type Double, for example, contains a field whose type is double,
representing that value in such a way that a reference to it can be stored in a variable of
reference type. These classes also provide a number of methods for converting among
primitive values, as well as supporting such standard methods as equals and hashCode.
 The class Math provides commonly used mathematical functions such as sine, cosine,
and square root. The classes String and StringBuffer similarly provide commonly used
operations on character strings.
 Classes ClassLoader, Process, Runtime, SecurityManager, and System provide "system
operations" that manage the dynamic loading of classes, creation of external processes,
host environment inquiries such as the time of day, and enforcement of security policies.
java.util
 Java.util package contains the collections framework, legacy collection classes, event
model, date and time facilities, internationalization, and miscellaneous utility classes.
 This reference will take you through simple and practical methods available in java.util
package.
java.io
 Java I/O (Input and Output) is used to process the input and produce the output.
 Java uses the concept of stream to make I/O operation fast. The java.io package contains
all the classes required for input and output operations.
 We can perform file handling in java by Java I/O API.
java.sql
 This package provides the APIs for accessing and processing data which is stored in the
database especially relational database by using the java programming language. It
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
25
includes a framework where we different drivers can be installed dynamically to access
different databases especially relational databases.
javax.swing
 Swing is a GUI widget toolkit for Java. It is part of Oracle's Java Foundation
Classes (JFC) – an API for providing a graphical user interface (GUI) for Java programs.
 Swing was developed to provide a more sophisticated set of GUI components than the
earlier Abstract Window Toolkit (AWT). Swing provides a native look and feel that
emulates the look and feel of several platforms, and also supports a pluggable look and
feel that allows applications to have a look and feel unrelated to the underlying
platform. It has more powerful and flexible components than AWT. In addition to
familiar components such as buttons, check boxes and labels, Swing provides several
advanced components such as tabbed panel, scroll panes, trees, tables, and lists.
 Unlike AWT components, Swing components are not implemented by platform-specific
code. Instead, they are written entirely in Java and therefore are platform-independent.
The term "lightweight" is used to describe such an element.
User-defined-package
 Java package created by user to categorized classes and interface
//save as FirstProgram.java
package LearnJava;
public class FirstProgram{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package?
javac -d . FirstProgram.java
JAVA ACCESS SPECIFIERS
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
26
The access to classes, constructors, methods and fields are regulated using access modifiers i.e. a
class can control what information or data can be accessible by other classes. To take advantage
of encapsulation, you should minimize access whenever possible.
Java provides a number of access modifiers to help you set the level of access you want for
classes as well as the fields, methods and constructors in your classes. A member has package or
default accessibility when no accessibility modifier is specified.
Access Modifiers
1.private
2.protected
3.default
4. public
public access modifier
Fields, methods and constructors declared public (least restrictive) within a public class are
visible to any class in the Java program, whether these classes are in the same package or in
another package.
private access modifier
The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It also
cannot be used for fields and methods within an interface. Fields, methods or constructors
declared private are strictly controlled, which means they cannot be accesses by anywhere
outside the enclosing class. A standard design strategy is to make all fields private and provide
public getter methods for them.
protected access modifier
The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used
for fields and methods within an interface. Fields, methods and constructors declared protected
in a superclass can be accessed only by subclasses in other packages. Classes in the same
package can also access protected fields, methods and constructors as well, even if they are not
a subclass of the protected member’s class.
default access modifier
Java provides a default specifier which is used when no access modifier is present. Any class,
field, method or constructor that has no declared access modifier is accessible only by classes in
the same package. The default modifier is not used for fields and methods within an interface.
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
27
UNIT 2
Exception Handling
An exception (or exceptional event) is a problem that arises during the execution of a program.
When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
 A user has entered an invalid data.
 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications or the JVM has
run out of memory.
Exception Hierarchy
All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass called
Error which is derived from the Throwable class.
Errors are abnormal conditions that happen in case of severe failures, these are not handled by
the Java programs. Errors are generated to indicate errors generated by the runtime
environment. Example: JVM is out of memory. Normally, programs cannot recover from errors.
The Exception class has two main subclasses: IOException class and RuntimeException Class.
Exceptions Methods
Sr.No. Method & Description
1 public String getMessage()
Returns a detailed message about the exception that has occurred. This message is
initialized in the Throwable constructor.
2 public Throwable getCause()
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
28
Returns the cause of the exception as represented by a Throwable object.
3 public String toString()
Returns the name of the class concatenated with the result of getMessage().
4 public void printStackTrace()
Prints the result of toString() along with the stack trace to System.err, the error
output stream.
Catching Exceptions
A method catches an exception using a combination of the try and catch keywords. A try/catch
block is placed around the code that might generate an exception. Code within a try/catch block
is referred to as protected code, and the syntax for using try/catch looks like the following −
Syntax
try {
// Protected code
}catch(ExceptionName e1) {
// Catch block
}
The code which is prone to exceptions is placed in the try block. When an exception occurs, that
exception occurred is handled by catch block associated with it.
Multiple Catch Blocks
A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks
like the following −
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
29
try {
// Protected code
}catch(ExceptionType1 e1) {
// Catch block
}catch(ExceptionType2 e2) {
// Catch block
}catch(ExceptionType3 e3) {
// Catch block
}
The previous statements demonstrate three catch blocks, but you can have any number of them
after a single try. If an exception occurs in the protected code, the exception is thrown to the first
catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets
caught there. If not, the exception passes down to the second catch statement. This continues
until the exception either is caught or falls through all catches, in which case the current method
stops execution and the exception is thrown down to the previous method on the call stack.
try {
file = new FileInputStream(fileName);
x = (byte) file.read();
}catch(IOException i) {
i.printStackTrace();
return -1;
}catch(FileNotFoundException f) // Not valid! {
f.printStackTrace();
return -1;
}
The Finally Block
The finally block follows a try block or a catch block. A finally block of code always executes,
irrespective of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that you want to execute,
no matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax −
try {
// Protected code
}catch(ExceptionType1 e1) {
// Catch block
}catch(ExceptionType2 e2) {
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
30
// Catch block
}catch(ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}
The Throws/Throw Keywords
If a method does not handle a checked exception, the method must declare it using
the throws keyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just
caught, by using the throw keyword.
Try to understand the difference between throws and throw keywords, throws is used to
postpone the handling of a checked exception and throw is used to invoke an exception
explicitly.
Example
import java.io.*;
public class className {
public void deposit(double amount) throws RemoteException {
// Method implementation
throw new RemoteException();
}
// Remainder of class definition
}
User-defined Exceptions
You can create your own exceptions in Java. Keep the following points in mind when writing
your own exception classes −
All exceptions must be a child of Throwable.
If you want to write a checked exception that is automatically enforced by the Handle or
Declare Rule, you need to extend the Exception class.
If you want to write a runtime exception, you need to extend the RuntimeException class.
We can define our own Exception class as below −
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
31
class MyException extends Exception {
}
Example
class MyException extends Exception
{
public MyException(String message)
{
super(" - - - > "+message);
}
}
class Semi
{
public static void main(String[] args)
{
try
{
throw new MyException("hello");
}
catch(Exception x)
{
System.out.println(x);
}
}
}
Multithreading
Process
A process is an instance of a computer program that is executed sequentially. It is a collection of
instructions which are executed simultaneously at the rum time. Thus several processes may be
associated with the same program. For example, to check the spelling is a single process in the
Word Processor program and you can also use other processes like printing, formatting,
drawing, etc. associated with this program.
Multiprocessing
 Many task done simultaneously in PC.
 Program is a set of instruction and a “A process is a running instance of a program.
 In Multiprocessing OS implements CONTEXT SWITICHING mechanism.
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
32
 Here CPU is shared between different process:
E.g. A MS-Word application and MS-Excel application is opened simultaneously or in general
any two applications running simultaneously is multiprocessing.
Thread
 Thread is any part of the program under execution.
 A thread is an entity within a process .
 Example:in your java program main() is a thread and garbage collector is another thread.
 When more than one thread execute concurrently in a single application, it is termed as
“Multithreading”
 Thread can be created in either of the following ways:
1. Extending Thread class.
2. Implementing Runnable Interface.
1. Extending the java.lang.Thread Class
For creating a thread a class have to extend the Thread Class. For creating a thread by this
procedure you have to follow these steps:
1. Extend the java.lang.Thread Class.
2. Override the run( ) method in the subclass from the Thread class to define the code executed
by the thread.
3. Create an instance of this subclass. This subclass may call a Thread class constructor by
subclass constructor.
4. Invoke the start( ) method on the instance of the class to make the thread eligible for
running.
2. Implementing the java.lang.Runnable Interface
The procedure for creating threads by implementing the Runnable Interface is as follows:
1. A Class implements the Runnable Interface, override the run() method to define the code
executed by thread. An object of this class is Runnable Object.
2. Create an object of Thread Class by passing a Runnable object as argument.
3. Invoke the start( ) method on the instance of the Thread class.
A thread is a lightweight process which exist within a program and executed to perform a
special task. Several threads of execution may be associated with a single process. Thus a
process that has only one thread is referred to as a single-threaded process, while a process with
multiple threads is referred to as a multi-threaded process.
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
33
In Java Programming language, thread is a sequential path of code execution within a program.
Each thread has its own local variables, program counter and lifetime. In single threaded runtime
environment, operations are executes sequentially i.e. next operation can execute only when the
previous one is complete. It exists in a common memory space and can share both data and code
of a program. Threading concept is very important in Java through which we can increase the
speed of any application. You can see diagram shown below in which a thread is executed along
with its several operations with in a single process.
Main Thread
When any standalone application is running, it firstly execute the main() method runs in a one
thread, called the main thread. If no other threads are created by the main thread, then program
terminates when the main() method complete its execution. The main thread creates some other
threads called child threads. The main() method execution can finish, but the program will keep
running until the all threads have complete its execution.
WAP to demonstrate thread through Extending thread class.
class thread1
{
public static void main(String arg[])
{
mythread mt=new mythread();
for(int i=1;i<=5;i++)
{
System.out.println(i);
try
{
Thread.sleep(500);
}
catch(Exception e)
{}
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
34
}
}
}
class mythread extends Thread
{
mythread()
{
start();
}
public void run()
{
for(int i=11;i<=15;i++)
{
System.out.println(i);
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
}
}
}
}
Output:
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
35
WAP to demonstrate thread by implementing Runnable Interface.
class thread2
{
public static void main(String arg[])
{
mythread mt=new mythread();
for(int i=1;i<=5;i++)
{
System.out.println(i);
try
{
Thread.sleep(500);
}
catch(Exception e){}
}
}
}
class mythread implements Runnable
{
Thread t;
mythread()
{
t=new Thread(this);
t.start();
}
public void run()
{
for(int i=11;i<=15;i++)
{
System.out.println(i);
try
{
Thread.sleep(1000);
}
catch(Exception e){}
}
}
}
Output:
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
36
Constructor
Thread() Allocates a new Thread object.
Thread(Runnable target) Allocates a new Thread object.
Thread(Runnable target,String name) Allocates a new Thread object.
Thread(String name) Allocates a new Thread object.
Thread(ThreadGroup group,Runnable target) Allocates a new Thread object.
Thread(ThreadGroup group,Runnable target,
String name)
Allocates a new Thread object so that it has
target as its run object, has the specified name as
its name, and belongs to the thread group
referred to by group.
Thread(ThreadGroup group,Runnable target,
String name,long stackSize)
Allocates a new Thread object so that it has
target as its run object, has the specified name as
its name, belongs to the thread group referred to
by group, and has the specified stack size.
Thread(ThreadGroup group,String name) Allocates a new Thread object.
Multithreading :
Multithreading is a technique that allows a program or a process to execute many tasks
concurrently (at the same time and parallel). It allows a process to run its tasks in parallel mode
on a single processor system
In the multithreading concept, several multiple lightweight processes are run in a single
process/task or program by a single processor. For Example, When you use a word processor
you perform a many different tasks such as printing, spell checking and so on. Multithreaded
software treats each process as a separate program.
In Java, the Java Virtual Machine (JVM) allows an application to have multiple threads of
execution running concurrently. It allows a program to be more responsible to the user. When a
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
37
program contains multiple threads then the CPU can switch between the two threads to execute
them at the same time.
For example, look at the diagram shown as:
In this diagram, two threads are being executed having more than one task. The task of each
thread is switched to the task of another thread.
Advantages of multithreading over multitasking :
 Reduces the computation time.
 Improves performance of an application.
 Threads share the same address space so it saves the memory.
 Context switching between threads is usually less expensive than between processes.
 Cost of communication between threads is relatively low.
Life cycle of a thread
 When you are programming with threads, understanding the life cycle of thread is very
valuable.
 While a thread is alive, it is in one of several states.
 By invoking start() method, it doesn’t mean that the thread has access to CPU and start
executing straight away.
Several factors determine how it will proceed.
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
38
1. Born state
After the creations of Thread instance the thread is in this state but before the start() method
invocation. At this point, the thread is considered not alive.
2. Runnable (Ready-to-run) state
A thread start its life from Runnable state. A thread first enters runnable state after the invoking
of start() method but a thread can return to this state after either running, waiting, sleeping or
coming back from blocked state also.On this state a thread is waiting for a turn on the processor.
3. Running state
A thread is in running state that means the thread is currently executing.There are several ways
to enter in Runnable state but there is only one way to enter in Running state: the scheduler select
a thread from runnable pool.
4. Dead state
A thread can be considered dead when its run() method completes. If any thread comes on this
state that means it cannot ever run again.
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
39
5. Blocked, Suspended
A thread can enter in this state because of waiting the resources that are hold by another thread.
6. Sleeping
On this state, the thread is still alive but it is not runnable, it might be return to runnable state
later, if a particular event occurs. On this state a thread sleeps for a specified amount of time.
You can use the method sleep( ) to stop the running state of a thread.
7. Waiting
A thread waits for notification from another thread.The thread sends back to runnable state after
sending notification from another thread.
Some Important Methods defined in java.lang.Thread are shown in the table:
Method Return
Type
Description
currentThread() Thread Returns an object reference to the thread in which it
is invoked.
getName( ) String Retrieve the name of the thread object or instance.
start( ) Void Start the thread by calling its run method.
run( ) Void This method is the entry point to execute thread, like
the main method for applications.
sleep( ) Void Suspends a thread for a specified amount of time (in
milliseconds).
isAlive( ) boolean This method is used to determine the thread is
running or not.
activeCount( ) int This method returns the number of active threads in
a particular thread group and all its subgroups.
interrupt( ) void The method interrupt the threads on which it is
invoked.
yield( ) void By invoking this method the current thread pause its
execution temporarily and allow other threads to
execute.
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
40
join( ) void This method and join(long millisec) Throws
InterruptedException. These two methods are
invoked on a thread. These are not returned until
either the thread has completed or it is timed out
respectively.
Synchronization
 Sometimes, when two or more threads need shared resource, they need a proper
mechanism to ensure that the resource will be used by only one thread at a time.
 The mechanism we use to achieve this is known as thread synchronization.
 The thread synchronization is achieved through the synchronized keyword. The
statements which need to be synchronized should put into the synchronized block It is
also known as critical section.
WAP to demonstrate synchronization.
class sync
{
public static void main(String arg[])
{
share s=new share();
mythread mt1=new mythread(s);
mythread mt2=new mythread(s);
mythread mt3=new mythread(s);
}
}
class mythread extends Thread
{
share p;
mythread(share s)
{
p=s;
start();
}
public void run()
{
p.doword(Thread.currentThread().getName());
}
}
class share
{
public synchronized void doword(String str)
{
for(int i=1;i<=5;i++)
{
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
41
System.out.println(str);
try
{
Thread.sleep(500);
}
catch(Exception e){}
}
}
}
Output:
wait(), notify() and notifyAll()methods?
wait() : It tells the calling thread to give up the lock and go to sleep until some other thread
enters the same monitor and calls notify(). The wait() method releases the lock prior to
waiting and reacquires the lock prior to returning from the wait() method.
The wait() method is actually tightly integrated with the synchronization lock, using a feature
not available directly from the synchronization mechanism. In other words, it is not possible for
us to implement the wait() method purely in Java: it is a native method.
General syntax for calling wait() method is like this:
synchronized( lockObject )
{
while( ! condition )
{
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
42
lockObject.wait();
}
//take the action here;
}
notify() : It wakes up one single thread that called wait() on the same object. It should be
noted that calling notify() does not actually give up a lock on a resource. It tells a waiting
thread that that thread can wake up. However, the lock is not actually given up until the
notifier’s synchronized block has completed. So, if a notifier calls notify() on a resource but
the notifier still needs to perform 10 seconds of actions on the resource within its synchronized
block, the thread that had been waiting will need to wait at least another additional 10 seconds
for the notifier to release the lock on the object, even though notify() had been called.
General syntax for calling notify() method is like this:
synchronized(lockObject)
{
//establish_the_condition;
lockObject.notify();
//any additional code if needed
}
notifyAll() : It wakes up all the threads that called wait() on the same object. The highest
priority thread will run first in most of the situation, though not guaranteed. Other things are
same as notify() method above.
General syntax for calling notify() method is like this:
synchronized(lockObject)
{
establish_the_condition;
lockObject.notifyAll();
}
I/O streams
The java.io package contains nearly every class you might ever need to perform input and
output (I/O) in Java. All these streams represent an input source and an output destination. The
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
43
stream in the java.io package supports many data such as primitives, object, localized
characters, etc.
Stream
A stream can be defined as a sequence of data. There are two kinds of Streams −
InPutStream − The InputStream is used to read data from a source.
OutPutStream − The OutputStream is used for writing data to a destination.
Java provides strong but flexible support for I/O related to files and networks but this tutorial
covers very basic functionality related to streams and I/O. We will see the most commonly used
examples one by one −
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes
are, FileInputStream and FileOutputStream. Following is an example which makes use of
these two classes to copy an input file into an output file −
Example
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
44
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas
Java Character streams are used to perform input and output for 16-bit unicode. Though there
are many classes related to character streams but the most frequently used classes
are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.
We can re-write the above example, which makes the use of these two classes to copy an input
file (having unicode characters) into an output file −
Example
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
45
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
File Class
Java File class represents the files and directory pathnames in an abstract manner. This class is
used for creation of files and directories, file searching, file deletion, etc.
The File object represents the actual file/directory on the disk.
Following is the list of constructors to create a File object.
Sr.No. Method & Description
1 File(File parent, String child)
This constructor creates a new File instance from a parent abstract pathname and a
child pathname string.
2 File(String pathname)
This constructor creates a new File instance by converting the given pathname string
into an abstract pathname.
3 File(String parent, String child)
This constructor creates a new File instance from a parent pathname string and a
child pathname string.
4 File(URI uri)
This constructor creates a new File instance by converting the given file: URI into an
abstract pathname.
Once you have File object in hand, then there is a list of helper methods which can be used to
manipulate the files.
Sr.No. Method & Description
1 public String getName()
Returns the name of the file or directory denoted by this abstract pathname.
2 public String getParent()
Returns the pathname string of this abstract pathname's parent, or null if this
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
46
pathname does not name a parent directory.
3 public String getPath()
Converts this abstract pathname into a pathname string.
4 public String getAbsolutePath()
Returns the absolute pathname string of this abstract pathname.
5 public boolean isDirectory()
Tests whether the file denoted by this abstract pathname is a directory. Returns true if
and only if the file denoted by this abstract pathname exists and is a directory; false
otherwise.
Random file access
 Using a random access file, we can read from a file as well as write to the file.
 Reading and writing using the file input and output streams are a sequential process.
 Using a random access file, we can read or write at any position within the file.
 An object of the RandomAccessFile class can do the random file access. We can
read/write bytes and all primitive types values to a file.
 RandomAccessFile can work with strings using its readUTF() and writeUTF() methods.
 The RandomAccessFile class is not in the class hierarchy of the InputStream and
OutputStream classes.
Mode
A random access file can be created in four different access modes. The access mode value is a
string. They are listed as follows:
Mode Meaning
"r" The file is opened in a read-only mode.
"rw" The file is opened in a read-write mode. The file is created if it does not exist.
"rws" The file is opened in a read-write mode. Any modifications to the file's content and its
metadata are written to the storage device immediately.
"rwd" The file is opened in a read-write mode. Any modifications to the file's content are
written to the storage device immediately.
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
47
Read and Write
We create an instance of the RandomAccessFile class by specifying the file name and the access
mode.
RandomAccessFile raf = new RandomAccessFile("randomtest.txt", "rw");
 A random access file has a file pointer that moves forward when we read data from it or
write data to it.
 The file pointer is a cursor where our next read or write will start.
 Its value indicates the distance of the cursor from the beginning of the file in bytes.
 We can get the value of file pointer by using its getFilePointer() method.
 When we create an object of the RandomAccessFile class, the file pointer is set to zero.
 We can set the file pointer at a specific location in the file using the seek() method.
 The length() method of a RandomAccessFile returns the current length of the file. We
can extend or truncate a file by using its setLength() method.
Example
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class Main {
public static void main(String[] args) throws IOException {
String fileName = "randomaccessfile.txt";
File fileObject = new File(fileName);
if (!fileObject.exists()) {
initialWrite(fileName);
}
readFile(fileName);
readFile(fileName);
}
public static void readFile(String fileName) throws IOException {
RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
int counter = raf.readInt();
String msg = raf.readUTF();
System.out.println(counter);
System.out.println(msg);
incrementReadCounter(raf);
raf.close();
}
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
48
public static void incrementReadCounter(RandomAccessFile raf)
throws IOException {
long currentPosition = raf.getFilePointer();
raf.seek(0);
int counter = raf.readInt();
counter++;
raf.seek(0);
raf.writeInt(counter);
raf.seek(currentPosition);
}
public static void initialWrite(String fileName) throws IOException {
RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
raf.writeInt(0);
raf.writeUTF("Hello world!");
raf.close();
}
}
Serialization
Java provides a mechanism, called object serialization where an object can be represented as a
sequence of bytes that includes the object's data as well as information about the object's type
and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and deserialized
that is, the type information and bytes that represent the object and its data can be used to
recreate the object in memory.
Most impressive is that the entire process is JVM independent, meaning an object can be
serialized on one platform and deserialized on an entirely different platform.
Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the
methods for serializing and deserializing an object.
To demonstrate how serialization works in Java, I am going to use the stud class which
implements the Serializable interface −
import java.io.*;
public class NewClassSer
{
public static void main(String[] args) throws IOException,
ClassNotFoundException
{
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
49
try{
//write
stud std = new stud();
std.rollno = 10;
std.name = "siddhesh";
FileOutputStream fos = new FileOutputStream("s.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(std);
oos.close();
fos.close();
//----------------------------------------------------
//read
FileInputStream fis = new FileInputStream("s.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
stud std1 = (stud)ois.readObject();
ois.close();
fis.close();
System.out.println(std1.name + " -- "+ std1.rollno);
}
catch(Exception x)
{
x.printStackTrace();
}
}
}
class stud implements Serializable
{
public int rollno;
public String name;
}
Networking
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
50
 Computers running on the Internet communicate to each other using either the
Transmission Control Protocol (TCP) or the User Datagram Protocol (UDP).
 When you write Java programs that communicate over the network, you are
programming at the application layer.
 Typically, you don't need to concern yourself with the TCP and UDP layers. Instead, you
can use the classes in the java.net package.
 These classes provide system-independent network communication.
TCP
 TCP (Transmission Control Protocol) is a connection-based protocol that provides a
reliable flow of data between two computers.
 When two applications want to communicate to each other reliably, they establish a
connection and send data back and forth over that connection.
 This is analogous to making a telephone call. If you want to speak to Aunt Beatrice in
Kentucky, a connection is established when you dial her phone number and she answers.
You send data back and forth over the connection by speaking to one another over the
phone lines.
 TCP provides a point-to-point channel for applications that require reliable
communications.
 The Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all
examples of applications that require a reliable communication channel.
UDP
 UDP (User Datagram Protocol) is a protocol that sends independent packets of data,
called datagrams, from one computer to another with no guarantees about arrival. UDP is
not connection-based like TCP.
 Sending datagrams is much like sending a letter through the postal service: The order of
delivery is not important and is not guaranteed, and each message is independent of any
other.
 Many firewalls and routers have been configured not to allow UDP packets. If you're
having trouble connecting to a service outside your firewall, or if clients are having
trouble connecting to your service, ask your system administrator if UDP is permitted.
Ports
 A computer has a single physical connection to the network. All data destined for a
particular computer arrives through that connection.
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
51
 However, the data may be intended for different applications running on the computer.
So how does the computer know to which application to forward the data?
 Through the use of ports.
 Data transmitted over the Internet is accompanied by addressing information that
identifies the computer and the port for which it is destined.
 The computer is identified by its 32-bit IP address, which IP uses to deliver data to the
right computer on the network.
 Ports are identified by a 16-bit number, which TCP and UDP use to deliver the data to the
right application.
 In connection-based communication such as TCP, a server application binds a socket to a
specific port number.
In datagram-based communication such as UDP, the datagram packet contains the port number
of its destination and UDP routes the packet to the appropriate application, as illustrated in this
figure:
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
52
Working with URL
 URL is the acronym for Uniform Resource Locator.
 It is a reference (an address) to a resource on the Internet.
 You provide URLs to your favorite Web browser so that it can locate files on the Internet
in the same way that you provide addresses on letters so that the post office can locate
your correspondents.
 A URL has two main components:
 Protocol identifier: For the URL http://example.com, the protocol identifier is http.
 Resource name: For the URL http://example.com, the resource name is example.com.
The resource name is the complete address to the resource. The format of the
resource name depends entirely on the protocol used, but for many protocols,
including HTTP, the resource name contains one or more of the following
components:
• Host Name: The name of the machine on which the resource lives.
• Filename: The pathname to the file on the machine.
• Port Number: The port number to which to connect (typically optional).
• Reference: A reference to a named anchor within a resource that usually identifies a
specific location within a file (typically optional).
What Is a Socket?
 A socket is one endpoint of a two-way communication link between two programs
running on the network.
 A socket is bound to a port number so that the TCP layer can identify the application that
data is destined to be sent.
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
53
Normally, a server runs on a specific computer and has a socket that is bound to a specific port
number. The server just waits, listening to the socket for a client to make a connection request.
On the client-side: The client knows the hostname of the machine on which the server is running
and the port number on which the server is listening. To make a connection request, the client
tries to rendezvous with the server on the server's machine and port. The client also needs to
identify itself to the server so it binds to a local port number that it will use during this
connection. This is usually assigned by the system.
If everything goes well, the server accepts the connection. Upon acceptance, the server gets a
new socket bound to the same local port and also has its remote endpoint set to the address and
port of the client. It needs a new socket so that it can continue to listen to the original socket for
connection requests while tending to the needs of the connected client.
On the client side, if the connection is accepted, a socket is successfully created and the client
can use the socket to communicate with the server.
The client and server can now communicate by writing to or reading from their sockets.
Socket Class
The java.net.Socket class represents the socket that both the client and the server use to
communicate with each other. The client obtains a Socket object by instantiating one, whereas
the server obtains a Socket object from the return value of the accept() method.
The Socket class has five constructors
Sr.No. Method & Description
1 public Socket(String host, int port) throws UnknownHostException, IOException.
This method attempts to connect to the specified server at the specified port. If this
constructor does not throw an exception, the connection is successful and the client is
connected to the server.
2 public Socket(InetAddress host, int port) throws IOException
This method is identical to the previous constructor, except that the host is denoted
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
54
by an InetAddress object.
3 public Socket(String host, int port, InetAddress localAddress, int localPort) throws
IOException.
Connects to the specified host and port, creating a socket on the local host at the
specified address and port.
4 public Socket(InetAddress host, int port, InetAddress localAddress, int localPort)
throws IOException.
This method is identical to the previous constructor, except that the host is denoted
by an InetAddress object instead of a String.
5 public Socket()
Creates an unconnected socket. Use the connect() method to connect this socket to a
server.
When the Socket constructor returns, it does not simply instantiate a Socket object but it actually
attempts to connect to the specified server and port.
Some methods of interest in the Socket class are listed here. Notice that both the client and the
server have a Socket object, so these methods can be invoked by both the client and the server.
Sr.No. Method & Description
1 public void connect(SocketAddress host, int timeout) throws IOException
This method connects the socket to the specified host. This method is needed only
when you instantiate the Socket using the no-argument constructor.
2 public InetAddress getInetAddress()
This method returns the address of the other computer that this socket is connected
to.
3 public int getPort()
Returns the port the socket is bound to on the remote machine.
4 public void close() throws IOException
Closes the socket, which makes this Socket object no longer capable of connecting
again to any server.
ServerSocket Class
The java.net.ServerSocket class is used by server applications to obtain a port and listen for
client requests.
The ServerSocket class has four constructors
Sr.No. Method & Description
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
55
1 public ServerSocket(int port) throws IOException
Attempts to create a server socket bound to the specified port. An exception occurs if
the port is already bound by another application.
2 public ServerSocket(int port, int backlog) throws IOException
Similar to the previous constructor, the backlog parameter specifies how many
incoming clients to store in a wait queue.
3 public ServerSocket(int port, int backlog, InetAddress address) throws IOException
Similar to the previous constructor, the InetAddress parameter specifies the local IP
address to bind to. The InetAddress is used for servers that may have multiple IP
addresses, allowing the server to specify which of its IP addresses to accept client
requests on.
4 public ServerSocket() throws IOException
Creates an unbound server socket. When using this constructor, use the bind()
method when you are ready to bind the server socket.
Following are some of the common methods of the ServerSocket class
Sr.No. Method & Description
1 public int getLocalPort()
Returns the port that the server socket is listening on. This method is useful if you
passed in 0 as the port number in a constructor and let the server find a port for you.
2 public Socket accept() throws IOException
Waits for an incoming client. This method blocks until either a client connects to the
server on the specified port or the socket times out, assuming that the time-out value
has been set using the setSoTimeout() method. Otherwise, this method blocks
indefinitely.
3 public void setSoTimeout(int timeout)
Sets the time-out value for how long the server socket waits for a client during the
accept().
4 public void bind(SocketAddress host, int backlog)
Binds the socket to the specified server and port in the SocketAddress object. Use this
method if you have instantiated the ServerSocket using the no-argument constructor.
Write a TCP uni-direction Socket programming.
//Server file
import java.net.*;
import java.io.*;
class server
{
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
56
public static void main(String[] args) throws Exception
{
int portno=1234;
ServerSocket ss= new ServerSocket(portno);
System.out.println("waiting for client to connect...");
Socket s=ss.accept();
System.out.println("Client Connected......");
BufferedReader br=new BufferedReader(new
InputStreamReader(s.getInputStream()));
String str;
while ((str=br.readLine())!=null)
{
System.out.println(str);
}
}
}
//Client file
import java.net.*;
import java.io.*;
class client
{
public static void main(String[] args) throws Exception
{
int portno=1234;
InetAddress ip=InetAddress.getByName(null);
Socket x=new Socket(ip,portno);
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
PrintWriter pw=new PrintWriter(new
OutputStreamWriter(x.getOutputStream()));
String str;
while ((str=br.readLine())!=null)
{
pw.println(str);
pw.flush();
}
}
}
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
57
Output:
Write a TCP bi-directional Socket programming.
//Client file
import java.net.*;
import java.io.*;
class client1
{
public static void main(String[] args) throws Exception
{
int portno=1234;
InetAddress ip=InetAddress.getByName(null);
Socket x=new Socket(ip,portno);
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
58
BufferedReader br1=new BufferedReader(new
InputStreamReader(x.getInputStream()));
PrintWriter pw=new PrintWriter(new
OutputStreamWriter(x.getOutputStream()));
String str=br.readLine();
pw.println(str);
pw.flush();
str=br1.readLine();
System.out.println(str);
}
}
// Server file
import java.net.*;
import java.io.*;
class server1
{
public static void main(String[] args) throws Exception
{
int portno=1234;
ServerSocket ss= new ServerSocket(portno);
System.out.println("waiting for client to connect...");
Socket s=ss.accept();
System.out.println("Client Connected......");
BufferedReader br=new BufferedReader(new
InputStreamReader(s.getInputStream()));
PrintWriter pw=new PrintWriter(new
OutputStreamWriter(s.getOutputStream()));
String str=br.readLine();
int num=Integer.parseInt(str);
pw.println("square is " + num*num);
pw.flush();
}
}
Output:
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
59
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
60
UNIT 3
Wrapper class in Java
Wrapper class in java provides the mechanism to convert primitive into object and object into
primitive.
Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and object into
primitive automatically. The automatic conversion of primitive into object is known as
autoboxing and vice-versa unboxing.
The eight classes of java.lang package are known as wrapper classes in java. The list of eight
wrapper classes are given below:
Primitive Type Wrapper class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Example: Primitive to Wrapper
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internal
ly
Example: Wrapper to Primitive
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int
int j=a;//unboxing, now compiler will write a.intValue() internally
SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS
ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W)
PHONE : 8097071144/8097071155
61
Collection Framework:
The Java collections framework (JCF) is a set of classes and interfaces that implement
commonly reusable collection data structures
Collections and arrays are similar in that they both hold references to objects and they can be
managed as a group. However, unlike arrays, collections do not need to be assigned a certain
capacity when instantiated. Collections can also grow and shrink in size automatically when
objects are added or removed. Collections cannot hold basic data type elements (primitive types)
such as int, long, or double; instead, they hold Wrapper Classes such as Integer, Long, or
Double.
Almost all collections in Java are derived from the java.util.Collection interface. Collection
defines the basic parts of all collections. The interface states the add() and remove() methods for
adding to and removing from a collection respectively. Also required is the toArray() method,
which converts the collection into a simple array of all the elements in the collection. Finally, the
contains() method checks if a specified element is in the collection.
util packages and interfaces
Sybsc cs sem 3 core java
Sybsc cs sem 3 core java
Sybsc cs sem 3 core java
Sybsc cs sem 3 core java
Sybsc cs sem 3 core java
Sybsc cs sem 3 core java
Sybsc cs sem 3 core java
Sybsc cs sem 3 core java
Sybsc cs sem 3 core java
Sybsc cs sem 3 core java
Sybsc cs sem 3 core java
Sybsc cs sem 3 core java
Sybsc cs sem 3 core java
Sybsc cs sem 3 core java
Sybsc cs sem 3 core java
Sybsc cs sem 3 core java
Sybsc cs sem 3 core java
Sybsc cs sem 3 core java
Sybsc cs sem 3 core java

Contenu connexe

Tendances

J2EE Struts with Hibernate Framework
J2EE Struts with Hibernate FrameworkJ2EE Struts with Hibernate Framework
J2EE Struts with Hibernate Frameworkmparth
 
Java programming(unit 1)
Java programming(unit 1)Java programming(unit 1)
Java programming(unit 1)SURBHI SAROHA
 
Java Lecture 1
Java Lecture 1Java Lecture 1
Java Lecture 1Qualys
 
Training on java niit (sahil gupta 9068557926)
Training on java niit (sahil gupta 9068557926)Training on java niit (sahil gupta 9068557926)
Training on java niit (sahil gupta 9068557926)Sahil Gupta
 
UML Case Tools
UML Case ToolsUML Case Tools
UML Case ToolsAshesh R
 
Java for Recruiters
Java for RecruitersJava for Recruiters
Java for Recruitersph7 -
 
Core java kvr - satya
Core  java kvr - satyaCore  java kvr - satya
Core java kvr - satyaSatya Johnny
 
Features of java unit 1
Features of java unit 1Features of java unit 1
Features of java unit 1RubaNagarajan
 
Java programming language
Java programming languageJava programming language
Java programming languageSubhashKumar329
 
What Your Jvm Has Been Trying To Tell You
What Your Jvm Has Been Trying To Tell YouWhat Your Jvm Has Been Trying To Tell You
What Your Jvm Has Been Trying To Tell YouJohn Pape
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Languagejaimefrozr
 
(Ebook pdf) java programming language basics
(Ebook pdf)   java programming language basics(Ebook pdf)   java programming language basics
(Ebook pdf) java programming language basicsRaffaella D'angelo
 

Tendances (19)

J2EE Struts with Hibernate Framework
J2EE Struts with Hibernate FrameworkJ2EE Struts with Hibernate Framework
J2EE Struts with Hibernate Framework
 
Java programming(unit 1)
Java programming(unit 1)Java programming(unit 1)
Java programming(unit 1)
 
Java Lecture 1
Java Lecture 1Java Lecture 1
Java Lecture 1
 
Java chapter 1
Java   chapter 1Java   chapter 1
Java chapter 1
 
1.introduction to java
1.introduction to java1.introduction to java
1.introduction to java
 
Training on java niit (sahil gupta 9068557926)
Training on java niit (sahil gupta 9068557926)Training on java niit (sahil gupta 9068557926)
Training on java niit (sahil gupta 9068557926)
 
Corejava ratan
Corejava ratanCorejava ratan
Corejava ratan
 
UML Case Tools
UML Case ToolsUML Case Tools
UML Case Tools
 
Java for Recruiters
Java for RecruitersJava for Recruiters
Java for Recruiters
 
Core java kvr - satya
Core  java kvr - satyaCore  java kvr - satya
Core java kvr - satya
 
Features of java unit 1
Features of java unit 1Features of java unit 1
Features of java unit 1
 
.NET Vs J2EE
.NET Vs J2EE.NET Vs J2EE
.NET Vs J2EE
 
Java basics notes
Java basics notesJava basics notes
Java basics notes
 
Java programming language
Java programming languageJava programming language
Java programming language
 
Java 3 rd sem. 2012 aug.ASSIGNMENT
Java 3 rd sem. 2012 aug.ASSIGNMENTJava 3 rd sem. 2012 aug.ASSIGNMENT
Java 3 rd sem. 2012 aug.ASSIGNMENT
 
What Your Jvm Has Been Trying To Tell You
What Your Jvm Has Been Trying To Tell YouWhat Your Jvm Has Been Trying To Tell You
What Your Jvm Has Been Trying To Tell You
 
Features of java
Features of javaFeatures of java
Features of java
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
 
(Ebook pdf) java programming language basics
(Ebook pdf)   java programming language basics(Ebook pdf)   java programming language basics
(Ebook pdf) java programming language basics
 

Similaire à Sybsc cs sem 3 core java

Similaire à Sybsc cs sem 3 core java (20)

Presentación rs232 java
Presentación rs232 javaPresentación rs232 java
Presentación rs232 java
 
Java1
Java1Java1
Java1
 
Java
Java Java
Java
 
Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...
 
Java features
Java  features Java  features
Java features
 
Unit1 JAVA.pptx
Unit1 JAVA.pptxUnit1 JAVA.pptx
Unit1 JAVA.pptx
 
Java unit 1
Java unit 1Java unit 1
Java unit 1
 
0f0cef_1dac552af56c4338ab0672859199e693.pdf
0f0cef_1dac552af56c4338ab0672859199e693.pdf0f0cef_1dac552af56c4338ab0672859199e693.pdf
0f0cef_1dac552af56c4338ab0672859199e693.pdf
 
java introduction.docx
java introduction.docxjava introduction.docx
java introduction.docx
 
Java part1
Java part1Java part1
Java part1
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
Ijaprr vol1-2-13-60-64tejinder
Ijaprr vol1-2-13-60-64tejinderIjaprr vol1-2-13-60-64tejinder
Ijaprr vol1-2-13-60-64tejinder
 
JAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptxJAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptx
 
OOPS JAVA.pdf
OOPS JAVA.pdfOOPS JAVA.pdf
OOPS JAVA.pdf
 
Introduction to Java Programming.pdf
Introduction to Java Programming.pdfIntroduction to Java Programming.pdf
Introduction to Java Programming.pdf
 
J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01
 
Java & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkJava & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate Framework
 
JAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptxJAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptx
 
Unit-IV_Introduction to Java.pdf
Unit-IV_Introduction to Java.pdfUnit-IV_Introduction to Java.pdf
Unit-IV_Introduction to Java.pdf
 
UNIT 1.pptx
UNIT 1.pptxUNIT 1.pptx
UNIT 1.pptx
 

Plus de WE-IT TUTORIALS

TYBSC CS 2018 WEB SERVICES NOTES
TYBSC CS 2018 WEB SERVICES NOTESTYBSC CS 2018 WEB SERVICES NOTES
TYBSC CS 2018 WEB SERVICES NOTESWE-IT TUTORIALS
 
Geographical information system unit 6
Geographical information  system unit 6Geographical information  system unit 6
Geographical information system unit 6WE-IT TUTORIALS
 
Geographical information system unit 5
Geographical information  system unit 5Geographical information  system unit 5
Geographical information system unit 5WE-IT TUTORIALS
 
Geographical information system unit 4
Geographical information  system unit 4Geographical information  system unit 4
Geographical information system unit 4WE-IT TUTORIALS
 
Geographical information system unit 3
Geographical information  system unit 3Geographical information  system unit 3
Geographical information system unit 3WE-IT TUTORIALS
 
Geographical information system unit 2
Geographical information  system unit 2Geographical information  system unit 2
Geographical information system unit 2WE-IT TUTORIALS
 
Geographical information system unit 1
Geographical information  system unit 1Geographical information  system unit 1
Geographical information system unit 1WE-IT TUTORIALS
 
Internet technology unit 5
Internet technology unit 5Internet technology unit 5
Internet technology unit 5WE-IT TUTORIALS
 
Internet technology unit 4
Internet technology unit 4Internet technology unit 4
Internet technology unit 4WE-IT TUTORIALS
 
Internet technology unit 3
Internet technology unit 3Internet technology unit 3
Internet technology unit 3WE-IT TUTORIALS
 
Internet technology unit 2
Internet technology unit 2Internet technology unit 2
Internet technology unit 2WE-IT TUTORIALS
 
Internet technology unit 1
Internet technology unit 1Internet technology unit 1
Internet technology unit 1WE-IT TUTORIALS
 
Internet technology unit 6
Internet technology unit 6Internet technology unit 6
Internet technology unit 6WE-IT TUTORIALS
 
Data warehousing unit 6.1
Data warehousing unit 6.1Data warehousing unit 6.1
Data warehousing unit 6.1WE-IT TUTORIALS
 
Data warehousing unit 5.2
Data warehousing unit 5.2Data warehousing unit 5.2
Data warehousing unit 5.2WE-IT TUTORIALS
 
Data warehousing unit 5.1
Data warehousing unit 5.1Data warehousing unit 5.1
Data warehousing unit 5.1WE-IT TUTORIALS
 
Data warehousing unit 4.2
Data warehousing unit 4.2Data warehousing unit 4.2
Data warehousing unit 4.2WE-IT TUTORIALS
 

Plus de WE-IT TUTORIALS (20)

TYBSC CS 2018 WEB SERVICES NOTES
TYBSC CS 2018 WEB SERVICES NOTESTYBSC CS 2018 WEB SERVICES NOTES
TYBSC CS 2018 WEB SERVICES NOTES
 
TYBSC CS SEM 5 AI NOTES
TYBSC CS SEM 5 AI NOTESTYBSC CS SEM 5 AI NOTES
TYBSC CS SEM 5 AI NOTES
 
Geographical information system unit 6
Geographical information  system unit 6Geographical information  system unit 6
Geographical information system unit 6
 
Geographical information system unit 5
Geographical information  system unit 5Geographical information  system unit 5
Geographical information system unit 5
 
Geographical information system unit 4
Geographical information  system unit 4Geographical information  system unit 4
Geographical information system unit 4
 
Geographical information system unit 3
Geographical information  system unit 3Geographical information  system unit 3
Geographical information system unit 3
 
Geographical information system unit 2
Geographical information  system unit 2Geographical information  system unit 2
Geographical information system unit 2
 
Geographical information system unit 1
Geographical information  system unit 1Geographical information  system unit 1
Geographical information system unit 1
 
Pm unit 1,2,3,4,5,6
Pm unit 1,2,3,4,5,6Pm unit 1,2,3,4,5,6
Pm unit 1,2,3,4,5,6
 
Internet technology unit 5
Internet technology unit 5Internet technology unit 5
Internet technology unit 5
 
Internet technology unit 4
Internet technology unit 4Internet technology unit 4
Internet technology unit 4
 
Internet technology unit 3
Internet technology unit 3Internet technology unit 3
Internet technology unit 3
 
Internet technology unit 2
Internet technology unit 2Internet technology unit 2
Internet technology unit 2
 
Internet technology unit 1
Internet technology unit 1Internet technology unit 1
Internet technology unit 1
 
Internet technology unit 6
Internet technology unit 6Internet technology unit 6
Internet technology unit 6
 
Data warehousing unit 2
Data warehousing unit 2Data warehousing unit 2
Data warehousing unit 2
 
Data warehousing unit 6.1
Data warehousing unit 6.1Data warehousing unit 6.1
Data warehousing unit 6.1
 
Data warehousing unit 5.2
Data warehousing unit 5.2Data warehousing unit 5.2
Data warehousing unit 5.2
 
Data warehousing unit 5.1
Data warehousing unit 5.1Data warehousing unit 5.1
Data warehousing unit 5.1
 
Data warehousing unit 4.2
Data warehousing unit 4.2Data warehousing unit 4.2
Data warehousing unit 4.2
 

Dernier

31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptxmary850239
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
CHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxCHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxAneriPatwari
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17Celine George
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptxmary850239
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1GloryAnnCastre1
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 

Dernier (20)

31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
CHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxCHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptx
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 

Sybsc cs sem 3 core java

  • 1. CORE JAVA SYBSC-CS SEM 3 302 PARANJPE UDYOG BHAVAN, NEAR KHANDELWAL SWEETS, NEAR THANE STATION , THANE (WEST) PHONE NO: 8097071144 / 8097071155
  • 2. INDEX SYLLABUS PAGE NO Unit I The Java Language: Features of Java, Java programming format, Java Tokens, Java Statements, Java Data Types, Typecasting, Arrays OOPS: Introduction, Class, Object, Static Keywords, Constructors, this Key Word, Inheritance, super Key Word, Polymorphism (overloading and overriding), Abstraction, Encapsulation, Abstract Classes, Interfaces String Manipulations: String, String Buffer, String Tokenizer Packages: Introduction to predefined packages (java.lang, java.util, java.io, java.sql, java.swing), User Defined Packages, Access specifiers 1 Unit II Exception Handling: Introduction, Pre-Defined Exceptions, Try-Catch-Finally, Throws, throw, User Defined Exception examples Multithreading: Thread Creations, Thread Life Cycle, Life Cycle Methods, Synchronization, Wait() notify() notify all() methods I/O Streams: Introduction, Byte-oriented streams, Character- oriented streams, File, Random access File, Serialization Networking: Introduction, Socket, Server socket, Client –Server Communication 27 Unit III Wrapper Classes: Introduction, Byte, Short, Integer, Long, Float, Double, Character, Boolean classes Collection Framework: Introduction, util Package interfaces, List, Set, Map, List interface & its classes, Set interface & its classes, Map interface & its classes Inner Classes: Introduction, Member inner class, Static inner class, Local inner class, Anonymous inner class AWT: Introduction, Components, Event-Delegation-Model, Listeners, Layouts, Individual components Label, Button, CheckBox, Radio Button, Choice, List, Menu, Text Field, Text Area 60
  • 3. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 1 UNIT 1 features of Java. Platform Independent The concept of Write-once-run-anywhere (known as the Platform independent) is one of the important key feature of java language that makes java as the most powerful language. Not even a single language is idle to this feature but java is more closer to this feature. The programs written on one platform can run on any platform provided the platform must have the JVM. Simple There are various features that makes the java as a simple language. Programs are easy to write and debug because java does not use the pointers explicitly. Java provides the bug free system due to the strong memory management. It also has the automatic memory allocation and deallocation system. Object Oriented To be an Object Oriented language, any language must follow at least the four characteristics.  Inheritance : It is the process of creating the new classes and using the behavior of the existing classes by extending them just to reuse the existing code and adding the additional features as needed.  Encapsulation: It is the mechanism of combining the information and providing the abstraction.  Polymorphism: As the name suggest one name multiple form, Polymorphism is the way of providing the different functionality by the functions having the same name based on the signatures of the methods.  Dynamic binding : Sometimes we don't have the knowledge of objects about their specific types while writing our code. It is the way of providing the maximum functionality to a program about the specific type at runtime.  Robust Java has the strong memory allocation and automatic garbage collection mechanism. It provides the powerful exception handling and type checking mechanism as compare to other programming languages. Compiler checks the program whether there any error and interpreter checks any run time error and makes the system secure from crash. All of the above features makes the java language robust.
  • 4. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 2  Distributed The widely used protocols like HTTP and FTP are developed in java. Internet programmers can call functions on these protocols and can get access the files from any remote machine on the internet rather than writing codes on their local system.  Portable The feature Write-once-run-anywhere makes the java language portable provided that the system must have interpreter for the JVM. Java also have the standard data size irrespective of operating system or the processor. These features makes the java as a portable language.  Dynamic While executing the java program the user can get the required files dynamically from a local drive or from a computer thousands of miles away from the user just by connecting with the Internet.  Secure Java does not use memory pointers explicitly. All the programs in java are run under an area known as the sand box. Security manager determines the accessibility options of a class like reading and writing a file to the local disk. Java uses the public key encryption system to allow the java applications to transmit over the internet in the secure encrypted form. The bytecode Verifier checks the classes after loading.  Performance Java uses native code usage, and lightweight process called threads. In the beginning interpretation of bytecode resulted the performance slow but the advance version of JVM uses the adaptive and just in time compilation technique that improves the performance.  Multithreaded As we all know several features of Java like Secure, Robust, Portable, dynamic etc; you will be more delighted to know another feature of Java which is Multithreaded. Java is also a Multithreaded programming language. Multithreading means a single program having different threads executing independently at the same time. Multiple threads execute instructions according to the program code in a process or a program. Multithreading works the similar way as multiple processes run on one computer. Multithreading programming is a very interesting concept in Java. In multithreaded programs not even a single thread disturbs the execution of other thread. Threads are obtained from the pool of available ready to run threads and they run on the system CPUs. This is how Multithreading works in Java which you will soon come to know in details in later chapters.  Interpreted We all know that Java is an interpreted language as well. With an interpreted language such as Java, programs run directly from the source code. The interpreter program reads the source code and translates it on the fly into computations. Thus, Java as an interpreted language depends on an interpreter program. The versatility of being platform independent makes Java to outshine from other languages. The source code to be written and distributed is platform independent. Another
  • 5. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 3 advantage of Java as an interpreted language is its error debugging quality. Due to this any error occurring in the program gets traced. This is how it is different to work with Java.  Architecture Neutral The term architectural neutral seems to be weird, but yes Java is an architectural neutral language as well. The growing popularity of networks makes developers think distributed. In the world of network it is essential that the applications must be able to migrate easily to different computer systems. Not only to computer systems but to a wide variety of hardware architecture and Operating system architectures as well. The Java compiler does this by generating byte code instructions, to be easily interpreted on any machine and to be easily translated into native machine code on the fly. The compiler generates an architecture-neutral object file format to enable a Java application to execute anywhere on the network and then the compiled code is executed on many processors, given the presence of the Java runtime system. Hence Java was designed to support applications on network. This feature of Java has thrived the programming language. short note on JVM Java’s Magic: The Bytecode The key that allows Java to solve both the security and the portability problems just described is that the output of a Java compiler is not executable code. Rather, it is bytecode.  Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time system, which is called the Java Virtual Machine (JVM). That is, in its standard form, the JVM is an interpreter for bytecode. This may come as a bit of a surprise. As you know, C++ is compiled to executable code. In fact, most modern languages are designed to be compiled, not interpreted—mostly because of performance concerns. However, the fact that a Java program is executed by the JVM helps solve the major problems associated with downloading programs over the internet.  Translating a Java program into bytecode helps makes it much easier to run a program in a wide variety of environments. The reason is straightforward: only the JVM needs to be implemented for each platform. Once the run-time package exists for a given system, any Java program can run on it. Remember, although the details of the JVM will differ from platform to platform, all interpret the same Java bytecode. If a Java program were compiled to native code, then different versions of the same program would have to exist for each type of CPU connected to the Internet. This is, of course, not a feasible solution. Thus, the interpretation of bytecode is the easiest way to create truly portable programs. The fact that a Java program is interpreted also helps to make it secure.
  • 6. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 4 Because the execution of every Java program is under the control of the JVM, the JVM can contain the program and prevent it from generating side effects outside of the system. As you will see, safety is also enhanced by certain restrictions that exist in the Java language. When a program is interpreted, it generally runs substantially slower than it would run if compiled to executable code. However, with Java, the differential between the two is not so great. The use of bytecode enables the Java run-time system to execute programs much faster than you might expect. Format of a Java program In Java, a class definition starts with the word "class" (possibly preceded by the word "public" or "private"), continues with the name of the class and the character "{" (a left brace or curly bracket), and ends with the character "}" (a right brace). Inside the braces are definitions of methods and variables. A method definition similarly starts with naming information followed by a pair of braces that include the statements of the method. The braces act in this way like parentheses in Scheme. Braces appear inside methods as well, to group statements (again in the same way that statements in a Scheme procedure body are grouped with parentheses). Statements within such a group are separated with semicolons. Here's an example of a "Hello world" program in Java (traditionally, the simplest program in a given language): class SimpleGreeter { public static void main (String [ ] arguments) { System.out.print ("hello "); System.out.println ("world"); } } At least one of the classes in a Java program must contain a method named main; a main method is what's called by the operating system to run the program. Java Tokens Java Tokens:- A java Program is made up of Classes and Methods and in the Methods are the Container of the various Statements And a Statement is made up of Variables, Constants, operators etc .
  • 7. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 5 Tokens are the various Java program elements which are identified by the compiler. A token is the smallest element of a program that is meaningful to the compiler. Tokens supported in Java include keywords, variables, constants, special characters, operations etc. Tokens are the smallest unit of Program There is Five Types of Tokens 1. Reserve Word or Keywords 2. Identifier 3. Literals 4. Operators 5. Separators java statements 1. Control Statement a. Conditional execution i. If Statement ii. If – Else statement iii. If- Else-if statement iv. Switch Statement b. Looping i. For Loop ii. While Loop iii. Do – While Loop c. Flow Control Statement i. Return Statement ii. Continue Statement iii. Break Statement 2. Assignment Statement
  • 8. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 6 An assignment statement in Java uses the assignment operator (=) to assign the result of an expression to a variable Variables Variables are locations in memory in which values can be stored. Each one has a name, a type, and a value. Before we can use a variable, we have to declare it. After it is declared, we can then assign values to it. Java actually has three kinds of variables: 1. instance variables, 2. class variables, 3. And local variables. Instance variables, are used to define the attributes of a particular object. Class variables, are similar to instance variables, except their values apply to all that class's instances (and to the class itself) rather than having different values for each object. Local variables, are declared and used inside method definitions, Although all three kinds of variables are declared in much the same ways, class and instance variables are accessed and assigned in slightly different ways from local variables. Java does not have global variables-that is, variables that are global to all parts of a program. Instance and class variables can be used to communicate global information between and among objects. Declaring Variables To use any variable in a Java program, we must first declare it. Variable declarations consist of a type and a variable name: int myAge; String myName; boolean isTired;
  • 9. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 7 Variable definitions can go anywhere in a method definition (that is, anywhere a regular Java statement can go), although they are most commonly declared at the beginning of the definition before they are used: public static void main (String args[]) { int count; String title; boolean isAsleep; ... } We can string together variable names with the same type on one line: int x, y, z; String firstName, LastName; We can also give each variable an initial value when we declare it: int myAge, mySize, numShoes = 28; String myName = "eBIZ"; boolean isTired = true; int a = 4, b = 5, c = 6; If there are multiple variables on the same line with only one initializer the initial value applies to only the last variable in a declaration. We can also group individual variables and initializers on the same line using commas, as with the last example. Rules on Variable Names Variable names in Java can start with a letter, an underscore (_), or a dollar sign ($). They cannot start with a number. After the first character, our variable names can include any letter or number. Symbols, such as %, *, @, and so on, are often reserved for operators in Java, so we should be careful when using symbols in variable names. The Java language uses the Unicode character set. The Java language is case sensitive, which means that uppercase letters are different from lowercase letters. This means that the variable X is different from the variable x, and a rose is not a Rose is not a ROSE. Variable Types
  • 10. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 8 In addition to the variable name, each variable declaration must have a type, which defines what values that variable can hold. The variable type can be one of three things: • One of the eight primitive data types • The name of a class or interface • An array Primitive Data Types The eight primitive data types handle common types for integers, floating-point numbers, characters, and boolean values (true or false). They're called primitive because they're built into the system and are not actual objects, which makes them more efficient to use. Integer Type There are four Java integer types, each with a different range of values. All are signed, which means they can hold either positive or negative numbers. Type Size Range byte 8 bits -128 to 127 short 16 bits -32,768 to 32,767 int 32 bits -2,147,483,648 to 2,147,483,647 long 64 bits -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 Data Type Default Value (for fields) float 0.0f double 0.0d char 'u0000' String (or any object) Null
  • 11. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 9 Floating-point type: Floating-point numbers are used for numbers with a decimal part. There are two floating-point types: float (32 bits, single precision) and double (64 bits, double precision). Char type: The char type is used for individual characters. Because Java uses the Unicode character set, the char type has 16 bits of precision, unsigned. Constants  Are similar to variables but, once initialized, their contents may NOT be changed?  Are declared with the keyword final?  By convention, have all capital letters in their identifier. This makes them easier to see within the code. This program defines a number of constants and then displays some of their values. public class App { public static void main(String[] args) { final boolean YES = true; final char DEPOSIT_CODE = 'D'; final byte INCHES_PER_FOOT = 12; final int FEET_PER_MILE = 5280; final float PI = 3.14F; final double SALES_TAX_RATE = .06; final String ADDRESS = "119 South Street"; // Display some of the values System.out.println(INCHES_PER_FOOT); System.out.println(ADDRESS); } } TYPE CASTING
  • 12. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 10 Type Casting refers to changing an entity of one datatype into another. This is important for the type conversion in developing any application. If you will store a int value into a byte variable directly, this will be illegal operation. For storing your calculated int value in a byte variable you will have to change the type of resultant data which has to be stored. Type Conversion and Casting it is fairly common to assign a value of one type to a variable of another type. If the two types are compatible, then Java will perform the conversion automatically. For example, it is always possible to assign an int value to a long variable. not all types are compatible, and thus, not all type conversions are implicitly allowed. For instance, there is no conversion defined from double to byte. it is still possible to obtain a conversion between incompatible types. To do so, you must use a cast, which performs an explicit conversion between incompatible types. Java’s Automatic Conversions When one type of data is assigned to another type of variable, an automatic type conversion will take place if the following two conditions are met: ■ The two types are compatible. ■ The destination type is larger than the source type. int type is always large enough to hold all valid byte values, so no explicit cast statement is required. the numeric types, including integer and floating-point types, are compatible with each other. However, the numeric types are not compatible with char or boolean. Also, char and boolean are not compatible with each other. Casting Incompatible Types what if you want to assign an int value to a byte variable? This conversion will not be performed automatically, because a byte is smaller than an int. This kind of conversion is sometimes called a narrowing conversion, since you are explicitly making the value narrower so that it will fit into the target type. To create a conversion between two incompatible types, you must use a cast. A cast is simply an explicit type conversion. It has this general form: (target-type) value int a;
  • 13. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 11 byte b; // ... b = (byte) a; A different type of conversion will occur when a floating-point value is assigned to an integer type: truncation. The Type Promotion Rules In addition to the elevation of bytes and shorts to int, Java defines several type promotion rules that apply to expressions. They are as follows. First, all byte and short values are promoted to int, as just described. Then, if one operand is a long, the whole expression is promoted to long. If one operand is a float, the entire expression is promoted to float. If any of the operands is double, the result is double. Arrays Introduction An array is a collection of items. Each slot in the array can hold an object or a primitive value. Arrays in Java are objects that can be treated just like other objects in the language. An array is an indexed table of like values. While they can exist in more than one dimension, we are only interested in one-dimensional arrays as depicted by the following This array consists of five elements where each is an integer value (217, 138, 92, 12, and 168). To access a particular element within an array, its corresponding index (offset) is used. For example, the integer value at index location 3 within this array is 12. Notice that the indexes are zero based because the offset of the first element is always zero (you don't have to skip over any other elements to get there). While all programming languages include the ability to process arrays, Java provides enhanced integrity and other features not found in other languages.
  • 14. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 12 Java arrays Java array require that all elements be of the same data type. For example, We may create an array of char values, or an array of float values, or an array of boolean values, etc... Java array are objects and must be declared like one. The general syntax is as follows: data-type[] identifier = new data-type[n]; or data-type identifier[] = new data-type[n]; Where identifier is the array (object) reference and n is an integer expression that specifies how many elements are in the array. For example, int[] myArray = new int[5]; Alternatively, a programmer may split the definition of the array reference and the instantiation of the array into two statements as follows: int[] myArray; myArray = new int[5]; Using either technique, it is important to understand what is created. The following diagram may help: The array reference (myArray) can be thought of as pointing to the array whose elements reside on the memory heap. Notes:
  • 15. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 13  At the time an array reference is declared, it initially contains null (it doesn't point to anything). It doesn't receive a value until an array is assigned to it.  An array reference can only be assigned an array of the correct type. In the above example, myArray is declared to be a reference to an int array, so only an array of int values can ever be assigned to it. To attempt otherwise will result in a compile error.  An array reference may be reused to point to a different array (of the appropriate type). Like all objects, however, an array that can no longer be r eferenced will be garbage collected.  When instantiated, all array elements are automatically initialized to binary zeros. This means all elements of numeric arrays will be zero, all elements of boolean arrays will be false, and all elements of char arrays will be the null character. Java array can be constructed from a value list. This is an alternative construction technique as shown by char[] chars = {'a', 'b', 'c'}; This creates a three element array of characters. The first element is initialized to 'a', the second is initialized to 'b', and the third is initialized to 'c'. Notes: The number of elements in the array is determined by the number of values in the list and the new keyword isn't coded. When a value list is used, it can only be coded in the statement that declares the array reference. In other words, the following will not compile: char[] chars; chars = {'a', 'b', 'c'}; Java array permit an element to be accessed via its unique index. For example, int[] numbers = {12, 15, 3, 8};
  • 16. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 14 The following expression will reference the third element (an int with a value of 3) numbers[2] The following program, ArrayDemo, creates an array of integers, puts some values in it, and prints each value to standard output. class ArrayDemo { public static void main(String[] args) { int[] anArray; // declares an array of integers anArray = new int[3]; // allocates memory for 10 integers anArray[0] = 100; // initialize first element anArray[1] = 200; // initialize second element anArray[2] = 300; // etc. System.out.println("Element at index 0: " + anArray[0]); System.out.println("Element at index 1: " + anArray[1]); System.out.println("Element at index 2: " + anArray[2]); } } oops Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts:  Object  Class  Inheritance  Polymorphism  Abstraction  Encapsulation CLASSES AND OBJECTS A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It is a logical entity. It can't be physical.
  • 17. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 15 A class in Java can contain:  fields  methods  constructors  blocks  nested class and interface Object is the physical as well as logical entity whereas class is the logical entity only.  An entity that has state and behavior is known as an object An object has three characteristics: 1. state: represents data (value) of an object. 2. behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc. 3. identity: Object identity is typically implemented via a unique ID. static keyword The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class. The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class. Constructor Constructor in java is a special type of method that is used to initialize the object. Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor. Rules for creating java constructor There are basically two rules defined for the constructor. 1. Constructor name must be same as its class name 2. Constructor must have no explicit return type Types of java constructors
  • 18. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 16 There are two types of constructors: 1. Default constructor (no-arg constructor) 2. Parameterized constructor this keyword There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object. Here is given the 6 usage of java this keyword. 1. this can be used to refer current class instance variable. 2. this can be used to invoke current class method (implicitly) 3. this() can be used to invoke current class constructor. 4. this can be passed as an argument in the method call. 5. this can be passed as argument in the constructor call. 6. this can be used to return the current class instance from the method. Inheritance Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object. The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also. Inheritance represents the IS-A relationship, also known as parent-child relationship. Types of inheritance in java On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
  • 19. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 17 In java programming, multiple and hybrid inheritance is supported through interface only super keyword The super keyword in java is a reference variable which is used to refer immediate parent class object. Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable. Usage of java super Keyword 1. super can be used to refer immediate parent class instance variable. 2. super can be used to invoke immediate parent class method. 3. super() can be used to invoke immediate parent class constructor. polymorphism Method Overloading
  • 20. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 18  If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.  If we have to perform only one operation, having same name of the methods increases the readability of the program.  Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs. Method Overriding  If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java.  In other words, If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding. No. Method Overloading Method Overriding 1) Method overloading is used to increase the readability of the program. Method overriding is used to provide the specific implementation of the method that is already provided by its super class. 2) Method overloading is performed within class. Method overriding occurs in two classes that have IS-A (inheritance) relationship. 3) In case of method overloading, parameter must be different. In case of method overriding, parameter must be same. 4) Method overloading is the example of compile time polymorphism. Method overriding is the example of run time polymorphism. 5) In java, method overloading can't be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter. Return type must be same or covariant in method overriding. Abstraction  Abstraction is a process of hiding the implementation details and showing only functionality to the user.
  • 21. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 19  Another way, it shows only important things to the user and hides the internal details for example sending sms, you just type the text and send the message. You don't know the internal processing about the message delivery.  Abstraction lets you focus on what the object does instead of how it does it. Encapsulation  Encapsulation in java is a process of wrapping code and data together into a single unit, for example capsule i.e. mixed of several medicines.  We can create a fully encapsulated class in java by making all the data members of the class private. Now we can use setter and getter methods to set and get the data in it. Abstract class A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated. abstract class A{} abstract method A method that is declared as abstract and does not have implementation is known as abstract method. abstract void printStatus();//no body and abstract Interface  An interface in java is a blueprint of a class. It has static constants and abstract methods.  The interface in java is a mechanism to achieve abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve abstraction and multiple inheritance in Java.  Java Interface also represents IS-A relationship.  It cannot be instantiated just like abstract class. Abstract class Interface 1) Abstract class can have abstract and non-abstractmethods. Interface can have only abstract methods. Since Java 8, it can have default and static methods also.
  • 22. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 20 2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance. 3) Abstract class can have final, non- final, static and non-static variables. Interface has only static and final variables. 4) Abstract class can provide the implementation of interface. Interface can't provide the implementation of abstract class. 5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface. 6) Example: public abstract class Shape{ public abstract void draw(); } Example: public interface Drawable{ void draw(); } String manipulation String  In java, string is basically an object that represents sequence of char values. An array of characters works same as java string.  Java String class provides a lot of methods to perform operations on string such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.  The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.  Generally, string is a sequence of characters. But in java, string is an object that represents a sequence of characters. The java.lang.String class is used to create string object.  The java String is immutable i.e. it cannot be changed. Whenever we change any string, a new instance is created. No. Method Description 1 char charAt(int index) returns char value for the particular index 2 int length() returns string length 3 static String format(String format, Object... args) returns formatted string 4 static String format(Locale l, String format, Object... args) returns formatted string with given locale
  • 23. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 21 5 String substring(int beginIndex) returns substring for given begin index 6 String substring(int beginIndex, int endIndex) returns substring for given begin index and end index 7 boolean contains(CharSequence s) returns true or false after matching the sequence of char value 8 static String join(CharSequence delimiter, CharSequence... elements) returns a joined string 9 static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) returns a joined string 10 boolean equals(Object another) checks the equality of string with object 11 boolean isEmpty() checks if string is empty 12 String concat(String str) concatinates specified string 13 String replace(char old, char new) replaces all occurrences of specified char value 14 String replace(CharSequence old, CharSequence new) replaces all occurrences of specified CharSequence 15 static String equalsIgnoreCase(String another) compares another string. It doesn't check case. 16 String[] split(String regex) returns splitted string matching regex 17 String[] split(String regex, int limit) returns splitted string matching regex and limit 18 String intern() returns interned string 19 int indexOf(int ch) returns specified char value index 20 int indexOf(int ch, int fromIndex) returns specified char value index starting with given index 21 int indexOf(String substring) returns specified substring index 22 int indexOf(String substring, int fromIndex) returns specified substring index starting with given index 23 String toLowerCase() returns string in lowercase. 24 String toLowerCase(Locale l) returns string in lowercase using specified locale. 25 String toUpperCase() returns string in uppercase. 26 String toUpperCase(Locale l) returns string in uppercase using specified locale. 27 String trim() removes beginning and ending spaces of this string. 28 static String valueOf(int value) converts given type into string. It is overloaded.
  • 24. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 22 StringBuffer Java StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed. Constructors of StringBuffer 1. StringBuffer(): creates an empty string buffer with the initial capacity of 16. 2. StringBuffer(String str): creates a string buffer with the specified string. 3. StringBuffer(int capacity): creates an empty string buffer with the specified capacity as length. Methods of StringBuffer 1. public synchronized StringBuffer append(String s): is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc. 2. public synchronized StringBuffer insert(int offset, String s): is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc. 3. public synchronized StringBuffer replace(int startIndex, int endIndex, String str): is used to replace the string from specified startIndex and endIndex. 4. public synchronized StringBuffer delete(int startIndex, int endIndex): is used to delete the string from specified startIndex and endIndex. 5. public synchronized StringBuffer reverse(): is used to reverse the string. 6. public int capacity(): is used to return the current capacity. 7. public void ensureCapacity(int minimumCapacity): is used to ensure the capacity at least equal to the given minimum. 8. public char charAt(int index): is used to return the character at the specified position. 9. public int length(): is used to return the length of the string i.e. total number of characters. 10. public String substring(int beginIndex): is used to return the substring from the specified beginIndex. 11. public String substring(int beginIndex, int endIndex): is used to return the substring from the specified beginIndex and endIndex. StringTokenizer
  • 25. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 23 The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to break string. It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like StreamTokenizer class. Constructors of StringTokenizer Constructor Description StringTokenizer(String str) creates StringTokenizer with specified string. StringTokenizer(String str, String delim) creates StringTokenizer with specified string and delimeter. StringTokenizer(String str, String delim, boolean returnValue) creates StringTokenizer with specified string, delimeter and returnValue. If return value is true, delimiter characters are considered to be tokens. If it is false, delimiter characters serve to separate tokens. Methods of StringTokenizer Public method Description boolean hasMoreTokens() checks if there is more tokens available. String nextToken() returns the next token from the StringTokenizer object. String nextToken(String delim) returns the next token based on the delimeter. boolean hasMoreElements() same as hasMoreTokens() method. Object nextElement() same as nextToken() but its return type is Object. int countTokens() returns the total number of tokens. Eg: import java.util.StringTokenizer; public class Simple{ public static void main(String args[]){ StringTokenizer st = new StringTokenizer("this is weit"," "); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } } } Op: this
  • 26. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 24 is weit Packages java.lang  The java.lang package contains classes that are fundamental to the design of the Java language. The most important classes are Object, which is the root of the class hierarchy, and Class, instances of which represent classes at run time.  Frequently it is necessary to represent a value of primitive type as if it were an object. The wrapper classes Boolean, Character, Integer, Long, Float, and Double serve this purpose. An object of type Double, for example, contains a field whose type is double, representing that value in such a way that a reference to it can be stored in a variable of reference type. These classes also provide a number of methods for converting among primitive values, as well as supporting such standard methods as equals and hashCode.  The class Math provides commonly used mathematical functions such as sine, cosine, and square root. The classes String and StringBuffer similarly provide commonly used operations on character strings.  Classes ClassLoader, Process, Runtime, SecurityManager, and System provide "system operations" that manage the dynamic loading of classes, creation of external processes, host environment inquiries such as the time of day, and enforcement of security policies. java.util  Java.util package contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes.  This reference will take you through simple and practical methods available in java.util package. java.io  Java I/O (Input and Output) is used to process the input and produce the output.  Java uses the concept of stream to make I/O operation fast. The java.io package contains all the classes required for input and output operations.  We can perform file handling in java by Java I/O API. java.sql  This package provides the APIs for accessing and processing data which is stored in the database especially relational database by using the java programming language. It
  • 27. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 25 includes a framework where we different drivers can be installed dynamically to access different databases especially relational databases. javax.swing  Swing is a GUI widget toolkit for Java. It is part of Oracle's Java Foundation Classes (JFC) – an API for providing a graphical user interface (GUI) for Java programs.  Swing was developed to provide a more sophisticated set of GUI components than the earlier Abstract Window Toolkit (AWT). Swing provides a native look and feel that emulates the look and feel of several platforms, and also supports a pluggable look and feel that allows applications to have a look and feel unrelated to the underlying platform. It has more powerful and flexible components than AWT. In addition to familiar components such as buttons, check boxes and labels, Swing provides several advanced components such as tabbed panel, scroll panes, trees, tables, and lists.  Unlike AWT components, Swing components are not implemented by platform-specific code. Instead, they are written entirely in Java and therefore are platform-independent. The term "lightweight" is used to describe such an element. User-defined-package  Java package created by user to categorized classes and interface //save as FirstProgram.java package LearnJava; public class FirstProgram{ public static void main(String args[]){ System.out.println("Welcome to package"); } } How to compile java package? javac -d . FirstProgram.java JAVA ACCESS SPECIFIERS
  • 28. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 26 The access to classes, constructors, methods and fields are regulated using access modifiers i.e. a class can control what information or data can be accessible by other classes. To take advantage of encapsulation, you should minimize access whenever possible. Java provides a number of access modifiers to help you set the level of access you want for classes as well as the fields, methods and constructors in your classes. A member has package or default accessibility when no accessibility modifier is specified. Access Modifiers 1.private 2.protected 3.default 4. public public access modifier Fields, methods and constructors declared public (least restrictive) within a public class are visible to any class in the Java program, whether these classes are in the same package or in another package. private access modifier The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods or constructors declared private are strictly controlled, which means they cannot be accesses by anywhere outside the enclosing class. A standard design strategy is to make all fields private and provide public getter methods for them. protected access modifier The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods and constructors declared protected in a superclass can be accessed only by subclasses in other packages. Classes in the same package can also access protected fields, methods and constructors as well, even if they are not a subclass of the protected member’s class. default access modifier Java provides a default specifier which is used when no access modifier is present. Any class, field, method or constructor that has no declared access modifier is accessible only by classes in the same package. The default modifier is not used for fields and methods within an interface.
  • 29. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 27 UNIT 2 Exception Handling An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled. An exception can occur for many different reasons. Following are some scenarios where an exception occurs.  A user has entered an invalid data.  A file that needs to be opened cannot be found.  A network connection has been lost in the middle of communications or the JVM has run out of memory. Exception Hierarchy All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class. Errors are abnormal conditions that happen in case of severe failures, these are not handled by the Java programs. Errors are generated to indicate errors generated by the runtime environment. Example: JVM is out of memory. Normally, programs cannot recover from errors. The Exception class has two main subclasses: IOException class and RuntimeException Class. Exceptions Methods Sr.No. Method & Description 1 public String getMessage() Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor. 2 public Throwable getCause()
  • 30. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 28 Returns the cause of the exception as represented by a Throwable object. 3 public String toString() Returns the name of the class concatenated with the result of getMessage(). 4 public void printStackTrace() Prints the result of toString() along with the stack trace to System.err, the error output stream. Catching Exceptions A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following − Syntax try { // Protected code }catch(ExceptionName e1) { // Catch block } The code which is prone to exceptions is placed in the try block. When an exception occurs, that exception occurred is handled by catch block associated with it. Multiple Catch Blocks A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following −
  • 31. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 29 try { // Protected code }catch(ExceptionType1 e1) { // Catch block }catch(ExceptionType2 e2) { // Catch block }catch(ExceptionType3 e3) { // Catch block } The previous statements demonstrate three catch blocks, but you can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack. try { file = new FileInputStream(fileName); x = (byte) file.read(); }catch(IOException i) { i.printStackTrace(); return -1; }catch(FileNotFoundException f) // Not valid! { f.printStackTrace(); return -1; } The Finally Block The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. A finally block appears at the end of the catch blocks and has the following syntax − try { // Protected code }catch(ExceptionType1 e1) { // Catch block }catch(ExceptionType2 e2) {
  • 32. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 30 // Catch block }catch(ExceptionType3 e3) { // Catch block }finally { // The finally block always executes. } The Throws/Throw Keywords If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature. You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. Try to understand the difference between throws and throw keywords, throws is used to postpone the handling of a checked exception and throw is used to invoke an exception explicitly. Example import java.io.*; public class className { public void deposit(double amount) throws RemoteException { // Method implementation throw new RemoteException(); } // Remainder of class definition } User-defined Exceptions You can create your own exceptions in Java. Keep the following points in mind when writing your own exception classes − All exceptions must be a child of Throwable. If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class. If you want to write a runtime exception, you need to extend the RuntimeException class. We can define our own Exception class as below −
  • 33. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 31 class MyException extends Exception { } Example class MyException extends Exception { public MyException(String message) { super(" - - - > "+message); } } class Semi { public static void main(String[] args) { try { throw new MyException("hello"); } catch(Exception x) { System.out.println(x); } } } Multithreading Process A process is an instance of a computer program that is executed sequentially. It is a collection of instructions which are executed simultaneously at the rum time. Thus several processes may be associated with the same program. For example, to check the spelling is a single process in the Word Processor program and you can also use other processes like printing, formatting, drawing, etc. associated with this program. Multiprocessing  Many task done simultaneously in PC.  Program is a set of instruction and a “A process is a running instance of a program.  In Multiprocessing OS implements CONTEXT SWITICHING mechanism.
  • 34. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 32  Here CPU is shared between different process: E.g. A MS-Word application and MS-Excel application is opened simultaneously or in general any two applications running simultaneously is multiprocessing. Thread  Thread is any part of the program under execution.  A thread is an entity within a process .  Example:in your java program main() is a thread and garbage collector is another thread.  When more than one thread execute concurrently in a single application, it is termed as “Multithreading”  Thread can be created in either of the following ways: 1. Extending Thread class. 2. Implementing Runnable Interface. 1. Extending the java.lang.Thread Class For creating a thread a class have to extend the Thread Class. For creating a thread by this procedure you have to follow these steps: 1. Extend the java.lang.Thread Class. 2. Override the run( ) method in the subclass from the Thread class to define the code executed by the thread. 3. Create an instance of this subclass. This subclass may call a Thread class constructor by subclass constructor. 4. Invoke the start( ) method on the instance of the class to make the thread eligible for running. 2. Implementing the java.lang.Runnable Interface The procedure for creating threads by implementing the Runnable Interface is as follows: 1. A Class implements the Runnable Interface, override the run() method to define the code executed by thread. An object of this class is Runnable Object. 2. Create an object of Thread Class by passing a Runnable object as argument. 3. Invoke the start( ) method on the instance of the Thread class. A thread is a lightweight process which exist within a program and executed to perform a special task. Several threads of execution may be associated with a single process. Thus a process that has only one thread is referred to as a single-threaded process, while a process with multiple threads is referred to as a multi-threaded process.
  • 35. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 33 In Java Programming language, thread is a sequential path of code execution within a program. Each thread has its own local variables, program counter and lifetime. In single threaded runtime environment, operations are executes sequentially i.e. next operation can execute only when the previous one is complete. It exists in a common memory space and can share both data and code of a program. Threading concept is very important in Java through which we can increase the speed of any application. You can see diagram shown below in which a thread is executed along with its several operations with in a single process. Main Thread When any standalone application is running, it firstly execute the main() method runs in a one thread, called the main thread. If no other threads are created by the main thread, then program terminates when the main() method complete its execution. The main thread creates some other threads called child threads. The main() method execution can finish, but the program will keep running until the all threads have complete its execution. WAP to demonstrate thread through Extending thread class. class thread1 { public static void main(String arg[]) { mythread mt=new mythread(); for(int i=1;i<=5;i++) { System.out.println(i); try { Thread.sleep(500); } catch(Exception e) {}
  • 36. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 34 } } } class mythread extends Thread { mythread() { start(); } public void run() { for(int i=11;i<=15;i++) { System.out.println(i); try { Thread.sleep(1000); } catch(Exception e) { } } } } Output:
  • 37. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 35 WAP to demonstrate thread by implementing Runnable Interface. class thread2 { public static void main(String arg[]) { mythread mt=new mythread(); for(int i=1;i<=5;i++) { System.out.println(i); try { Thread.sleep(500); } catch(Exception e){} } } } class mythread implements Runnable { Thread t; mythread() { t=new Thread(this); t.start(); } public void run() { for(int i=11;i<=15;i++) { System.out.println(i); try { Thread.sleep(1000); } catch(Exception e){} } } } Output:
  • 38. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 36 Constructor Thread() Allocates a new Thread object. Thread(Runnable target) Allocates a new Thread object. Thread(Runnable target,String name) Allocates a new Thread object. Thread(String name) Allocates a new Thread object. Thread(ThreadGroup group,Runnable target) Allocates a new Thread object. Thread(ThreadGroup group,Runnable target, String name) Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group. Thread(ThreadGroup group,Runnable target, String name,long stackSize) Allocates a new Thread object so that it has target as its run object, has the specified name as its name, belongs to the thread group referred to by group, and has the specified stack size. Thread(ThreadGroup group,String name) Allocates a new Thread object. Multithreading : Multithreading is a technique that allows a program or a process to execute many tasks concurrently (at the same time and parallel). It allows a process to run its tasks in parallel mode on a single processor system In the multithreading concept, several multiple lightweight processes are run in a single process/task or program by a single processor. For Example, When you use a word processor you perform a many different tasks such as printing, spell checking and so on. Multithreaded software treats each process as a separate program. In Java, the Java Virtual Machine (JVM) allows an application to have multiple threads of execution running concurrently. It allows a program to be more responsible to the user. When a
  • 39. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 37 program contains multiple threads then the CPU can switch between the two threads to execute them at the same time. For example, look at the diagram shown as: In this diagram, two threads are being executed having more than one task. The task of each thread is switched to the task of another thread. Advantages of multithreading over multitasking :  Reduces the computation time.  Improves performance of an application.  Threads share the same address space so it saves the memory.  Context switching between threads is usually less expensive than between processes.  Cost of communication between threads is relatively low. Life cycle of a thread  When you are programming with threads, understanding the life cycle of thread is very valuable.  While a thread is alive, it is in one of several states.  By invoking start() method, it doesn’t mean that the thread has access to CPU and start executing straight away. Several factors determine how it will proceed.
  • 40. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 38 1. Born state After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive. 2. Runnable (Ready-to-run) state A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also.On this state a thread is waiting for a turn on the processor. 3. Running state A thread is in running state that means the thread is currently executing.There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool. 4. Dead state A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again.
  • 41. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 39 5. Blocked, Suspended A thread can enter in this state because of waiting the resources that are hold by another thread. 6. Sleeping On this state, the thread is still alive but it is not runnable, it might be return to runnable state later, if a particular event occurs. On this state a thread sleeps for a specified amount of time. You can use the method sleep( ) to stop the running state of a thread. 7. Waiting A thread waits for notification from another thread.The thread sends back to runnable state after sending notification from another thread. Some Important Methods defined in java.lang.Thread are shown in the table: Method Return Type Description currentThread() Thread Returns an object reference to the thread in which it is invoked. getName( ) String Retrieve the name of the thread object or instance. start( ) Void Start the thread by calling its run method. run( ) Void This method is the entry point to execute thread, like the main method for applications. sleep( ) Void Suspends a thread for a specified amount of time (in milliseconds). isAlive( ) boolean This method is used to determine the thread is running or not. activeCount( ) int This method returns the number of active threads in a particular thread group and all its subgroups. interrupt( ) void The method interrupt the threads on which it is invoked. yield( ) void By invoking this method the current thread pause its execution temporarily and allow other threads to execute.
  • 42. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 40 join( ) void This method and join(long millisec) Throws InterruptedException. These two methods are invoked on a thread. These are not returned until either the thread has completed or it is timed out respectively. Synchronization  Sometimes, when two or more threads need shared resource, they need a proper mechanism to ensure that the resource will be used by only one thread at a time.  The mechanism we use to achieve this is known as thread synchronization.  The thread synchronization is achieved through the synchronized keyword. The statements which need to be synchronized should put into the synchronized block It is also known as critical section. WAP to demonstrate synchronization. class sync { public static void main(String arg[]) { share s=new share(); mythread mt1=new mythread(s); mythread mt2=new mythread(s); mythread mt3=new mythread(s); } } class mythread extends Thread { share p; mythread(share s) { p=s; start(); } public void run() { p.doword(Thread.currentThread().getName()); } } class share { public synchronized void doword(String str) { for(int i=1;i<=5;i++) {
  • 43. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 41 System.out.println(str); try { Thread.sleep(500); } catch(Exception e){} } } } Output: wait(), notify() and notifyAll()methods? wait() : It tells the calling thread to give up the lock and go to sleep until some other thread enters the same monitor and calls notify(). The wait() method releases the lock prior to waiting and reacquires the lock prior to returning from the wait() method. The wait() method is actually tightly integrated with the synchronization lock, using a feature not available directly from the synchronization mechanism. In other words, it is not possible for us to implement the wait() method purely in Java: it is a native method. General syntax for calling wait() method is like this: synchronized( lockObject ) { while( ! condition ) {
  • 44. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 42 lockObject.wait(); } //take the action here; } notify() : It wakes up one single thread that called wait() on the same object. It should be noted that calling notify() does not actually give up a lock on a resource. It tells a waiting thread that that thread can wake up. However, the lock is not actually given up until the notifier’s synchronized block has completed. So, if a notifier calls notify() on a resource but the notifier still needs to perform 10 seconds of actions on the resource within its synchronized block, the thread that had been waiting will need to wait at least another additional 10 seconds for the notifier to release the lock on the object, even though notify() had been called. General syntax for calling notify() method is like this: synchronized(lockObject) { //establish_the_condition; lockObject.notify(); //any additional code if needed } notifyAll() : It wakes up all the threads that called wait() on the same object. The highest priority thread will run first in most of the situation, though not guaranteed. Other things are same as notify() method above. General syntax for calling notify() method is like this: synchronized(lockObject) { establish_the_condition; lockObject.notifyAll(); } I/O streams The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The
  • 45. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 43 stream in the java.io package supports many data such as primitives, object, localized characters, etc. Stream A stream can be defined as a sequence of data. There are two kinds of Streams − InPutStream − The InputStream is used to read data from a source. OutPutStream − The OutputStream is used for writing data to a destination. Java provides strong but flexible support for I/O related to files and networks but this tutorial covers very basic functionality related to streams and I/O. We will see the most commonly used examples one by one − Byte Streams Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to byte streams but the most frequently used classes are, FileInputStream and FileOutputStream. Following is an example which makes use of these two classes to copy an input file into an output file − Example import java.io.*; public class CopyFile { public static void main(String args[]) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("input.txt"); out = new FileOutputStream("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c);
  • 46. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 44 } }finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } } Character Streams Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character streams are used to perform input and output for 16-bit unicode. Though there are many classes related to character streams but the most frequently used classes are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time. We can re-write the above example, which makes the use of these two classes to copy an input file (having unicode characters) into an output file − Example import java.io.*; public class CopyFile { public static void main(String args[]) throws IOException { FileReader in = null; FileWriter out = null; try { in = new FileReader("input.txt"); out = new FileWriter("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } }finally {
  • 47. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 45 if (in != null) { in.close(); } if (out != null) { out.close(); } } } } File Class Java File class represents the files and directory pathnames in an abstract manner. This class is used for creation of files and directories, file searching, file deletion, etc. The File object represents the actual file/directory on the disk. Following is the list of constructors to create a File object. Sr.No. Method & Description 1 File(File parent, String child) This constructor creates a new File instance from a parent abstract pathname and a child pathname string. 2 File(String pathname) This constructor creates a new File instance by converting the given pathname string into an abstract pathname. 3 File(String parent, String child) This constructor creates a new File instance from a parent pathname string and a child pathname string. 4 File(URI uri) This constructor creates a new File instance by converting the given file: URI into an abstract pathname. Once you have File object in hand, then there is a list of helper methods which can be used to manipulate the files. Sr.No. Method & Description 1 public String getName() Returns the name of the file or directory denoted by this abstract pathname. 2 public String getParent() Returns the pathname string of this abstract pathname's parent, or null if this
  • 48. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 46 pathname does not name a parent directory. 3 public String getPath() Converts this abstract pathname into a pathname string. 4 public String getAbsolutePath() Returns the absolute pathname string of this abstract pathname. 5 public boolean isDirectory() Tests whether the file denoted by this abstract pathname is a directory. Returns true if and only if the file denoted by this abstract pathname exists and is a directory; false otherwise. Random file access  Using a random access file, we can read from a file as well as write to the file.  Reading and writing using the file input and output streams are a sequential process.  Using a random access file, we can read or write at any position within the file.  An object of the RandomAccessFile class can do the random file access. We can read/write bytes and all primitive types values to a file.  RandomAccessFile can work with strings using its readUTF() and writeUTF() methods.  The RandomAccessFile class is not in the class hierarchy of the InputStream and OutputStream classes. Mode A random access file can be created in four different access modes. The access mode value is a string. They are listed as follows: Mode Meaning "r" The file is opened in a read-only mode. "rw" The file is opened in a read-write mode. The file is created if it does not exist. "rws" The file is opened in a read-write mode. Any modifications to the file's content and its metadata are written to the storage device immediately. "rwd" The file is opened in a read-write mode. Any modifications to the file's content are written to the storage device immediately.
  • 49. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 47 Read and Write We create an instance of the RandomAccessFile class by specifying the file name and the access mode. RandomAccessFile raf = new RandomAccessFile("randomtest.txt", "rw");  A random access file has a file pointer that moves forward when we read data from it or write data to it.  The file pointer is a cursor where our next read or write will start.  Its value indicates the distance of the cursor from the beginning of the file in bytes.  We can get the value of file pointer by using its getFilePointer() method.  When we create an object of the RandomAccessFile class, the file pointer is set to zero.  We can set the file pointer at a specific location in the file using the seek() method.  The length() method of a RandomAccessFile returns the current length of the file. We can extend or truncate a file by using its setLength() method. Example import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; public class Main { public static void main(String[] args) throws IOException { String fileName = "randomaccessfile.txt"; File fileObject = new File(fileName); if (!fileObject.exists()) { initialWrite(fileName); } readFile(fileName); readFile(fileName); } public static void readFile(String fileName) throws IOException { RandomAccessFile raf = new RandomAccessFile(fileName, "rw"); int counter = raf.readInt(); String msg = raf.readUTF(); System.out.println(counter); System.out.println(msg); incrementReadCounter(raf); raf.close(); }
  • 50. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 48 public static void incrementReadCounter(RandomAccessFile raf) throws IOException { long currentPosition = raf.getFilePointer(); raf.seek(0); int counter = raf.readInt(); counter++; raf.seek(0); raf.writeInt(counter); raf.seek(currentPosition); } public static void initialWrite(String fileName) throws IOException { RandomAccessFile raf = new RandomAccessFile(fileName, "rw"); raf.writeInt(0); raf.writeUTF("Hello world!"); raf.close(); } } Serialization Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object. After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory. Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform. Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object. To demonstrate how serialization works in Java, I am going to use the stud class which implements the Serializable interface − import java.io.*; public class NewClassSer { public static void main(String[] args) throws IOException, ClassNotFoundException {
  • 51. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 49 try{ //write stud std = new stud(); std.rollno = 10; std.name = "siddhesh"; FileOutputStream fos = new FileOutputStream("s.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(std); oos.close(); fos.close(); //---------------------------------------------------- //read FileInputStream fis = new FileInputStream("s.ser"); ObjectInputStream ois = new ObjectInputStream(fis); stud std1 = (stud)ois.readObject(); ois.close(); fis.close(); System.out.println(std1.name + " -- "+ std1.rollno); } catch(Exception x) { x.printStackTrace(); } } } class stud implements Serializable { public int rollno; public String name; } Networking
  • 52. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 50  Computers running on the Internet communicate to each other using either the Transmission Control Protocol (TCP) or the User Datagram Protocol (UDP).  When you write Java programs that communicate over the network, you are programming at the application layer.  Typically, you don't need to concern yourself with the TCP and UDP layers. Instead, you can use the classes in the java.net package.  These classes provide system-independent network communication. TCP  TCP (Transmission Control Protocol) is a connection-based protocol that provides a reliable flow of data between two computers.  When two applications want to communicate to each other reliably, they establish a connection and send data back and forth over that connection.  This is analogous to making a telephone call. If you want to speak to Aunt Beatrice in Kentucky, a connection is established when you dial her phone number and she answers. You send data back and forth over the connection by speaking to one another over the phone lines.  TCP provides a point-to-point channel for applications that require reliable communications.  The Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all examples of applications that require a reliable communication channel. UDP  UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival. UDP is not connection-based like TCP.  Sending datagrams is much like sending a letter through the postal service: The order of delivery is not important and is not guaranteed, and each message is independent of any other.  Many firewalls and routers have been configured not to allow UDP packets. If you're having trouble connecting to a service outside your firewall, or if clients are having trouble connecting to your service, ask your system administrator if UDP is permitted. Ports  A computer has a single physical connection to the network. All data destined for a particular computer arrives through that connection.
  • 53. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 51  However, the data may be intended for different applications running on the computer. So how does the computer know to which application to forward the data?  Through the use of ports.  Data transmitted over the Internet is accompanied by addressing information that identifies the computer and the port for which it is destined.  The computer is identified by its 32-bit IP address, which IP uses to deliver data to the right computer on the network.  Ports are identified by a 16-bit number, which TCP and UDP use to deliver the data to the right application.  In connection-based communication such as TCP, a server application binds a socket to a specific port number. In datagram-based communication such as UDP, the datagram packet contains the port number of its destination and UDP routes the packet to the appropriate application, as illustrated in this figure:
  • 54. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 52 Working with URL  URL is the acronym for Uniform Resource Locator.  It is a reference (an address) to a resource on the Internet.  You provide URLs to your favorite Web browser so that it can locate files on the Internet in the same way that you provide addresses on letters so that the post office can locate your correspondents.  A URL has two main components:  Protocol identifier: For the URL http://example.com, the protocol identifier is http.  Resource name: For the URL http://example.com, the resource name is example.com. The resource name is the complete address to the resource. The format of the resource name depends entirely on the protocol used, but for many protocols, including HTTP, the resource name contains one or more of the following components: • Host Name: The name of the machine on which the resource lives. • Filename: The pathname to the file on the machine. • Port Number: The port number to which to connect (typically optional). • Reference: A reference to a named anchor within a resource that usually identifies a specific location within a file (typically optional). What Is a Socket?  A socket is one endpoint of a two-way communication link between two programs running on the network.  A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.
  • 55. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 53 Normally, a server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits, listening to the socket for a client to make a connection request. On the client-side: The client knows the hostname of the machine on which the server is running and the port number on which the server is listening. To make a connection request, the client tries to rendezvous with the server on the server's machine and port. The client also needs to identify itself to the server so it binds to a local port number that it will use during this connection. This is usually assigned by the system. If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bound to the same local port and also has its remote endpoint set to the address and port of the client. It needs a new socket so that it can continue to listen to the original socket for connection requests while tending to the needs of the connected client. On the client side, if the connection is accepted, a socket is successfully created and the client can use the socket to communicate with the server. The client and server can now communicate by writing to or reading from their sockets. Socket Class The java.net.Socket class represents the socket that both the client and the server use to communicate with each other. The client obtains a Socket object by instantiating one, whereas the server obtains a Socket object from the return value of the accept() method. The Socket class has five constructors Sr.No. Method & Description 1 public Socket(String host, int port) throws UnknownHostException, IOException. This method attempts to connect to the specified server at the specified port. If this constructor does not throw an exception, the connection is successful and the client is connected to the server. 2 public Socket(InetAddress host, int port) throws IOException This method is identical to the previous constructor, except that the host is denoted
  • 56. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 54 by an InetAddress object. 3 public Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException. Connects to the specified host and port, creating a socket on the local host at the specified address and port. 4 public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException. This method is identical to the previous constructor, except that the host is denoted by an InetAddress object instead of a String. 5 public Socket() Creates an unconnected socket. Use the connect() method to connect this socket to a server. When the Socket constructor returns, it does not simply instantiate a Socket object but it actually attempts to connect to the specified server and port. Some methods of interest in the Socket class are listed here. Notice that both the client and the server have a Socket object, so these methods can be invoked by both the client and the server. Sr.No. Method & Description 1 public void connect(SocketAddress host, int timeout) throws IOException This method connects the socket to the specified host. This method is needed only when you instantiate the Socket using the no-argument constructor. 2 public InetAddress getInetAddress() This method returns the address of the other computer that this socket is connected to. 3 public int getPort() Returns the port the socket is bound to on the remote machine. 4 public void close() throws IOException Closes the socket, which makes this Socket object no longer capable of connecting again to any server. ServerSocket Class The java.net.ServerSocket class is used by server applications to obtain a port and listen for client requests. The ServerSocket class has four constructors Sr.No. Method & Description
  • 57. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 55 1 public ServerSocket(int port) throws IOException Attempts to create a server socket bound to the specified port. An exception occurs if the port is already bound by another application. 2 public ServerSocket(int port, int backlog) throws IOException Similar to the previous constructor, the backlog parameter specifies how many incoming clients to store in a wait queue. 3 public ServerSocket(int port, int backlog, InetAddress address) throws IOException Similar to the previous constructor, the InetAddress parameter specifies the local IP address to bind to. The InetAddress is used for servers that may have multiple IP addresses, allowing the server to specify which of its IP addresses to accept client requests on. 4 public ServerSocket() throws IOException Creates an unbound server socket. When using this constructor, use the bind() method when you are ready to bind the server socket. Following are some of the common methods of the ServerSocket class Sr.No. Method & Description 1 public int getLocalPort() Returns the port that the server socket is listening on. This method is useful if you passed in 0 as the port number in a constructor and let the server find a port for you. 2 public Socket accept() throws IOException Waits for an incoming client. This method blocks until either a client connects to the server on the specified port or the socket times out, assuming that the time-out value has been set using the setSoTimeout() method. Otherwise, this method blocks indefinitely. 3 public void setSoTimeout(int timeout) Sets the time-out value for how long the server socket waits for a client during the accept(). 4 public void bind(SocketAddress host, int backlog) Binds the socket to the specified server and port in the SocketAddress object. Use this method if you have instantiated the ServerSocket using the no-argument constructor. Write a TCP uni-direction Socket programming. //Server file import java.net.*; import java.io.*; class server {
  • 58. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 56 public static void main(String[] args) throws Exception { int portno=1234; ServerSocket ss= new ServerSocket(portno); System.out.println("waiting for client to connect..."); Socket s=ss.accept(); System.out.println("Client Connected......"); BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream())); String str; while ((str=br.readLine())!=null) { System.out.println(str); } } } //Client file import java.net.*; import java.io.*; class client { public static void main(String[] args) throws Exception { int portno=1234; InetAddress ip=InetAddress.getByName(null); Socket x=new Socket(ip,portno); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw=new PrintWriter(new OutputStreamWriter(x.getOutputStream())); String str; while ((str=br.readLine())!=null) { pw.println(str); pw.flush(); } } }
  • 59. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 57 Output: Write a TCP bi-directional Socket programming. //Client file import java.net.*; import java.io.*; class client1 { public static void main(String[] args) throws Exception { int portno=1234; InetAddress ip=InetAddress.getByName(null); Socket x=new Socket(ip,portno); BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  • 60. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 58 BufferedReader br1=new BufferedReader(new InputStreamReader(x.getInputStream())); PrintWriter pw=new PrintWriter(new OutputStreamWriter(x.getOutputStream())); String str=br.readLine(); pw.println(str); pw.flush(); str=br1.readLine(); System.out.println(str); } } // Server file import java.net.*; import java.io.*; class server1 { public static void main(String[] args) throws Exception { int portno=1234; ServerSocket ss= new ServerSocket(portno); System.out.println("waiting for client to connect..."); Socket s=ss.accept(); System.out.println("Client Connected......"); BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream())); PrintWriter pw=new PrintWriter(new OutputStreamWriter(s.getOutputStream())); String str=br.readLine(); int num=Integer.parseInt(str); pw.println("square is " + num*num); pw.flush(); } } Output:
  • 61. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 59
  • 62. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 60 UNIT 3 Wrapper class in Java Wrapper class in java provides the mechanism to convert primitive into object and object into primitive. Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and object into primitive automatically. The automatic conversion of primitive into object is known as autoboxing and vice-versa unboxing. The eight classes of java.lang package are known as wrapper classes in java. The list of eight wrapper classes are given below: Primitive Type Wrapper class boolean Boolean char Character byte Byte short Short int Integer long Long float Float double Double Example: Primitive to Wrapper int a=20; Integer i=Integer.valueOf(a);//converting int into Integer Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internal ly Example: Wrapper to Primitive Integer a=new Integer(3); int i=a.intValue();//converting Integer to int int j=a;//unboxing, now compiler will write a.intValue() internally
  • 63. SYBSC-CS (SEM 3 CORE JAVA NOTES) FOR PROGRAMS REFER CLASSROOM NOTES WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS ADDRESS: 302 PARANJPE UDYOG BHAVAN, ABOVE KHANDELWAL SWEETS, THANE STATION ROAD(W) PHONE : 8097071144/8097071155 61 Collection Framework: The Java collections framework (JCF) is a set of classes and interfaces that implement commonly reusable collection data structures Collections and arrays are similar in that they both hold references to objects and they can be managed as a group. However, unlike arrays, collections do not need to be assigned a certain capacity when instantiated. Collections can also grow and shrink in size automatically when objects are added or removed. Collections cannot hold basic data type elements (primitive types) such as int, long, or double; instead, they hold Wrapper Classes such as Integer, Long, or Double. Almost all collections in Java are derived from the java.util.Collection interface. Collection defines the basic parts of all collections. The interface states the add() and remove() methods for adding to and removing from a collection respectively. Also required is the toArray() method, which converts the collection into a simple array of all the elements in the collection. Finally, the contains() method checks if a specified element is in the collection. util packages and interfaces